PageSourceSearch

https://angelofailla.com/js/pdf-js/build/pdf.js

js angelofailla.com collected 2026-10-04 22:21:15 UTC 500,693 bytes, 15,792 lines download raw bytes

vendor: 4,479 bytes, lines 1-104
1/**
2 * @licstart The following is the entire license notice for the
3 * JavaScript code in this page
4 *
5 * Copyright 2023 Mozilla Foundation
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 *     http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * @licend The above is the entire license notice for the
20 * JavaScript code in this page
21 */
22
23(function webpackUniversalModuleDefinition(root, factory) {
24	if(typeof exports === 'object' && typeof module === 'object')
25		module.exports = factory();
26	else if(typeof define === 'function' && define.amd)
27		define("pdfjs-dist/build/pdf", [], factory);
28	else if(typeof exports === 'object')
29		exports["pdfjs-dist/build/pdf"] = factory();
30	else
31		root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
32})(globalThis, () => {
33return /******/ (() => { // webpackBootstrap
34/******/ 	"use strict";
35/******/ 	var __webpack_modules__ = ([
36/* 0 */,
37/* 1 */
38/***/ ((__unused_webpack_module, exports) => {
39
40
41
42Object.defineProperty(exports, "__esModule", ({
43  value: true
44}));
45exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.LINE_FACTOR = exports.LINE_DESCENT_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.BASELINE_FACTOR = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationEditorType = exports.AnnotationEditorPrefix = exports.AnnotationEditorParamsType = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
46exports.assert = assert;
47exports.bytesToString = bytesToString;
48exports.createPromiseCapability = createPromiseCapability;
49exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
50exports.getModificationDate = getModificationDate;
51exports.getVerbosityLevel = getVerbosityLevel;
52exports.info = info;
53exports.isArrayBuffer = isArrayBuffer;
54exports.isArrayEqual = isArrayEqual;
55exports.objectFromMap = objectFromMap;
56exports.objectSize = objectSize;
57exports.setVerbosityLevel = setVerbosityLevel;
58exports.shadow = shadow;
59exports.string32 = string32;
60exports.stringToBytes = stringToBytes;
61exports.stringToPDFString = stringToPDFString;
62exports.stringToUTF8String = stringToUTF8String;
63exports.unreachable = unreachable;
64exports.utf8StringToString = utf8StringToString;
65exports.warn = warn;
66;
67const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
68exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
69const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
70exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
71const LINE_FACTOR = 1.35;
72exports.LINE_FACTOR = LINE_FACTOR;
73const LINE_DESCENT_FACTOR = 0.35;
74exports.LINE_DESCENT_FACTOR = LINE_DESCENT_FACTOR;
75const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
76exports.BASELINE_FACTOR = BASELINE_FACTOR;
77const RenderingIntentFlag = {
78  ANY: 0x01,
79  DISPLAY: 0x02,
80  PRINT: 0x04,
81  SAVE: 0x08,
82  ANNOTATIONS_FORMS: 0x10,
83  ANNOTATIONS_STORAGE: 0x20,
84  ANNOTATIONS_DISABLE: 0x40,
85  OPLIST: 0x100
86};
87exports.RenderingIntentFlag = RenderingIntentFlag;
88const AnnotationMode = {
89  DISABLE: 0,
90  ENABLE: 1,
91  ENABLE_FORMS: 2,
92  ENABLE_STORAGE: 3
93};
94exports.AnnotationMode = AnnotationMode;
95const AnnotationEditorPrefix = "pdfjs_internal_editor_";
96exports.AnnotationEditorPrefix = AnnotationEditorPrefix;
97const AnnotationEditorType = {
98  DISABLE: -1,
99  NONE: 0,
100  FREETEXT: 3,
101  INK: 15
102};
103exports.AnnotationEditorType = AnnotationEditorType;
104const AnnotationEditorParamsType = {
105  FREETEXT_SIZE: 1,
106  FREETEXT_COLOR: 2,
107  FREETEXT_OPACITY: 3,
108  INK_COLOR: 11,
109  INK_THICKNESS: 12,
110  INK_OPACITY: 13
111};
112exports.AnnotationEditorParamsType = AnnotationEditorParamsType;
113const PermissionFlag = {
114  PRINT: 0x04,
115  MODIFY_CONTENTS: 0x08,
116  COPY: 0x10,
117  MODIFY_ANNOTATIONS: 0x20,
118  FILL_INTERACTIVE_FORMS: 0x100,
119  COPY_FOR_ACCESSIBILITY: 0x200,
120  ASSEMBLE: 0x400,
121  PRINT_HIGH_QUALITY: 0x800
122};
123exports.PermissionFlag = PermissionFlag;
124const TextRenderingMode = {
125  FILL: 0,
126  STROKE: 1,
127  FILL_STROKE: 2,
128  INVISIBLE: 3,
129  FILL_ADD_TO_PATH: 4,
130  STROKE_ADD_TO_PATH: 5,
131  FILL_STROKE_ADD_TO_PATH: 6,
132  ADD_TO_PATH: 7,
133  FILL_STROKE_MASK: 3,
134  ADD_TO_PATH_FLAG: 4
135};
136exports.TextRenderingMode = TextRenderingMode;
137const ImageKind = {
138  GRAYSCALE_1BPP: 1,
139  RGB_24BPP: 2,
140  RGBA_32BPP: 3
141};
142exports.ImageKind = ImageKind;
143const AnnotationType = {
144  TEXT: 1,
145  LINK: 2,
146  FREETEXT: 3,
147  LINE: 4,
148  SQUARE: 5,
149  CIRCLE: 6,
150  POLYGON: 7,
151  POLYLINE: 8,
152  HIGHLIGHT: 9,
153  UNDERLINE: 10,
154  SQUIGGLY: 11,
155  STRIKEOUT: 12,
156  STAMP: 13,
157  CARET: 14,
158  INK: 15,
159  POPUP: 16,
160  FILEATTACHMENT: 17,
161  SOUND: 18,
162  MOVIE: 19,
163  WIDGET: 20,
164  SCREEN: 21,
165  PRINTERMARK: 22,
166  TRAPNET: 23,
167  WATERMARK: 24,
168  THREED: 25,
169  REDACT: 26
170};
171exports.AnnotationType = AnnotationType;
172const AnnotationStateModelType = {
173  MARKED: "Marked",
174  REVIEW: "Review"
175};
176exports.AnnotationStateModelType = AnnotationStateModelType;
177const AnnotationMarkedState = {
178  MARKED: "Marked",
179  UNMARKED: "Unmarked"
180};
181exports.AnnotationMarkedState = AnnotationMarkedState;
182const AnnotationReviewState = {
183  ACCEPTED: "Accepted",
184  REJECTED: "Rejected",
185  CANCELLED: "Cancelled",
186  COMPLETED: "Completed",
187  NONE: "None"
188};
189exports.AnnotationReviewState = AnnotationReviewState;
190const AnnotationReplyType = {
191  GROUP: "Group",
192  REPLY: "R"
193};
194exports.AnnotationReplyType = AnnotationReplyType;
195const AnnotationFlag = {
196  INVISIBLE: 0x01,
197  HIDDEN: 0x02,
198  PRINT: 0x04,
199  NOZOOM: 0x08,
200  NOROTATE: 0x10,
201  NOVIEW: 0x20,
202  READONLY: 0x40,
203  LOCKED: 0x80,
204  TOGGLENOVIEW: 0x100,
205  LOCKEDCONTENTS: 0x200
206};
207exports.AnnotationFlag = AnnotationFlag;
208const AnnotationFieldFlag = {
209  READONLY: 0x0000001,
210  REQUIRED: 0x0000002,
211  NOEXPORT: 0x0000004,
212  MULTILINE: 0x0001000,
213  PASSWORD: 0x0002000,
214  NOTOGGLETOOFF: 0x0004000,
215  RADIO: 0x0008000,
216  PUSHBUTTON: 0x0010000,
217  COMBO: 0x0020000,
218  EDIT: 0x0040000,
219  SORT: 0x0080000,
220  FILESELECT: 0x0100000,
221  MULTISELECT: 0x0200000,
222  DONOTSPELLCHECK: 0x0400000,
223  DONOTSCROLL: 0x0800000,
224  COMB: 0x1000000,
225  RICHTEXT: 0x2000000,
226  RADIOSINUNISON: 0x2000000,
227  COMMITONSELCHANGE: 0x4000000
228};
229exports.AnnotationFieldFlag = AnnotationFieldFlag;
230const AnnotationBorderStyleType = {
231  SOLID: 1,
232  DASHED: 2,
233  BEVELED: 3,
234  INSET: 4,
235  UNDERLINE: 5
236};
237exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
238const AnnotationActionEventType = {
239  E: "Mouse Enter",
240  X: "Mouse Exit",
241  D: "Mouse Down",
242  U: "Mouse Up",
243  Fo: "Focus",
244  Bl: "Blur",
245  PO: "PageOpen",
246  PC: "PageClose",
247  PV: "PageVisible",
248  PI: "PageInvisible",
249  K: "Keystroke",
250  F: "Format",
251  V: "Validate",
252  C: "Calculate"
253};
254exports.AnnotationActionEventType = AnnotationActionEventType;
255const DocumentActionEventType = {
256  WC: "WillClose",
257  WS: "WillSave",
258  DS: "DidSave",
259  WP: "WillPrint",
260  DP: "DidPrint"
261};
262exports.DocumentActionEventType = DocumentActionEventType;
263const PageActionEventType = {
264  O: "PageOpen",
265  C: "PageClose"
266};
267exports.PageActionEventType = PageActionEve
vendor: 7,289 bytes, lines 267-560
267ntType;
268const VerbosityLevel = {
269  ERRORS: 0,
270  WARNINGS: 1,
271  INFOS: 5
272};
273exports.VerbosityLevel = VerbosityLevel;
274const CMapCompressionType = {
275  NONE: 0,
276  BINARY: 1
277};
278exports.CMapCompressionType = CMapCompressionType;
279const OPS = {
280  dependency: 1,
281  setLineWidth: 2,
282  setLineCap: 3,
283  setLineJoin: 4,
284  setMiterLimit: 5,
285  setDash: 6,
286  setRenderingIntent: 7,
287  setFlatness: 8,
288  setGState: 9,
289  save: 10,
290  restore: 11,
291  transform: 12,
292  moveTo: 13,
293  lineTo: 14,
294  curveTo: 15,
295  curveTo2: 16,
296  curveTo3: 17,
297  closePath: 18,
298  rectangle: 19,
299  stroke: 20,
300  closeStroke: 21,
301  fill: 22,
302  eoFill: 23,
303  fillStroke: 24,
304  eoFillStroke: 25,
305  closeFillStroke: 26,
306  closeEOFillStroke: 27,
307  endPath: 28,
308  clip: 29,
309  eoClip: 30,
310  beginText: 31,
311  endText: 32,
312  setCharSpacing: 33,
313  setWordSpacing: 34,
314  setHScale: 35,
315  setLeading: 36,
316  setFont: 37,
317  setTextRenderingMode: 38,
318  setTextRise: 39,
319  moveText: 40,
320  setLeadingMoveText: 41,
321  setTextMatrix: 42,
322  nextLine: 43,
323  showText: 44,
324  showSpacedText: 45,
325  nextLineShowText: 46,
326  nextLineSetSpacingShowText: 47,
327  setCharWidth: 48,
328  setCharWidthAndBounds: 49,
329  setStrokeColorSpace: 50,
330  setFillColorSpace: 51,
331  setStrokeColor: 52,
332  setStrokeColorN: 53,
333  setFillColor: 54,
334  setFillColorN: 55,
335  setStrokeGray: 56,
336  setFillGray: 57,
337  setStrokeRGBColor: 58,
338  setFillRGBColor: 59,
339  setStrokeCMYKColor: 60,
340  setFillCMYKColor: 61,
341  shadingFill: 62,
342  beginInlineImage: 63,
343  beginImageData: 64,
344  endInlineImage: 65,
345  paintXObject: 66,
346  markPoint: 67,
347  markPointProps: 68,
348  beginMarkedContent: 69,
349  beginMarkedContentProps: 70,
350  endMarkedContent: 71,
351  beginCompat: 72,
352  endCompat: 73,
353  paintFormXObjectBegin: 74,
354  paintFormXObjectEnd: 75,
355  beginGroup: 76,
356  endGroup: 77,
357  beginAnnotation: 80,
358  endAnnotation: 81,
359  paintImageMaskXObject: 83,
360  paintImageMaskXObjectGroup: 84,
361  paintImageXObject: 85,
362  paintInlineImageXObject: 86,
363  paintInlineImageXObjectGroup: 87,
364  paintImageXObjectRepeat: 88,
365  paintImageMaskXObjectRepeat: 89,
366  paintSolidColorImageMask: 90,
367  constructPath: 91
368};
369exports.OPS = OPS;
370const UNSUPPORTED_FEATURES = {
371  forms: "forms",
372  javaScript: "javaScript",
373  signatures: "signatures",
374  smask: "smask",
375  shadingPattern: "shadingPattern",
376  errorTilingPattern: "errorTilingPattern",
377  errorExtGState: "errorExtGState",
378  errorXObject: "errorXObject",
379  errorFontLoadType3: "errorFontLoadType3",
380  errorFontState: "errorFontState",
381  errorFontMissing: "errorFontMissing",
382  errorFontTranslate: "errorFontTranslate",
383  errorColorSpace: "errorColorSpace",
384  errorOperatorList: "errorOperatorList",
385  errorFontToUnicode: "errorFontToUnicode",
386  errorFontLoadNative: "errorFontLoadNative",
387  errorFontBuildPath: "errorFontBuildPath",
388  errorFontGetPath: "errorFontGetPath",
389  errorMarkedContent: "errorMarkedContent",
390  errorContentSubStream: "errorContentSubStream"
391};
392exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
393const PasswordResponses = {
394  NEED_PASSWORD: 1,
395  INCORRECT_PASSWORD: 2
396};
397exports.PasswordResponses = PasswordResponses;
398let verbosity = VerbosityLevel.WARNINGS;
399function setVerbosityLevel(level) {
400  if (Number.isInteger(level)) {
401    verbosity = level;
402  }
403}
404function getVerbosityLevel() {
405  return verbosity;
406}
407function info(msg) {
408  if (verbosity >= VerbosityLevel.INFOS) {
409    console.log(`Info: ${msg}`);
410  }
411}
412function warn(msg) {
413  if (verbosity >= VerbosityLevel.WARNINGS) {
414    console.log(`Warning: ${msg}`);
415  }
416}
417function unreachable(msg) {
418  throw new Error(msg);
419}
420function assert(cond, msg) {
421  if (!cond) {
422    unreachable(msg);
423  }
424}
425function _isValidProtocol(url) {
426  if (!url) {
427    return false;
428  }
429  switch (url.protocol) {
430    case "http:":
431    case "https:":
432    case "ftp:":
433    case "mailto:":
434    case "tel:":
435      return true;
436    default:
437      return false;
438  }
439}
440function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
441  if (!url) {
442    return null;
443  }
444  try {
445    if (options && typeof url === "string") {
446      if (options.addDefaultProtocol && url.startsWith("www.")) {
447        const dots = url.match(/\./g);
448        if (dots && dots.length >= 2) {
449          url = `http://${url}`;
450        }
451      }
452      if (options.tryConvertEncoding) {
453        try {
454          url = stringToUTF8String(url);
455        } catch (ex) {}
456      }
457    }
458    const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
459    if (_isValidProtocol(absoluteUrl)) {
460      return absoluteUrl;
461    }
462  } catch (ex) {}
463  return null;
464}
465function shadow(obj, prop, value, nonSerializable = false) {
466  Object.defineProperty(obj, prop, {
467    value,
468    enumerable: !nonSerializable,
469    configurable: true,
470    writable: false
471  });
472  return value;
473}
474const BaseException = function BaseExceptionClosure() {
475  function BaseException(message, name) {
476    if (this.constructor === BaseException) {
477      unreachable("Cannot initialize BaseException.");
478    }
479    this.message = message;
480    this.name = name;
481  }
482  BaseException.prototype = new Error();
483  BaseException.constructor = BaseException;
484  return BaseException;
485}();
486exports.BaseException = BaseException;
487class PasswordException extends BaseException {
488  constructor(msg, code) {
489    super(msg, "PasswordException");
490    this.code = code;
491  }
492}
493exports.PasswordException = PasswordException;
494class UnknownErrorException extends BaseException {
495  constructor(msg, details) {
496    super(msg, "UnknownErrorException");
497    this.details = details;
498  }
499}
500exports.UnknownErrorException = UnknownErrorException;
501class InvalidPDFException extends BaseException {
502  constructor(msg) {
503    super(msg, "InvalidPDFException");
504  }
505}
506exports.InvalidPDFException = InvalidPDFException;
507class MissingPDFException extends BaseException {
508  constructor(msg) {
509    super(msg, "MissingPDFException");
510  }
511}
512exports.MissingPDFException = MissingPDFException;
513class UnexpectedResponseException extends BaseException {
514  constructor(msg, status) {
515    super(msg, "UnexpectedResponseException");
516    this.status = status;
517  }
518}
519exports.UnexpectedResponseException = UnexpectedResponseException;
520class FormatError extends BaseException {
521  constructor(msg) {
522    super(msg, "FormatError");
523  }
524}
525exports.FormatError = FormatError;
526class AbortException extends BaseException {
527  constructor(msg) {
528    super(msg, "AbortException");
529  }
530}
531exports.AbortException = AbortException;
532function bytesToString(bytes) {
533  if (typeof bytes !== "object" || bytes === null || bytes.length === undefined) {
534    unreachable("Invalid argument for bytesToString");
535  }
536  const length = bytes.length;
537  const MAX_ARGUMENT_COUNT = 8192;
538  if (length < MAX_ARGUMENT_COUNT) {
539    return String.fromCharCode.apply(null, bytes);
540  }
541  const strBuf = [];
542  for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
543    const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
544    const chunk = bytes.subarray(i, chunkEnd);
545    strBuf.push(String.fromCharCode.apply(null, chunk));
546  }
547  return strBuf.join("");
548}
549function stringToBytes(str) {
550  if (typeof str !== "string") {
551    unreachable("Invalid argument for stringToBytes");
552  }
553  const length = str.length;
554  const bytes = new Uint8Array(length);
555  for (let i = 0; i < length; ++i) {
556    bytes[i] = str.charCodeAt(i) & 0xff;
557  }
558  return bytes;
559}
560function 
vendor: 7,924 bytes, lines 560-789
560string32(value) {
561  return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
562}
563function objectSize(obj) {
564  return Object.keys(obj).length;
565}
566function objectFromMap(map) {
567  const obj = Object.create(null);
568  for (const [key, value] of map) {
569    obj[key] = value;
570  }
571  return obj;
572}
573function isLittleEndian() {
574  const buffer8 = new Uint8Array(4);
575  buffer8[0] = 1;
576  const view32 = new Uint32Array(buffer8.buffer, 0, 1);
577  return view32[0] === 1;
578}
579function isEvalSupported() {
580  try {
581    new Function("");
582    return true;
583  } catch (e) {
584    return false;
585  }
586}
587class FeatureTest {
588  static get isLittleEndian() {
589    return shadow(this, "isLittleEndian", isLittleEndian());
590  }
591  static get isEvalSupported() {
592    return shadow(this, "isEvalSupported", isEvalSupported());
593  }
594  static get isOffscreenCanvasSupported() {
595    return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
596  }
597  static get platform() {
598    if (typeof navigator === "undefined") {
599      return shadow(this, "platform", {
600        isWin: false,
601        isMac: false
602      });
603    }
604    return shadow(this, "platform", {
605      isWin: navigator.platform.includes("Win"),
606      isMac: navigator.platform.includes("Mac")
607    });
608  }
609}
610exports.FeatureTest = FeatureTest;
611const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
612class Util {
613  static makeHexColor(r, g, b) {
614    return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
615  }
616  static scaleMinMax(transform, minMax) {
617    let temp;
618    if (transform[0]) {
619      if (transform[0] < 0) {
620        temp = minMax[0];
621        minMax[0] = minMax[1];
622        minMax[1] = temp;
623      }
624      minMax[0] *= transform[0];
625      minMax[1] *= transform[0];
626      if (transform[3] < 0) {
627        temp = minMax[2];
628        minMax[2] = minMax[3];
629        minMax[3] = temp;
630      }
631      minMax[2] *= transform[3];
632      minMax[3] *= transform[3];
633    } else {
634      temp = minMax[0];
635      minMax[0] = minMax[2];
636      minMax[2] = temp;
637      temp = minMax[1];
638      minMax[1] = minMax[3];
639      minMax[3] = temp;
640      if (transform[1] < 0) {
641        temp = minMax[2];
642        minMax[2] = minMax[3];
643        minMax[3] = temp;
644      }
645      minMax[2] *= transform[1];
646      minMax[3] *= transform[1];
647      if (transform[2] < 0) {
648        temp = minMax[0];
649        minMax[0] = minMax[1];
650        minMax[1] = temp;
651      }
652      minMax[0] *= transform[2];
653      minMax[1] *= transform[2];
654    }
655    minMax[0] += transform[4];
656    minMax[1] += transform[4];
657    minMax[2] += transform[5];
658    minMax[3] += transform[5];
659  }
660  static transform(m1, m2) {
661    return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
662  }
663  static applyTransform(p, m) {
664    const xt = p[0] * m[0] + p[1] * m[2] + m[4];
665    const yt = p[0] * m[1] + p[1] * m[3] + m[5];
666    return [xt, yt];
667  }
668  static applyInverseTransform(p, m) {
669    const d = m[0] * m[3] - m[1] * m[2];
670    const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
671    const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
672    return [xt, yt];
673  }
674  static getAxialAlignedBoundingBox(r, m) {
675    const p1 = Util.applyTransform(r, m);
676    const p2 = Util.applyTransform(r.slice(2, 4), m);
677    const p3 = Util.applyTransform([r[0], r[3]], m);
678    const p4 = Util.applyTransform([r[2], r[1]], m);
679    return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
680  }
681  static inverseTransform(m) {
682    const d = m[0] * m[3] - m[1] * m[2];
683    return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
684  }
685  static singularValueDecompose2dScale(m) {
686    const transpose = [m[0], m[2], m[1], m[3]];
687    const a = m[0] * transpose[0] + m[1] * transpose[2];
688    const b = m[0] * transpose[1] + m[1] * transpose[3];
689    const c = m[2] * transpose[0] + m[3] * transpose[2];
690    const d = m[2] * transpose[1] + m[3] * transpose[3];
691    const first = (a + d) / 2;
692    const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
693    const sx = first + second || 1;
694    const sy = first - second || 1;
695    return [Math.sqrt(sx), Math.sqrt(sy)];
696  }
697  static normalizeRect(rect) {
698    const r = rect.slice(0);
699    if (rect[0] > rect[2]) {
700      r[0] = rect[2];
701      r[2] = rect[0];
702    }
703    if (rect[1] > rect[3]) {
704      r[1] = rect[3];
705      r[3] = rect[1];
706    }
707    return r;
708  }
709  static intersect(rect1, rect2) {
710    const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
711    const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
712    if (xLow > xHigh) {
713      return null;
714    }
715    const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
716    const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
717    if (yLow > yHigh) {
718      return null;
719    }
720    return [xLow, yLow, xHigh, yHigh];
721  }
722  static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
723    const tvalues = [],
724      bounds = [[], []];
725    let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
726    for (let i = 0; i < 2; ++i) {
727      if (i === 0) {
728        b = 6 * x0 - 12 * x1 + 6 * x2;
729        a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
730        c = 3 * x1 - 3 * x0;
731      } else {
732        b = 6 * y0 - 12 * y1 + 6 * y2;
733        a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
734        c = 3 * y1 - 3 * y0;
735      }
736      if (Math.abs(a) < 1e-12) {
737        if (Math.abs(b) < 1e-12) {
738          continue;
739        }
740        t = -c / b;
741        if (0 < t && t < 1) {
742          tvalues.push(t);
743        }
744        continue;
745      }
746      b2ac = b * b - 4 * c * a;
747      sqrtb2ac = Math.sqrt(b2ac);
748      if (b2ac < 0) {
749        continue;
750      }
751      t1 = (-b + sqrtb2ac) / (2 * a);
752      if (0 < t1 && t1 < 1) {
753        tvalues.push(t1);
754      }
755      t2 = (-b - sqrtb2ac) / (2 * a);
756      if (0 < t2 && t2 < 1) {
757        tvalues.push(t2);
758      }
759    }
760    let j = tvalues.length,
761      mt;
762    const jlen = j;
763    while (j--) {
764      t = tvalues[j];
765      mt = 1 - t;
766      bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
767      bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
768    }
769    bounds[0][jlen] = x0;
770    bounds[1][jlen] = y0;
771    bounds[0][jlen + 1] = x3;
772    bounds[1][jlen + 1] = y3;
773    bounds[0].length = bounds[1].length = jlen + 2;
774    return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
775  }
776}
777exports.Util = Util;
778const PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 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, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac];
779function stringToPDFString(str) {
780  if (str[0] >= "\xEF") {
781    let encoding;
782    if (str[0] === "\xFE" && str[1] === "\xFF") {
783      encoding = "utf-16be";
784    } else if (str[0] === "\xFF" && str[1] === "\xFE") {
785      encoding = "utf-16le";
786    } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
787      encoding = "utf-8";
788    }
789    if (encoding) {
790      try {
791        const decoder = new TextDecoder(encoding, {
792          fatal: true
793        });
794        const buffer = stringToBytes(str);
795        return decoder.decode(buffer);
796      } catch (ex) {
797        warn(`stringToPDFString: "${ex}".`);
798      }
799    }
800  }
801  const strBuf = [];
802  for (let i = 0, ii = str.length; i < ii; i++) {
803    const code = PDFStringTranslateTable[str.charCodeAt(i)];
804    strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
805  }
806  return strBuf.join("");
807}
808function stringToUTF8String(str) {
809  return decodeURIComponent(escape(str));
810}
811function utf8StringToString(str) {
812  return unescape(encodeURIComponent(str));
813}
814function isArrayBuffer(v) {
815  return typeof v === "object" && v !== null && v.byteLength !== undefined;
816}
817function isArrayEqual(arr1, arr2) {
818  if (arr1.length !== arr2.length) {
819    return false;
820  }
821  for (let i = 0, ii = arr1.length; i < ii; i++) {
822    if (arr1[i] !== arr2[i]) {
823      return false;
824    }
825  }
826  return true;
827}
828function getModificationDate(date = new Date()) {
829  const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
830  return buffer.join("");
831}
832function createPromiseCapability() {
833  const capability = Object.create(null);
834  let isSettled = false;
835  Object.defineProperty(capability, "settled", {
836    get() {
837      return isSettled;
838    }
839  });
840  capability.promise = new Promise(function (resolve, reject) {
841    capability.resolve = function (data) {
842      isSettled = true;
843      resolve(data);
844    };
845    capability.reject = function (reason) {
846      isSettled = true;
847      reject(reason);
848    };
849  });
850  return capability;
851}
852
853/***/ }),
854/* 2 */
855/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
856
857
858
859Object.defineProperty(exports, "__esModule", ({
860  value: true
861}));
862exports.build = exports.RenderTask = exports.PDFWorkerUtil = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
863exports.getDocument = getDocument;
864exports.version = void 0;
865var _util = __w_pdfjs_require__(1);
866var _annotation_storage = __w_pdfjs_require__(3);
867var _display_utils = __w_pdfjs_require__(6);
868var _font_loader = __w_pdfjs_require__(9);
869var _canvas = __w_pdfjs_require__(11);
870var _worker_options = __w_pdfjs_require__(14);
871var _is_node = __w_pdfjs_require__(10);
872var _message_handler = __w_pdfjs_require__(15);
873var _metadata = __w_pdfjs_require__(16);
874var _optional_content_config = __w_pdfjs_require__(17);
875var _transport_stream = __w_pdfjs_require__(18);
876var _xfa_text = __w_pdfjs_require__(19);
877const DEFAULT_RANGE_CHUNK_SIZE = 65536;
878const RENDERING_CANCELLED_TIMEOUT = 100;
879let DefaultCanvasFactory = _display_utils.DOMCanvasFactory;
880exports.DefaultCanvasFactory = DefaultCanvasFactory;
881let DefaultCMapReaderFactory = _display_utils.DOMCMapReaderFactory;
882exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
883let DefaultStandardFontDataFactory = _display_utils.DOMStandardFontDataFactory;
884exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
885if (_is_node.isNodeJS) {
886  const {
887    NodeCanvasFactory,
888    NodeCMapReaderFactory,
889    NodeStandardFontDataFactory
890  } = __w_pdfjs_require__(20);
891  exports.DefaultCanvasFactory = DefaultCanvasFactory = NodeCanvasFactory;
892  exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory = NodeCMapReaderFactory;
893  exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory = NodeStandardFontDataFactory;
894}
895let createPDFNetworkStream;
896{
897  if (_is_node.isNodeJS) {
898    const {
899      PDFNodeStream
900    } = __w_pdfjs_require__(21);
901    createPDFNetworkStream = params => {
902      return new PDFNodeStream(params);
903    };
904  } else {
905    const {
906      PDFNetworkStream
907    } = __w_pdfjs_require__(24);
908    const {
909      PDFFetchStream
910    } = __w_pdfjs_require__(25);
911    createPDFNetworkStream = params => {
912      return (0, _display_utils.isValidFetchUrl)(params.url) ? new PDFFetchStream(params) : new PDFNetworkStream(params);
913    };
914  }
915}
916function getDocument(src) {
917  if (typeof src === "string" || src instanceof URL) {
918    src = {
919      url: src
920    };
921  } else if ((0, _util.isArrayBuffer)(src)) {
922    src = {
923      data: src
924    };
925  } else if (src instanceof PDFDataRangeTransport) {
926    (0, _display_utils.deprecated)("`PDFDataRangeTransport`-instance, " + "please use a parameter object with `range`-property instead.");
927    src = {
928      range: src
929    };
930  } else {
931    if (typeof src !== "object") {
932      throw new Error("Invalid parameter in getDocument, " + "need either string, URL, TypedArray, or parameter object.");
933    }
934  }
935  if (!src.url && !src.data && !src.range) {
936    throw new Error("Invalid parameter object: need either .data, .range or .url");
937  }
938  const task = new PDFDocumentLoadingTask();
939  const url = src.url ? getUrlProp(src.url) : null;
940  const data = src.data ? getDataProp(src.data) : null;
941  const httpHeaders = src.httpHeaders || null;
942  const withCredentials = src.withCredentials === true;
943  const password = src.password ?? null;
944  const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
945  const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE;
946  let worker = src.worker instanceof PDFWorker ? src.worker : null;
947  const verbosity = src.verbosity;
948  const docBaseUrl = typeof src.docBaseUrl === "string" && !(0, _display_utils.isDataScheme)(src.docBaseUrl) ? src.docBaseUrl : null;
949  const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null;
950  const cMapPacked = src.cMapPacked !== false;
951  const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;
952  const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null;
953  const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory;
954  const ignoreErrors = src.stopAtErrors !== true;
955  const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
956  const isEvalSupported = src.isEvalSupported !== false;
957  const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !_is_node.isNodeJS;
958  const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : _is_node.isNodeJS;
959  const fontExtraProperties = src.fontExtraProperties === true;
960  const enableXfa = src.enableXfa === true;
961  const ownerDocument = src.ownerDocument || globalThis.document;
962  const disableRange = src.disableRange === true;
963  const disableStream = src.disableStream === true;
964  const disableAutoFetch = src.disableAutoFetch === true;
965  const pdfBug = src.pdfBug === true;
966  const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
967  const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !_is_node.isNodeJS && !disableFontFace;
968  const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === _display_utils.DOMCMapReaderFactory && StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory && (0, _display_utils.isValidFetchUrl)(cMapUrl, document.baseURI) && (0, _display_utils.isValidFetchUrl)(standardFontDataUrl, document.baseURI);
969  const styleElement = null;
970  (0, _util.setVerbosityLevel)(verbosity);
971  const transportFactory = useWorkerFetch ? null : {
972    cMapReaderFactory: new CMapReaderFactory({
973      baseUrl: cMapUrl,
974      isCompressed: cMapPacked
975    }),
976    standardFontDataFactory: new StandardFontDataFactory({
977      baseUrl: standardFontDataUrl
978    })
979  };
980  if (!worker) {
981    const workerParams = {
982      verbosity,
983      port: _worker_options.GlobalWorkerOptions.workerPort
984    };
985    worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
986    task._worker = worker;
987  }
988  const docId = task.docId;
989  const fetchDocParams = {
990    docId,
991    apiVersion: '3.4.120',
992    data,
993    password,
994    disableAutoFetch,
995    rangeChunkSize,
996    length,
997    docBaseUrl,
998    enableXfa,
999    evaluatorOptions: {
1000      maxImageSize,
1001      disableFontFace,
1002      ignoreErrors,
1003      isEvalSupported,
1004      isOffscreenCanvasSupported,
1005      fontExtraProperties,
1006      useSystemFonts,
1007      cMapUrl: useWorkerFetch ? cMapUrl : null,
1008      standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null
1009    }
1010  };
1011  const transportParams = {
1012    ignoreErrors,
1013    isEvalSupported,
1014    disableFontFace,
1015    fontExtraProperties,
1016    enableXfa,
1017    ownerDocument,
1018    disableAutoFetch,
1019    pdfBug,
1020    styleElement
1021  };
1022  worker.promise.then(function () {
1023    if (task.destroyed) {
1024      throw new Error("Loading aborted");
1025    }
1026    const workerIdPromise = _fetchDocument(worker, fetchDocParams);
1027    const networkStreamPromise = new Promise(function (resolve) {
1028      let networkStream;
1029      if (rangeTransport) {
1030        networkStream = new _transport_stream.PDFDataTransportStream({
1031          length,
1032          initialData: rangeTransport.initialData,
1033          progressiveDone: rangeTransport.progressiveDone,
1034          contentDispositionFilename: rangeTransport.contentDispositionFilename,
1035          disableRange,
1036          disableStream
1037        }, rangeTransport);
1038      } else if (!data) {
1039        networkStream = createPDFNetworkStream({
1040          url,
1041          length,
1042          httpHeaders,
1043          withCredentials,
1044          rangeChunkSize,
1045          disableRange,
1046          disableStream
1047        });
1048      }
1049      resolve(networkStream);
1050    });
1051    return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
1052      if (task.destroyed) {
1053        throw new Error("Loading aborted");
1054      }
1055      const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
1056      const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
1057      task._transport = transport;
1058      messageHandler.send("Ready", null);
1059    });
1060  }).catch(task._capability.reject);
1061  return task;
1062}
1063async function _fetchDocument(worker, source) {
1064  if (worker.destroyed) {
1065    throw new Error("Worker was destroyed");
1066  }
1067  const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", source, source.data ? [source.data.buffer] : null);
1068  if (worker.destroyed) {
1069    throw new Error("Worker was destroyed");
1070  }
1071  return workerId;
1072}
1073function getUrlProp(val) {
1074  if (val instanceof URL) {
1075    return val.href;
1076  }
1077  try {
1078    return new URL(val, window.location).href;
1079  } catch (ex) {
1080    if (_is_node.isNodeJS && typeof val === "string") {
1081      return val;
1082    }
1083  }
1084  throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
1085}
1086function getDataProp(val) {
1087  if (_is_node.isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
1088    (0, _display_utils.deprecated)("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
1089    return new Uint8Array(val);
1090  }
1091  if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
1092    return val;
1093  }
1094  if (typeof val === "string") {
1095    return (0, _util.stringToBytes)(val);
1096  }
1097  if (typeof val === "object" && !isNaN(val?.length) || (0, _util.isArrayBuffer)(val)) {
1098    return new Uint8Array(val);
1099  }
1100  throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
1101}
1102class PDFDocumentLoadingTask {
1103  static #docId = 0;
1104  #onUnsupportedFeature = null;
1105  constructor() {
1106    this._capability = (0, _util.createPromiseCapability)();
1107    this._transport = null;
1108    this._worker = null;
1109    this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
1110    this.destroyed = false;
1111    this.onPassword = null;
1112    this.onProgress = null;
1113  }
1114  get onUnsupportedFeature() {
1115    return this.#onUnsupportedFeature;
1116  }
1117  set onUnsupportedFeature(callback) {
1118    (0, _display_utils.deprecated)("The PDFDocumentLoadingTask onUnsupportedFeature property will be removed in the future.");
1119    this.#onUnsupportedFeature = callback;
1120  }
1121  get promise() {
1122    return this._capability.promise;
1123  }
1124  async destroy() {
1125    this.destroyed = true;
1126    await this._transport?.destroy();
1127    this._transport = null;
1128    if (this._worker) {
1129      this._worker.destroy();
1130      this._worker = null;
1131    }
1132  }
1133}
1134exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
1135class PDFDataRangeTransport {
1136  constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
1137    this.length = length;
1138    this.initialData = initialData;
1139    this.progressiveDone = progressiveDone;
1140    this.contentDispositionFilename = contentDispositionFilename;
1141    this._rangeListeners = [];
1142    this._progressListeners = [];
1143    this._progressiveReadListeners = [];
1144    this._progressiveDoneListeners = [];
1145    this._readyCapability = (0, _util.createPromiseCapability)();
1146  }
1147  addRangeListener(listener) {
1148    this._rangeListeners.push(listener);
1149  }
1150  addProgressListener(listener) {
1151    this._progressListeners.push(listener);
1152  }
1153  addProgressiveReadListener(listener) {
1154    this._progressiveReadListeners.push(listener);
1155  }
1156  addProgressiveDoneListener(listener) {
1157    this._progressiveDoneListeners.push(listener);
1158  }
1159  onDataRange(begin, chunk) {
1160    for (const listener of this._rangeListeners) {
1161      listener(begin, chunk);
1162    }
1163  }
1164  onDataProgress(loaded, total) {
1165    this._readyCapability.promise.then(() => {
1166      for (const listener of this._progressListeners) {
1167        listener(loaded, total);
1168      }
1169    });
1170  }
1171  onDataProgressiveRead(chunk) {
1172    this._readyCapability.promise.then(() => {
1173      for (const listener of this._progressiveReadListeners) {
1174        listener(chunk);
1175      }
1176    });
1177  }
1178  onDataProgressiveDone() {
1179    this._readyCapability.promise.then(() => {
1180      for (const listener of this._progressiveDoneListeners) {
1181        listener();
1182      }
1183    });
1184  }
1185  transportReady() {
1186    this._readyCapability.resolve();
1187  }
1188  requestDataRange(begin, end) {
1189    (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
1190  }
1191  abort() {}
1192}
1193exports.PDFDataRangeTransport = PDFDataRangeTransport;
1194class PDFDocumentProxy {
1195  constructor(pdfInfo, transport) {
1196    this._pdfInfo = pdfInfo;
1197    this._transport = transport;
1198  }
1199  get annotationStorage() {
1200    return this._transport.annotationStorage;
1201  }
1202  get numPages() {
1203    return this._pdfInfo.numPages;
1204  }
1205  get fingerprints() {
1206    return this._pdfInfo.fingerprints;
1207  }
1208  get isPureXfa() {
1209    return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
1210  }
1211  get allXfaHtml() {
1212    return this._transport._htmlForXfa;
1213  }
1214  getPage(pageNumber) {
1215    return this._transport.getPage(pageNumber);
1216  }
1217  getPageIndex(ref) {
1218    return this._transport.getPageIndex(ref);
1219  }
1220  getDestinations() {
1221    return this._transport.getDestinations();
1222  }
1223  getDestination(id) {
1224    return this._transport.getDestination(id);
1225  }
1226  getPageLabels() {
1227    return this._transport.getPageLabels();
1228  }
1229  getPageLayout() {
1230    return this._transport.getPageLayout();
1231  }
1232  getPageMode() {
1233    return this._transport.getPageMode();
1234  }
1235  getViewerPreferences() {
1236    return this._transport.getViewerPreferences();
1237  }
1238  getOpenAction() {
1239    return this._transport.getOpenAction();
1240  }
1241  getAttachments() {
1242    return this._transport.getAttachments();
1243  }
1244  getJavaScript() {
1245    return this._transport.getJavaScript();
1246  }
1247  getJSActions() {
1248    return this._transport.getDocJSActions();
1249  }
1250  getOutline() {
1251    return this._transport.getOutline();
1252  }
1253  getOptionalContentConfig() {
1254    return this._transport.getOptionalContentConfig();
1255  }
1256  getPermissions() {
1257    return this._transport.getPermissions();
1258  }
1259  getMetadata() {
1260    return this._transport.getMetadata();
1261  }
1262  getMarkInfo() {
1263    return this._transport.getMarkInfo();
1264  }
1265  getData() {
1266    return this._transport.getData();
1267  }
1268  saveDocument() {
1269    return this._transport.saveDocument();
1270  }
1271  getDownloadInfo() {
1272    return this._transport.downloadInfoCapability.promise;
1273  }
1274  cleanup(keepLoadedFonts = false) {
1275    return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
1276  }
1277  destroy() {
1278    return this.loadingTask.destroy();
1279  }
1280  get loadingParams() {
1281    return this._transport.loadingParams;
1282  }
1283  get loadingTask() {
1284    return this._transport.loadingTask;
1285  }
1286  getFieldObjects() {
1287    return this._transport.getFieldObjects();
1288  }
1289  hasJSActions() {
1290    return this._transport.hasJSActions();
1291  }
1292  getCalculationOrderIds() {
1293    return this._transport.getCalculationOrderIds();
1294  }
1295}
1296exports.PDFDocumentProxy = PDFDocumentProxy;
1297class PDFPageProxy {
1298  constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
1299    this._pageIndex = pageIndex;
1300    this._pageInfo = pageInfo;
1301    this._ownerDocument = ownerDocument;
1302    this._transport = transport;
1303    this._stats = pdfBug ? new _display_utils.StatTimer() : null;
1304    this._pdfBug = pdfBug;
1305    this.commonObjs = transport.commonObjs;
1306    this.objs = new PDFObjects();
1307    this.cleanupAfterRender = false;
1308    this.pendingCleanup = false;
1309    this._intentStates = new Map();
1310    this.destroyed = false;
1311  }
1312  get pageNumber() {
1313    return this._pageIndex + 1;
1314  }
1315  get rotate() {
1316    return this._pageInfo.rotate;
1317  }
1318  get ref() {
1319    return this._pageInfo.ref;
1320  }
1321  get userUnit() {
1322    return this._pageInfo.userUnit;
1323  }
1324  get view() {
1325    return this._pageInfo.view;
1326  }
1327  getViewport({
1328    scale,
1329    rotation = this.rotate,
1330    offsetX = 0,
1331    offsetY = 0,
1332    dontFlip = false
1333  } = {}) {
1334    return new _display_utils.PageViewport({
1335      viewBox: this.view,
1336      scale,
1337      rotation,
1338      offsetX,
1339      offsetY,
1340      dontFlip
1341    });
1342  }
1343  getAnnotations({
1344    intent = "display"
1345  } = {}) {
1346    const intentArgs = this._transport.getRenderingIntent(intent);
1347    return this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
1348  }
1349  getJSActions() {
1350    return this._transport.getPageJSActions(this._pageIndex);
1351  }
1352  get isPureXfa() {
1353    return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
1354  }
1355  async getXfa() {
1356    return this._transport._htmlForXfa?.children[this._pageIndex] || null;
1357  }
1358  render({
1359    canvasContext,
1360    viewport,
1361    intent = "display",
1362    annotationMode = _util.AnnotationMode.ENABLE,
1363    transform = null,
1364    canvasFactory = null,
1365    background = null,
1366    optionalContentConfigPromise = null,
1367    annotationCanvasMap = null,
1368    pageColors = null,
1369    printAnnotationStorage = null
1370  }) {
1371    this._stats?.time("Overall");
1372    const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage);
1373    this.pendingCleanup = false;
1374    if (!optionalContentConfigPromise) {
1375      optionalContentConfigPromise = this._transport.getOptionalContentConfig();
1376    }
1377    let intentState = this._intentStates.get(intentArgs.cacheKey);
1378    if (!intentState) {
1379      intentState = Object.create(null);
1380      this._intentStates.set(intentArgs.cacheKey, intentState);
1381    }
1382    if (intentState.streamReaderCancelTimeout) {
1383      clearTimeout(intentState.streamReaderCancelTimeout);
1384      intentState.streamReaderCancelTimeout = null;
1385    }
1386    const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
1387      ownerDocument: this._ownerDocument
1388    });
1389    const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
1390    if (!intentState.displayReadyCapability) {
1391      intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
1392      intentState.operatorList = {
1393        fnArray: [],
1394        argsArray: [],
1395        lastChunk: false,
1396        separateAnnots: null
1397      };
1398      this._stats?.time("Page Request");
1399      this._pumpOperatorList(intentArgs);
1400    }
1401    const complete = error => {
1402      intentState.renderTasks.delete(internalRenderTask);
1403      if (this.cleanupAfterRender || intentPrint) {
1404        this.pendingCleanup = true;
1405      }
1406      this._tryCleanup();
1407      if (error) {
1408        internalRenderTask.capability.reject(error);
1409        this._abortOperatorList({
1410          intentState,
1411          reason: error instanceof Error ? error : new Error(error)
1412        });
1413      } else {
1414        internalRenderTask.capability.resolve();
1415      }
1416      this._stats?.timeEnd("Rendering");
1417      this._stats?.timeEnd("Overall");
1418    };
1419    const internalRenderTask = new InternalRenderTask({
1420      callback: complete,
1421      params: {
1422        canvasContext,
1423        viewport,
1424        transform,
1425        background
1426      },
1427      objs: this.objs,
1428      commonObjs: this.commonObjs,
1429      annotationCanvasMap,
1430      operatorList: intentState.operatorList,
1431      pageIndex: this._pageIndex,
1432      canvasFactory: canvasFactoryInstance,
1433      useRequestAnimationFrame: !intentPrint,
1434      pdfBug: this._pdfBug,
1435      pageColors
1436    });
1437    (intentState.renderTasks ||= new Set()).add(internalRenderTask);
1438    const renderTask = internalRenderTask.task;
1439    Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
1440      if (this.pendingCleanup) {
1441        complete();
1442        return;
1443      }
1444      this._stats?.time("Rendering");
1445      internalRenderTask.initializeGraphics({
1446        transparency,
1447        optionalContentConfig
1448      });
1449      internalRenderTask.operatorListChanged();
1450    }).catch(complete);
1451    return renderTask;
1452  }
1453  getOperatorList({
1454    intent = "display",
1455    annotationMode = _util.AnnotationMode.ENABLE,
1456    printAnnotationStorage = null
1457  } = {}) {
1458    function operatorListChanged() {
1459      if (intentState.operatorList.lastChunk) {
1460        intentState.opListReadCapability.resolve(intentState.operatorList);
1461        intentState.renderTasks.delete(opListTask);
1462      }
1463    }
1464    const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true);
1465    let intentState = this._intentStates.get(intentArgs.cacheKey);
1466    if (!intentState) {
1467      intentState = Object.create(null);
1468      this._intentStates.set(intentArgs.cacheKey, intentState);
1469    }
1470    let opListTask;
1471    if (!intentState.opListReadCapability) {
1472      opListTask = Object.create(null);
1473      opListTask.operatorListChanged = operatorListChanged;
1474      intentState.opListReadCapability = (0, _util.createPromiseCapability)();
1475      (intentState.renderTasks ||= new Set()).add(opListTask);
1476      intentState.operatorList = {
1477        fnArray: [],
1478        argsArray: [],
1479        lastChunk: false,
1480        separateAnnots: null
1481      };
1482      this._stats?.time("Page Request");
1483      this._pumpOperatorList(intentArgs);
1484    }
1485    return intentState.opListReadCapability.promise;
1486  }
1487  streamTextContent({
1488    disableCombineTextItems = false,
1489    includeMarkedContent = false
1490  } = {}) {
1491    const TEXT_CONTENT_CHUNK_SIZE = 100;
1492    return this._transport.messageHandler.sendWithStream("GetTextContent", {
1493      pageIndex: this._pageIndex,
1494      combineTextItems: disableCombineTextItems !== true,
1495      includeMarkedContent: includeMarkedContent === true
1496    }, {
1497      highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
1498      size(textContent) {
1499        return textContent.items.length;
1500      }
1501    });
1502  }
1503  getTextContent(params = {}) {
1504    if (this._transport._htmlForXfa) {
1505      return this.getXfa().then(xfa => {
1506        return _xfa_text.XfaText.textContent(xfa);
1507      });
1508    }
1509    const readableStream = this.streamTextContent(params);
1510    return new Promise(function (resolve, reject) {
1511      function pump() {
1512        reader.read().then(function ({
1513          value,
1514          done
1515        }) {
1516          if (done) {
1517            resolve(textContent);
1518            return;
1519          }
1520          Object.assign(textContent.styles, value.styles);
1521          textContent.items.push(...value.items);
1522          pump();
1523        }, reject);
1524      }
1525      const reader = readableStream.getReader();
1526      const textContent = {
1527        items: [],
1528        styles: Object.create(null)
1529      };
1530      pump();
1531    });
1532  }
1533  getStructTree() {
1534    return this._transport.getStructTree(this._pageIndex);
1535  }
1536  _destroy() {
1537    this.destroyed = true;
1538    const waitOn = [];
1539    for (const intentState of this._intentStates.values()) {
1540      this._abortOperatorList({
1541        intentState,
1542        reason: new Error("Page was destroyed."),
1543        force: true
1544      });
1545      if (intentState.opListReadCapability) {
1546        continue;
1547      }
1548      for (const internalRenderTask of intentState.renderTasks) {
1549        waitOn.push(internalRenderTask.completed);
1550        internalRenderTask.cancel();
1551      }
1552    }
1553    this.objs.clear();
1554    this.pendingCleanup = false;
1555    return Promise.all(waitOn);
1556  }
1557  cleanup(resetStats = false) {
1558    this.pendingCleanup = true;
1559    return this._tryCleanup(resetStats);
1560  }
1561  _tryCleanup(resetStats = false) {
1562    if (!this.pendingCleanup) {
1563      return false;
1564    }
1565    for (const {
1566      renderTasks,
1567      operatorList
1568    } of this._intentStates.values()) {
1569      if (renderTasks.size > 0 || !operatorList.lastChunk) {
1570        return false;
1571      }
1572    }
1573    this._intentStates.clear();
1574    this.objs.clear();
1575    if (resetStats && this._stats) {
1576      this._stats = new _display_utils.StatTimer();
1577    }
1578    this.pendingCleanup = false;
1579    return true;
1580  }
1581  _startRenderPage(transparency, cacheKey) {
1582    const intentState = this._intentStates.get(cacheKey);
1583    if (!intentState) {
1584      return;
1585    }
1586    this._stats?.timeEnd("Page Request");
1587    intentState.displayReadyCapability?.resolve(transparency);
1588  }
1589  _renderPageChunk(operatorListChunk, intentState) {
1590    for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
1591      intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
1592      intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
1593    }
1594    intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
1595    intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
1596    for (const internalRenderTask of intentState.renderTasks) {
1597      internalRenderTask.operatorListChanged();
1598    }
1599    if (operatorListChunk.lastChunk) {
1600      this._tryCleanup();
1601    }
1602  }
1603  _pumpOperatorList({
1604    renderingIntent,
1605    cacheKey,
1606    annotationStorageMap
1607  }) {
1608    const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
1609      pageIndex: this._pageIndex,
1610      intent: renderingIntent,
1611      cacheKey,
1612      annotationStorage: annotationStorageMap
1613    });
1614    const reader = readableStream.getReader();
1615    const intentState = this._intentStates.get(cacheKey);
1616    intentState.streamReader = reader;
1617    const pump = () => {
1618      reader.read().then(({
1619        value,
1620        done
1621      }) => {
1622        if (done) {
1623          intentState.streamReader = null;
1624          return;
1625        }
1626        if (this._transport.destroyed) {
1627          return;
1628        }
1629        this._renderPageChunk(value, intentState);
1630        pump();
1631      }, reason => {
1632        intentState.streamReader = null;
1633        if (this._transport.destroyed) {
1634          return;
1635        }
1636        if (intentState.operatorList) {
1637          intentState.operatorList.lastChunk = true;
1638          for (const internalRenderTask of intentState.renderTasks) {
1639            internalRenderTask.operatorListChanged();
1640          }
1641          this._tryCleanup();
1642        }
1643        if (intentState.displayReadyCapability) {
1644          intentState.displayReadyCapability.reject(reason);
1645        } else if (intentState.opListReadCapability) {
1646          intentState.opListReadCapability.reject(reason);
1647        } else {
1648          throw reason;
1649        }
1650      });
1651    };
1652    pump();
1653  }
1654  _abortOperatorList({
1655    intentState,
1656    reason,
1657    force = false
1658  }) {
1659    if (!intentState.streamReader) {
1660      return;
1661    }
1662    if (intentState.streamReaderCancelTimeout) {
1663      clearTimeout(intentState.streamReaderCancelTimeout);
1664      intentState.streamReaderCancelTimeout = null;
1665    }
1666    if (!force) {
1667      if (intentState.renderTasks.size > 0) {
1668        return;
1669      }
1670      if (reason instanceof _display_utils.RenderingCancelledException) {
1671        let delay = RENDERING_CANCELLED_TIMEOUT;
1672        if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
1673          delay += reason.extraDelay;
1674        }
1675        intentState.streamReaderCancelTimeout = setTimeout(() => {
1676          intentState.streamReaderCancelTimeout = null;
1677          this._abortOperatorList({
1678            intentState,
1679            reason,
1680            force: true
1681          });
1682        }, delay);
1683        return;
1684      }
1685    }
1686    intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
1687    intentState.streamReader = null;
1688    if (this._transport.destroyed) {
1689      return;
1690    }
1691    for (const [curCacheKey, curIntentState] of this._intentStates) {
1692      if (curIntentState === intentState) {
1693        this._intentStates.delete(curCacheKey);
1694        break;
1695      }
1696    }
1697    this.cleanup();
1698  }
1699  get stats() {
1700    return this._stats;
1701  }
1702}
1703exports.PDFPageProxy = PDFPageProxy;
1704class LoopbackPort {
1705  #listeners = new Set();
1706  #deferred = Promise.resolve();
1707  postMessage(obj, transfers) {
1708    const event = {
1709      data: structuredClone(obj, transfers)
1710    };
1711    this.#deferred.then(() => {
1712      for (const listener of this.#listeners) {
1713        listener.call(this, event);
1714      }
1715    });
1716  }
1717  addEventListener(name, listener) {
1718    this.#listeners.add(listener);
1719  }
1720  removeEventListener(name, listener) {
1721    this.#listeners.delete(listener);
1722  }
1723  terminate() {
1724    this.#listeners.clear();
1725  }
1726}
1727exports.LoopbackPort = LoopbackPort;
1728const PDFWorkerUtil = {
1729  isWorkerDisabled: false,
1730  fallbackWorkerSrc: null,
1731  fakeWorkerId: 0
1732};
1733exports.PDFWorkerUtil = PDFWorkerUtil;
1734{
1735  if (_is_node.isNodeJS && typeof require === "function") {
1736    PDFWorkerUtil.isWorkerDisabled = true;
1737    PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
1738  } else if (typeof document === "object") {
1739    const pdfjsFilePath = document?.currentScript?.src;
1740    if (pdfjsFilePath) {
1741      PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".w
1741orker$1$2");
1742    }
1743  }
1744  PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
1745    let base;
1746    try {
1747      base = new URL(baseUrl);
1748      if (!base.origin || base.origin === "null") {
1749        return false;
1750      }
1751    } catch (e) {
1752      return false;
1753    }
1754    const other = new URL(otherUrl, base);
1755    return base.origin === other.origin;
1756  };
1757  PDFWorkerUtil.createCDNWrapper = function (url) {
1758    const wrapper = `importScripts("${url}");`;
1759    return URL.createObjectURL(new Blob([wrapper]));
1760  };
1761}
1762class PDFWorker {
1763  static #workerPorts = new WeakMap();
1764  constructor({
1765    name = null,
1766    port = null,
1767    verbosity = (0, _util.getVerbosityLevel)()
1768  } = {}) {
1769    if (port && PDFWorker.#workerPorts.has(port)) {
1770      throw new Error("Cannot use more than one PDFWorker per port.");
1771    }
1772    this.name = name;
1773    this.destroyed = false;
1774    this.verbosity = verbosity;
1775    this._readyCapability = (0, _util.createPromiseCapability)();
1776    this._port = null;
1777    this._webWorker = null;
1778    this._messageHandler = null;
1779    if (port) {
1780      PDFWorker.#workerPorts.set(port, this);
1781      this._initializeFromPort(port);
1782      return;
1783    }
1784    this._initialize();
1785  }
1786  get promise() {
1787    return this._readyCapability.promise;
1788  }
1789  get port() {
1790    return this._port;
1791  }
1792  get messageHandler() {
1793    return this._messageHandler;
1794  }
1795  _initializeFromPort(port) {
1796    this._port = port;
1797    this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
1798    this._messageHandler.on("ready", function () {});
1799    this._readyCapability.resolve();
1800    this._messageHandler.send("configure", {
1801      verbosity: this.verbosity
1802    });
1803  }
1804  _initialize() {
1805    if (!PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
1806      let {
1807        workerSrc
1808      } = PDFWorker;
1809      try {
1810        if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
1811          workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
1812        }
1813        const worker = new Worker(workerSrc);
1814        const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
1815        const terminateEarly = () => {
1816          worker.removeEventListener("error", onWorkerError);
1817          messageHandler.destroy();
1818          worker.terminate();
1819          if (this.destroyed) {
1820            this._readyCapability.reject(new Error("Worker was destroyed"));
1821          } else {
1822            this._setupFakeWorker();
1823          }
1824        };
1825        const onWorkerError = () => {
1826          if (!this._webWorker) {
1827            terminateEarly();
1828          }
1829        };
1830        worker.addEventListener("error", onWorkerError);
1831        messageHandler.on("test", data => {
1832          worker.removeEventListener("error", onWorkerError);
1833          if (this.destroyed) {
1834            terminateEarly();
1835            return;
1836          }
1837          if (data) {
1838            this._messageHandler = messageHandler;
1839            this._port = worker;
1840            this._webWorker = worker;
1841            this._readyCapability.resolve();
1842            messageHandler.send("configure", {
1843              verbosity: this.verbosity
1844            });
1845          } else {
1846            this._setupFakeWorker();
1847            messageHandler.destroy();
1848            worker.terminate();
1849          }
1850        });
1851        messageHandler.on("ready", data => {
1852          worker.removeEventListener("error", onWorkerError);
1853          if (this.destroyed) {
1854            terminateEarly();
1855            return;
1856          }
1857          try {
1858            sendTest();
1859          } catch (e) {
1860            this._setupFakeWorker();
1861          }
1862        });
1863        const sendTest = () => {
1864          const testObj = new Uint8Array();
1865          messageHandler.send("test", testObj, [testObj.buffer]);
1866        };
1867        sendTest();
1868        return;
1869      } catch (e) {
1870        (0, _util.info)("The worker has been disabled.");
1871      }
1872    }
1873    this._setupFakeWorker();
1874  }
1875  _setupFakeWorker() {
1876    if (!PDFWorkerUtil.isWorkerDisabled) {
1877      (0, _util.warn)("Setting up fake worker.");
1878      PDFWorkerUtil.isWorkerDisabled = true;
1879    }
1880    PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
1881      if (this.destroyed) {
1882        this._readyCapability.reject(new Error("Worker was destroyed"));
1883        return;
1884      }
1885      const port = new LoopbackPort();
1886      this._port = port;
1887      const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
1888      const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
1889      WorkerMessageHandler.setup(workerHandler, port);
1890      const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
1891      this._messageHandler = messageHandler;
1892      this._readyCapability.resolve();
1893      messageHandler.send("configure", {
1894        verbosity: this.verbosity
1895      });
1896    }).catch(reason => {
1897      this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
1898    });
1899  }
1900  destroy() {
1901    this.destroyed = true;
1902    if (this._webWorker) {
1903      this._webWorker.terminate();
1904      this._webWorker = null;
1905    }
1906    PDFWorker.#workerPorts.delete(this._port);
1907    this._port = null;
1908    if (this._messageHandler) {
1909      this._messageHandler.destroy();
1910      this._messageHandler = null;
1911    }
1912  }
1913  static fromPort(params) {
1914    if (!params?.port) {
1915      throw new Error("PDFWorker.fromPort - invalid method signature.");
1916    }
1917    if (this.#workerPorts.has(params.port)) {
1918      return this.#workerPorts.get(params.port);
1919    }
1920    return new PDFWorker(params);
1921  }
1922  static get workerSrc() {
1923    if (_worker_options.GlobalWorkerOptions.workerSrc) {
1924      return _worker_options.GlobalWorkerOptions.workerSrc;
1925    }
1926    if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
1927      if (!_is_node.isNodeJS) {
1928        (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
1929      }
1930      return PDFWorkerUtil.fallbackWorkerSrc;
1931    }
1932    throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
1933  }
1934  static get _mainThreadWorkerMessageHandler() {
1935    try {
1936      return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
1937    } catch (ex) {
1938      return null;
1939    }
1940  }
1941  static get _setupFakeWorkerGlobal() {
1942    const loader = async () => {
1943      const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
1944      if (mainWorkerMessageHandler) {
1945        return mainWorkerMessageHandler;
1946      }
1947      if (_is_node.isNodeJS && typeof require === "function") {
1948        const worker = eval("require")(this.workerSrc);
1949        return worker.WorkerMessageHandler;
1950      }
1951      await (0, _display_utils.loadScript)(this.workerSrc);
1952      return window.pdfjsWorker.WorkerMessageHandler;
1953    };
1954    return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
1955  }
1956}
1957exports.PDFWorker = PDFWorker;
1958class WorkerTransport {
1959  #methodPromises = new Map();
1960  #pageCache = new Map();
1961  #pagePromises = new Map();
1962  constructor(messageHandler, loadingTask, networkStream, params, factory) {
1963    this.messageHandler = messageHandler;
1964    this.loadingTask = loadingTask;
1965    this.commonObjs = new PDFObjects();
1966    this.fontLoader = new _font_loader.FontLoader({
1967      onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
1968      ownerDocument: params.ownerDocument,
1969      styleElement: params.styleElement
1970    });
1971    this._params = params;
1972    this.cMapReaderFactory = factory?.cMapReaderFactory;
1973    this.standardFontDataFactory = factory?.standardFontDataFactory;
1974    this.destroyed = false;
1975    this.destroyCapability = null;
1976    this._passwordCapability = null;
1977    this._networkStream = networkStream;
1978    this._fullReader = null;
1979    this._lastProgress = null;
1980    this.downloadInfoCapability = (0, _util.createPromiseCapability)();
1981    this.setupMessageHandler();
1982  }
1983  #cacheSimpleMethod(name, data = null) {
1984    const cachedPromise = this.#methodPromises.get(name);
1985    if (cachedPromise) {
1986      return cachedPromise;
1987    }
1988    const promise = this.messageHandler.sendWithPromise(name, data);
1989    this.#methodPromises.set(name, promise);
1990    return promise;
1991  }
1992  get annotationStorage() {
1993    return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
1994  }
1995  getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) {
1996    let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
1997    let annotationMap = null;
1998    switch (intent) {
1999      case "any":
2000        renderingIntent = _util.RenderingIntentFlag.ANY;
2001        break;
2002      case "display":
2003        break;
2004      case "print":
2005        renderingIntent = _util.RenderingIntentFlag.PRINT;
2006        break;
2007      default:
2008        (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
2009    }
2010    switch (annotationMode) {
2011      case _util.AnnotationMode.DISABLE:
2012        renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
2013        break;
2014      case _util.AnnotationMode.ENABLE:
2015        break;
2016      case _util.AnnotationMode.ENABLE_FORMS:
2017        renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
2018        break;
2019      case _util.AnnotationMode.ENABLE_STORAGE:
2020        renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
2021        const annotationStorage = renderingIntent & _util.RenderingIntentFlag.PRINT && printAnnotationStorage instanceof _annotation_storage.PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
2022        annotationMap = annotationStorage.serializable;
2023        break;
2024      default:
2025        (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
2026    }
2027    if (isOpList) {
2028      renderingIntent += _util.RenderingIntentFlag.OPLIST;
2029    }
2030    return {
2031      renderingIntent,
2032      cacheKey: `${renderingIntent}_${_annotation_storage.AnnotationStorage.getHash(annotationMap)}`,
2033      annotationStorageMap: annotationMap
2034    };
2035  }
2036  destroy() {
2037    if (this.destroyCapability) {
2038      return this.destroyCapability.promise;
2039    }
2040    this.destroyed = true;
2041    this.destroyCapability = (0, _util.createPromiseCapability)();
2042    if (this._passwordCapability) {
2043      this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
2044    }
2045    const waitOn = [];
2046    for (const page of this.#pageCache.values()) {
2047      waitOn.push(page._destroy());
2048    }
2049    this.#pageCache.clear();
2050    this.#pagePromises.clear();
2051    if (this.hasOwnProperty("annotationStorage")) {
2052      this.annotationStorage.resetModified();
2053    }
2054    const terminated = this.messageHandler.sendWithPromise("Terminate", null);
2055    waitOn.push(terminated);
2056    Promise.all(waitOn).then(() => {
2057      this.commonObjs.clear();
2058      this.fontLoader.clear();
2059      this.#methodPromises.clear();
2060      if (this._networkStream) {
2061        this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
2062      }
2063      if (this.messageHandler) {
2064        this.messageHandler.destroy();
2065        this.messageHandler = null;
2066      }
2067      this.destroyCapability.resolve();
2068    }, this.destroyCapability.reject);
2069    return this.destroyCapability.promise;
2070  }
2071  setupMessageHandler() {
2072    const {
2073      messageHandler,
2074      loadingTask
2075    } = this;
2076    messageHandler.on("GetReader", (data, sink) => {
2077      (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
2078      this._fullReader = this._networkStream.getFullReader();
2079      this._fullReader.onProgress = evt => {
2080        this._lastProgress = {
2081          loaded: evt.loaded,
2082          total: evt.total
2083        };
2084      };
2085      sink.onPull = () => {
2086        this._fullReader.read().then(function ({
2087          value,
2088          done
2089        }) {
2090          if (done) {
2091            sink.close();
2092            return;
2093          }
2094          (0, _util.assert)(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
2095          sink.enqueue(new Uint8Array(value), 1, [value]);
2096        }).catch(reason => {
2097          sink.error(reason);
2098        });
2099      };
2100      sink.onCancel = reason => {
2101        this._fullReader.cancel(reason);
2102        sink.ready.catch(readyReason => {
2103          if (this.destroyed) {
2104            return;
2105          }
2106          throw readyReason;
2107        });
2108      };
2109    });
2110    messageHandler.on("ReaderHeadersReady", data => {
2111      const headersCapability = (0, _util.createPromiseCapability)();
2112      const fullReader = this._fullReader;
2113      fullReader.headersReady.then(() => {
2114        if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
2115          if (this._lastProgress) {
2116            loadingTask.onProgress?.(this._lastProgress);
2117          }
2118          fullReader.onProgress = evt => {
2119            loadingTask.onProgress?.({
2120              loaded: evt.loaded,
2121              total: evt.total
2122            });
2123          };
2124        }
2125        headersCapability.resolve({
2126          isStreamingSupported: fullReader.isStreamingSupported,
2127          isRangeSupported: fullReader.isRangeSupported,
2128          contentLength: fullReader.contentLength
2129        });
2130      }, headersCapability.reject);
2131      return headersCapability.promise;
2132    });
2133    messageHandler.on("GetRangeReader", (data, sink) => {
2134      (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
2135      const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
2136      if (!rangeReader) {
2137        sink.close();
2138        return;
2139      }
2140      sink.onPull = () => {
2141        rangeReader.read().then(function ({
2142          value,
2143          done
2144        }) {
2145          if (done) {
2146            sink.close();
2147            return;
2148          }
2149          (0, _util.assert)(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
2150          sink.enqueue(new Uint8Array(value), 1, [value]);
2151        }).catch(reason => {
2152          sink.error(reason);
2153        });
2154      };
2155      sink.onCancel = reason => {
2156        rangeReader.cancel(reason);
2157        sink.ready.catch(readyReason => {
2158          if (this.destroyed) {
2159            return;
2160          }
2161          throw readyReason;
2162        });
2163      };
2164    });
2165    messageHandler.on("GetDoc", ({
2166      pdfInfo
2167    }) => {
2168      this._numPages = pdfInfo.numPages;
2169      this._htmlForXfa = pdfInfo.htmlForXfa;
2170      delete pdfInfo.htmlForXfa;
2171      loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
2172    });
2173    messageHandler.on("DocException", function (ex) {
2174      let reason;
2175      switch (ex.name) {
2176        case "PasswordException":
2177          reason = new _util.PasswordException(ex.message, ex.code);
2178          break;
2179        case "InvalidPDFException":
2180          reason = new _util.InvalidPDFException(ex.message);
2181          break;
2182        case "MissingPDFException":
2183          reason = new _util.MissingPDFException(ex.message);
2184          break;
2185        case "UnexpectedResponseException":
2186          reason = new _util.UnexpectedResponseException(ex.message, ex.status);
2187          break;
2188        case "UnknownErrorException":
2189          reason = new _util.UnknownErrorException(ex.message, ex.details);
2190          break;
2191        default:
2192          (0, _util.unreachable)("DocException - expected a valid Error.");
2193      }
2194      loadingTask._capability.reject(reason);
2195    });
2196    messageHandler.on("PasswordRequest", exception => {
2197      this._passwordCapability = (0, _util.createPromiseCapability)();
2198      if (loadingTask.onPassword) {
2199        const updatePassword = password => {
2200          if (password instanceof Error) {
2201            this._passwordCapability.reject(password);
2202          } else {
2203            this._passwordCapability.resolve({
2204              password
2205            });
2206          }
2207        };
2208        try {
2209          loadingTask.onPassword(updatePassword, exception.code);
2210        } catch (ex) {
2211          this._passwordCapability.reject(ex);
2212        }
2213      } else {
2214        this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
2215      }
2216      return this._passwordCapability.promise;
2217    });
2218    messageHandler.on("DataLoaded", data => {
2219      loadingTask.onProgress?.({
2220        loaded: data.length,
2221        total: data.length
2222      });
2223      this.downloadInfoCapability.resolve(data);
2224    });
2225    messageHandler.on("StartRenderPage", data => {
2226      if (this.destroyed) {
2227        return;
2228      }
2229      const page = this.#pageCache.get(data.pageIndex);
2230      page._startRenderPage(data.transparency, data.cacheKey);
2231    });
2232    messageHandler.on("commonobj", ([id, type, exportedData]) => {
2233      if (this.destroyed) {
2234        return;
2235      }
2236      if (this.commonObjs.has(id)) {
2237        return;
2238      }
2239      switch (type) {
2240        case "Font":
2241          const params = this._params;
2242          if ("error" in exportedData) {
2243            const exportedError = exportedData.error;
2244            (0, _util.warn)(`Error during font loading: ${exportedError}`);
2245            this.commonObjs.resolve(id, exportedError);
2246            break;
2247          }
2248          let fontRegistry = null;
2249          if (params.pdfBug && globalThis.FontInspector?.enabled) {
2250            fontRegistry = {
2251              registerFont(font, url) {
2252                globalThis.FontInspector.fontAdded(font, url);
2253              }
2254            };
2255          }
2256          const font = new _font_loader.FontFaceObject(exportedData, {
2257            isEvalSupported: params.isEvalSupported,
2258            disableFontFace: params.disableFontFace,
2259            ignoreErrors: params.ignoreErrors,
2260            onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
2261            fontRegistry
2262          });
2263          this.fontLoader.bind(font).catch(reason => {
2264            return messageHandler.sendWithPromise("FontFallback", {
2265              id
2266            });
2267          }).finally(() => {
2268            if (!params.fontExtraProperties && font.data) {
2269              font.data = null;
2270            }
2271            this.commonObjs.resolve(id, font);
2272          });
2273          break;
2274        case "FontPath":
2275        case "Image":
2276          this.commonObjs.resolve(id, exportedData);
2277          break;
2278        default:
2279          throw new Error(`Got unknown common object type ${type}`);
2280      }
2281    });
2282    messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
2283      if (this.destroyed) {
2284        return;
2285      }
2286      const pageProxy = this.#pageCache.get(pageIndex);
2287      if (pageProxy.objs.has(id)) {
2288        return;
2289      }
2290      switch (type) {
2291        case "Image":
2292          pageProxy.objs.resolve(id, imageData);
2293          const MAX_IMAGE_SIZE_TO_STORE = 8000000;
2294          if (imageData) {
2295            let length;
2296            if (imageData.bitmap) {
2297              const {
2298                width,
2299                height
2300              } = imageData;
2301              length = width * height * 4;
2302            } else {
2303              length = imageData.data?.length || 0;
2304            }
2305            if (length > MAX_IMAGE_SIZE_TO_STORE) {
2306              pageProxy.cleanupAfterRender = true;
2307            }
2308          }
2309          break;
2310        case "Pattern":
2311          pageProxy.objs.resolve(id, imageData);
2312          break;
2313        default:
2314          throw new Error(`Got unknown object type ${type}`);
2315      }
2316    });
2317    messageHandler.on("DocProgress", data => {
2318      if (this.destroyed) {
2319        return;
2320      }
2321      loadingTask.onProgress?.({
2322        loaded: data.loaded,
2323        total: data.total
2324      });
2325    });
2326    messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
2327    messageHandler.on("FetchBuiltInCMap", data => {
2328      if (this.destroyed) {
2329        return Promise.reject(new Error("Worker was destroyed."));
2330      }
2331      if (!this.cMapReaderFactory) {
2332        return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
2333      }
2334      return this.cMapReaderFactory.fetch(data);
2335    });
2336    messageHandler.on("FetchStandardFontData", data => {
2337      if (this.destroyed) {
2338        return Promise.reject(new Error("Worker was destroyed."));
2339      }
2340      if (!this.standardFontDataFactory) {
2341        return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
2342      }
2343      return this.standardFontDataFactory.fetch(data);
2344    });
2345  }
2346  _onUnsupportedFeature({
2347    featureId
2348  }) {
2349    if (this.destroyed) {
2350      return;
2351    }
2352    this.loadingTask.onUnsupportedFeature?.(featureId);
2353  }
2354  getData() {
2355    return this.messageHandler.sendWithPromise("GetData", null);
2356  }
2357  saveDocument() {
2358    if (this.annotationStorage.size <= 0) {
2359      (0, _util.warn)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
2360    }
2361    return this.messageHandler.sendWithPromise("SaveDocument", {
2362      isPureXfa: !!this._htmlForXfa,
2363      numPages: this._numPages,
2364      annotationStorage: this.annotationStorage.serializable,
2365      filename: this._fullReader?.filename ?? null
2366    }).finally(() => {
2367      this.annotationStorage.resetModified();
2368    });
2369  }
2370  getPage(pageNumber) {
2371    if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
2372      return Promise.reject(new Error("Invalid page request."));
2373    }
2374    const pageIndex = pageNumber - 1,
2375      cachedPromise = this.#pagePromises.get(pageIndex);
2376    if (cachedPromise) {
2377      return cachedPromise;
2378    }
2379    const promise = this.messageHandler.sendWithPromise("GetPage", {
2380      pageIndex
2381    }).then(pageInfo => {
2382      if (this.destroyed) {
2383        throw new Error("Transport destroyed");
2384      }
2385      const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
2386      this.#pageCache.set(pageIndex, page);
2387      return page;
2388    });
2389    this.#pagePromises.set(pageIndex, promise);
2390    return promise;
2391  }
2392  getPageIndex(ref) {
2393    if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
2394      return Promise.reject(new Error("Invalid pageIndex request."));
2395    }
2396    return this.messageHandler.sendWithPromise("GetPageIndex", {
2397      num: ref.num,
2398      gen: ref.gen
2399    });
2400  }
2401  getAnnotations(pageIndex, intent) {
2402    return this.messageHandler.sendWithPromise("GetAnnotations", {
2403      pageIndex,
2404      intent
2405    });
2406  }
2407  getFieldObjects() {
2408    return this.#cacheSimpleMethod("GetFieldObjects");
2409  }
2410  hasJSActions() {
2411    return this.#cacheSimpleMethod("HasJSActions");
2412  }
2413  getCalculationOrderIds() {
2414    return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
2415  }
2416  getDestinations() {
2417    return this.messageHandler.sendWithPromise("GetDestinations", null);
2418  }
2419  getDestination(id) {
2420    if (typeof id !== "string") {
2421      return Promise.reject(new Error("Invalid destination request."));
2422    }
2423    return this.messageHandler.sendWithPromise("GetDestination", {
2424      id
2425    });
2426  }
2427  getPageLabels() {
2428    return this.messageHandler.sendWithPromise("GetPageLabels", null);
2429  }
2430  getPageLayout() {
2431    return this.messageHandler.sendWithPromise("GetPageLayout", null);
2432  }
2433  getPageMode() {
2434    return this.messageHandler.sendWithPromise("GetPageMode", null);
2435  }
2436  getViewerPreferences() {
2437    return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
2438  }
2439  getOpenAction() {
2440    return this.messageHandler.sendWithPromise("GetOpenAction", null);
2441  }
2442  getAttachments() {
2443    return this.messageHandler.sendWithPromise("GetAttachments", null);
2444  }
2445  getJavaScript() {
2446    return this.messageHandler.sendWithPromise("GetJavaScript", null);
2447  }
2448  getDocJSActions() {
2449    return this.messageHandler.sendWithPromise("GetDocJSActions", null);
2450  }
2451  getPageJSActions(pageIndex) {
2452    return this.messageHandler.sendWithPromise("GetPageJSActions", {
2453      pageIndex
2454    });
2455  }
2456  getStructTree(pageIndex) {
2457    return this.messageHandler.sendWithPromise("GetStructTree", {
2458      pageIndex
2459    });
2460  }
2461  getOutline() {
2462    return this.messageHandler.sendWithPromise("GetOutline", null);
2463  }
2464  getOptionalContentConfig() {
2465    return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
2466      return new _optional_content_config.OptionalContentConfig(results);
2467    });
2468  }
2469  getPermissions() {
2470    return this.messageHandler.sendWithPromise("GetPermissions", null);
2471  }
2472  getMetadata() {
2473    const name = "GetMetadata",
2474      cachedPromise = this.#methodPromises.get(name);
2475    if (cachedPromise) {
2476      return cachedPromise;
2477    }
2478    const promise = this.messageHandler.sendWithPromise(name, null).then(results => {
2479      return {
2480        info: results[0],
2481        metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
2482        contentDispositionFilename: this._fullReader?.filename ?? null,
2483        contentLength: this._fullReader?.contentLength ?? null
2484      };
2485    });
2486    this.#methodPromises.set(name, promise);
2487    return promise;
2488  }
2489  getMarkInfo() {
2490    return this.messageHandler.sendWithPromise("GetMarkInfo", null);
2491  }
2492  async startCleanup(keepLoadedFonts = false) {
2493    if (this.destroyed) {
2494      return;
2495    }
2496    await this.messageHandler.sendWithPromise("Cleanup", null);
2497    for (const page of this.#pageCache.values()) {
2498      const cleanupSuccessful = page.cleanup();
2499      if (!cleanupSuccessful) {
2500        throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
2501      }
2502    }
2503    this.commonObjs.clear();
2504    if (!keepLoadedFonts) {
2505      this.fontLoader.clear();
2506    }
2507    this.#methodPromises.clear();
2508  }
2509  get loadingParams() {
2510    const {
2511      disableAutoFetch,
2512      enableXfa
2513    } = this._params;
2514    return (0, _util.shadow)(this, "loadingParams", {
2515      disableAutoFetch,
2516      enableXfa
2517    });
2518  }
2519}
2520class PDFObjects {
2521  #objs = Object.create(null);
2522  #ensureObj(objId) {
2523    const obj = this.#objs[objId];
2524    if (obj) {
2525      return obj;
2526    }
2527    return this.#objs[objId] = {
2528      capability: (0, _util.createPromiseCapability)(),
2529      data: null
2530    };
2531  }
2532  get(objId, callback = null) {
2533    if (callback) {
2534      const obj = this.#ensureObj(objId);
2535      obj.capability.promise.then(() => callback(obj.data));
2536      return null;
2537    }
2538    const obj = this.#objs[objId];
2539    if (!obj?.capability.settled) {
2540      throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
2541    }
2542    return obj.data;
2543  }
2544  has(objId) {
2545    const obj = this.#objs[objId];
2546    return obj?.capability.settled || false;
2547  }
2548  resolve(objId, data = null) {
2549    const obj = this.#ensureObj(objId);
2550    obj.data = data;
2551    obj.capability.resolve();
2552  }
2553  clear() {
2554    for (const objId in this.#objs) {
2555      const {
2556        data
2557      } = this.#objs[objId];
2558      data?.bitmap?.close();
2559    }
2560    this.#objs = Object.create(null);
2561  }
2562}
2563class RenderTask {
2564  #internalRenderTask = null;
2565  constructor(internalRenderTask) {
2566    this.#internalRenderTask = internalRenderTask;
2567    this.onContinue = null;
2568  }
2569  get promise() {
2570    return this.#internalRenderTask.capability.promise;
2571  }
2572  cancel(extraDelay = 0) {
2573    this.#internalRenderTask.cancel(null, extraDelay);
2574  }
2575  get separateAnnots() {
2576    const {
2577      separateAnnots
2578    } = this.#internalRenderTask.operatorList;
2579    if (!separateAnnots) {
2580      return false;
2581    }
2582    const {
2583      annotationCanvasMap
2584    } = this.#internalRenderTask;
2585    return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
2586  }
2587}
2588exports.RenderTask = RenderTask;
2589class InternalRenderTask {
2590  static #canvasInUse = new WeakSet();
2591  constructor({
2592    callback,
2593    params,
2594    objs,
2595    commonObjs,
2596    annotationCanvasMap,
2597    operatorList,
2598    pageIndex,
2599    canvasFactory,
2600    useRequestAnimationFrame = false,
2601    pdfBug = false,
2602    pageColors = null
2603  }) {
2604    this.callback = callback;
2605    this.params = params;
2606    this.objs = objs;
2607    this.commonObjs = commonObjs;
2608    this.annotationCanvasMap = annotationCanvasMap;
2609    this.operatorListIdx = null;
2610    this.operatorList = operatorList;
2611    this._pageIndex = pageIndex;
2612    this.canvasFactory = canvasFactory;
2613    this._pdfBug = pdfBug;
2614    this.pageColors = pageColors;
2615    this.running = false;
2616    this.graphicsReadyCallback = null;
2617    this.graphicsReady = false;
2618    this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
2619    this.cancelled = false;
2620    this.capability = (0, _util.createPromiseCapability)();
2621    this.task = new RenderTask(this);
2622    this._cancelBound = this.cancel.bind(this);
2623    this._continueBound = this._continue.bind(this);
2624    this._scheduleNextBound = this._scheduleNext.bind(this);
2625    this._nextBound = this._next.bind(this);
2626    this._canvas = params.canvasContext.canvas;
2627  }
2628  get completed() {
2629    return this.capability.promise.catch(function () {});
2630  }
2631  initializeGraphics({
2632    transparency = false,
2633    optionalContentConfig
2634  }) {
2635    if (this.cancelled) {
2636      return;
2637    }
2638    if (this._canvas) {
2639      if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
2640        throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
2641      }
2642      InternalRenderTask.#canvasInUse.add(this._canvas);
2643    }
2644    if (this._pdfBug && globalThis.StepperManager?.enabled) {
2645      this.stepper = globalThis.StepperManager.create(this._pageIndex);
2646      this.stepper.init(this.operatorList);
2647      this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
2648    }
2649    const {
2650      canvasContext,
2651      viewport,
2652      transform,
2653      background
2654    } = this.params;
2655    this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, {
2656      optionalContentConfig
2657    }, this.annotationCanvasMap, this.pageColors);
2658    this.gfx.beginDrawing({
2659      transform,
2660      viewport,
2661      transparency,
2662      background
2663    });
2664    this.operatorListIdx = 0;
2665    this.graphicsReady = true;
2666    this.graphicsReadyCallback?.();
2667  }
2668  cancel(error = null, extraDelay = 0) {
2669    this.running = false;
2670    this.cancelled = true;
2671    this.gfx?.endDrawing();
2672    if (this._canvas) {
2673      InternalRenderTask.#canvasInUse.delete(this._canvas);
2674    }
2675    this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas", extraDelay));
2676  }
2677  operatorListChanged() {
2678    if (!this.graphicsReady) {
2679      if (!this.graphicsReadyCallback) {
2680        this.graphicsReadyCallback = this._continueBound;
2681      }
2682      return;
2683    }
2684    this.stepper?.updateOperatorList(this.operatorList);
2685    if (this.running) {
2686      return;
2687    }
2688    this._continue();
2689  }
2690  _continue() {
2691    this.running = true;
2692    if (this.cancelled) {
2693      return;
2694    }
2695    if (this.task.onContinue) {
2696      this.task.onContinue(this._scheduleNextBound);
2697    } else {
2698      this._scheduleNext();
2699    }
2700  }
2701  _scheduleNext() {
2702    if (this._useRequestAnimationFrame) {
2703      window.requestAnimationFrame(() => {
2704        this._nextBound().catch(this._cancelBound);
2705      });
2706    } else {
2707      Promise.resolve().then(this._nextBound).catch(this._cancelBound);
2708    }
2709  }
2710  async _next() {
2711    if (this.cancelled) {
2712      return;
2713    }
2714    this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
2715    if (this.operatorListIdx === this.operatorList.argsArray.length) {
2716      this.running = false;
2717      if (this.operatorList.lastChunk) {
2718        this.gfx.endDrawing();
2719        if (this._canvas) {
2720          InternalRenderTask.#canvasInUse.delete(this._canvas);
2721        }
2722        this.callback();
2723      }
2724    }
2725  }
2726}
2727const version = '3.4.120';
2728exports.version = version;
2729const build = 'af6414988';
2730exports.build = build;
2731
2732/***/ }),
2733/* 3 */
2734/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
2735
2736
2737
2738Object.defineProperty(exports, "__esModule", ({
2739  value: true
2740}));
2741exports.PrintAnnotationStorage = exports.AnnotationStorage = void 0;
2742var _util = __w_pdfjs_require__(1);
2743var _editor = __w_pdfjs_require__(4);
2744var _murmurhash = __w_pdfjs_require__(8);
2745class AnnotationStorage {
2746  #modified = false;
2747  #storage = new Map();
2748  constructor() {
2749    this.onSetModified = null;
2750    this.onResetModified = null;
2751    this.onAnnotationEditor = null;
2752  }
2753  getValue(key, defaultValue) {
2754    const value = this.#storage.get(key);
2755    if (value === undefined) {
2756      return defaultValue;
2757    }
2758    return Object.assign(defaultValue, value);
2759  }
2760  getRawValue(key) {
2761    return this.#storage.get(key);
2762  }
2763  remove(key) {
2764    this.#storage.delete(key);
2765    if (this.#storage.size === 0) {
2766      this.resetModified();
2767    }
2768    if (typeof this.onAnnotationEditor === "function") {
2769      for (const value of this.#storage.values()) {
2770        if (value instanceof _editor.AnnotationEditor) {
2771          return;
2772        }
2773      }
2774      this.onAnnotationEditor(null);
2775    }
2776  }
2777  setValue(key, value) {
2778    const obj = this.#storage.get(key);
2779    let modified = false;
2780    if (obj !== undefined) {
2781      for (const [entry, val] of Object.entries(value)) {
2782        if (obj[entry] !== val) {
2783          modified = true;
2784          obj[entry] = val;
2785        }
2786      }
2787    } else {
2788      modified = true;
2789      this.#storage.set(key, value);
2790    }
2791    if (modified) {
2792      this.#setModified();
2793    }
2794    if (value instanceof _editor.AnnotationEditor && typeof this.onAnnotationEditor === "function") {
2795      this.onAnnotationEditor(value.constructor._type);
2796    }
2797  }
2798  has(key) {
2799    return this.#storage.has(key);
2800  }
2801  getAll() {
2802    return this.#storage.size > 0 ? (0, _util.objectFromMap)(this.#storage) : null;
2803  }
2804  setAll(obj) {
2805    for (const [key, val] of Object.entries(obj)) {
2806      this.setValue(key, val);
2807    }
2808  }
2809  get size() {
2810    return this.#storage.size;
2811  }
2812  #setModified() {
2813    if (!this.#modified) {
2814      this.#modified = true;
2815      if (typeof this.onSetModified === "function") {
2816        this.onSetModified();
2817      }
2818    }
2819  }
2820  resetModified() {
2821    if (this.#modified) {
2822      this.#modified = false;
2823      if (typeof this.onResetModified === "function") {
2824        this.onResetModified();
2825      }
2826    }
2827  }
2828  get print() {
2829    return new PrintAnnotationStorage(this);
2830  }
2831  get serializable() {
2832    if (this.#storage.size === 0) {
2833      return null;
2834    }
2835    const clone = new Map();
2836    for (const [key, val] of this.#storage) {
2837      const serialized = val instanceof _editor.AnnotationEditor ? val.serialize() : val;
2838      if (serialized) {
2839        clone.set(key, serialized);
2840      }
2841    }
2842    return clone;
2843  }
2844  static getHash(map) {
2845    if (!map) {
2846      return "";
2847    }
2848    const hash = new _murmurhash.MurmurHash3_64();
2849    for (const [key, val] of map) {
2850      hash.update(`${key}:${JSON.stringify(val)}`);
2851    }
2852    return hash.hexdigest();
2853  }
2854}
2855exports.AnnotationStorage = AnnotationStorage;
2856class PrintAnnotationStorage extends AnnotationStorage {
2857  #serializable = null;
2858  constructor(parent) {
2859    super();
2860    this.#serializable = structuredClone(parent.serializable);
2861  }
2862  get print() {
2863    (0, _util.unreachable)("Should not call PrintAnnotationStorage.print");
2864  }
2865  get serializable() {
2866    return this.#serializable;
2867  }
2868}
2869exports.PrintAnnotationStorage = PrintAnnotationStorage;
2870
2871/***/ }),
2872/* 4 */
2873/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
2874
2875
2876
2877Object.defineProperty(exports, "__esModule", ({
2878  value: true
2879}));
2880exports.AnnotationEditor = void 0;
2881var _tools = __w_pdfjs_require__(5);
2882var _util = __w_pdfjs_require__(1);
2883class AnnotationEditor {
2884  #boundFocusin = this.focusin.bind(this);
2885  #boundFocusout = this.focusout.bind(this);
2886  #hasBeenSelected = false;
2887  #isEditing = false;
2888  #isInEditMode = false;
2889  _uiManager = null;
2890  #zIndex = AnnotationEditor._zIndex++;
2891  static _colorManager = new _tools.ColorManager();
2892  static _zIndex = 1;
2893  constructor(parameters) {
2894    if (this.constructor === AnnotationEditor) {
2895      (0, _util.unreachable)("Cannot initialize AnnotationEditor.");
2896    }
2897    this.parent = parameters.parent;
2898    this.id = parameters.id;
2899    this.width = this.height = null;
2900    this.pageIndex = parameters.parent.pageIndex;
2901    this.name = parameters.name;
2902    this.div = null;
2903    this._uiManager = parameters.uiManager;
2904    const {
2905      rotation,
2906      rawDims: {
2907        pageWidth,
2908        pageHeight,
2909        pageX,
2910        pageY
2911      }
2912    } = this.parent.viewport;
2913    this.rotation = rotation;
2914    this.pageDimensions = [pageWidth, pageHeight];
2915    this.pageTranslation = [pageX, pageY];
2916    const [width, height] = this.parentDimensions;
2917    this.x = parameters.x / width;
2918    this.y = parameters.y / height;
2919    this.isAttachedToDOM = false;
2920  }
2921  static get _defaultLineColor() {
2922    return (0, _util.shadow)(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
2923  }
2924  addCommands(params) {
2925    this._uiManager.addCommands(params);
2926  }
2927  get currentLayer() {
2928    return this._uiManager.currentLayer;
2929  }
2930  setInBackground() {
2931    this.div.style.zIndex = 0;
2932  }
2933  setInForeground() {
2934    this.div.style.zIndex = this.#zIndex;
2935  }
2936  setParent(parent) {
2937    if (parent !== null) {
2938      this.pageIndex = parent.pageIndex;
2939      this.pageDimensions = parent.pageDimensions;
2940    }
2941    this.parent = parent;
2942  }
2943  focusin(event) {
2944    if (!this.#hasBeenSelected) {
2945      this.parent.setSelected(this);
2946    } else {
2947      this.#hasBeenSelected = false;
2948    }
2949  }
2950  focusout(event) {
2951    if (!this.isAttachedToDOM) {
2952      return;
2953    }
2954    const target = event.relatedTarget;
2955    if (target?.closest(`#${this.id}`)) {
2956      return;
2957    }
2958    event.preventDefault();
2959    if (!this.parent?.isMultipleSelection) {
2960      this.commitOrRemove();
2961    }
2962  }
2963  commitOrRemove() {
2964    if (this.isEmpty()) {
2965      this.remove();
2966    } else {
2967      this.commit();
2968    }
2969  }
2970  commit() {
2971    this.addToAnnotationStorage();
2972  }
2973  addToAnnotationStorage() {
2974    this._uiManager.addToAnnotationStorage(this);
2975  }
2976  dragstart(event) {
2977    const rect = this.parent.div.getBoundingClientRect();
2978    this.startX = event.clientX - rect.x;
2979    this.startY = event.clientY - rect.y;
2980    event.dataTransfer.setData("text/plain", this.id);
2981    event.dataTransfer.effectAllowed = "move";
2982  }
2983  setAt(x, y, tx, ty) {
2984    const [width, height] = this.parentDimensions;
2985    [tx, ty] = this.screenToPageTranslation(tx, ty);
2986    this.x = (x + tx) / width;
2987    this.y = (y + ty) / height;
2988    this.div.style.left = `${100 * this.x}%`;
2989    this.div.style.top = `${100 * this.y}%`;
2990  }
2991  translate(x, y) {
2992    const [width, height] = this.parentDimensions;
2993    [x, y] = this.screenToPageTranslation(x, y);
2994    this.x += x / width;
2995    this.y += y / height;
2996    this.div.style.left = `${100 * this.x}%`;
2997    this.div.style.top = `${100 * this.y}%`;
2998  }
2999  screenToPageTranslation(x, y) {
3000    switch (this.parentRotation) {
3001      case 90:
3002        return [y, -x];
3003      case 180:
3004        return [-x, -y];
3005      case 270:
3006        return [-y, x];
3007      default:
3008        return [x, y];
3009    }
3010  }
3011  get parentScale() {
3012    return this._uiManager.viewParameters.realScale;
3013  }
3014  get parentRotation() {
3015    return this._uiManager.viewParameters.rotation;
3016  }
3017  get parentDimensions() {
3018    const {
3019      realScale
3020    } = this._uiManager.viewParameters;
3021    const [pageWidth, pageHeight] = this.pageDimensions;
3022    return [pageWidth * realScale, pageHeight * realScale];
3023  }
3024  setDims(width, height) {
3025    const [parentWidth, parentHeight] = this.parentDimensions;
3026    this.div.style.width = `${100 * width / parentWidth}%`;
3027    this.div.style.height = `${100 * height / parentHeight}%`;
3028  }
3029  fixDims() {
3030    const {
3031      style
3032    } = this.div;
3033    const {
3034      height,
3035      width
3036    } = style;
3037    const widthPercent = width.endsWith("%");
3038    const heightPercent = height.endsWith("%");
3039    if (widthPercent && heightPercent) {
3040      return;
3041    }
3042    const [parentWidth, parentHeight] = this.parentDimensions;
3043    if (!widthPercent) {
3044      style.width = `${100 * parseFloat(width) / parentWidth}%`;
3045    }
3046    if (!heightPercent) {
3047      style.height = `${100 * parseFloat(height) / parentHeight}%`;
3048    }
3049  }
3050  getInitialTranslation() {
3051    return [0, 0];
3052  }
3053  render() {
3054    this.div = document.createElement("div");
3055    this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
3056    this.div.className = this.name;
3057    this.div.setAttribute("id", this.id);
3058    this.div.setAttribute("tabIndex", 0);
3059    this.setInForeground();
3060    this.div.addEventListener("focusin", this.#boundFocusin);
3061    this.div.addEventListener("focusout", this.#boundFocusout);
3062    const [tx, ty] = this.getInitialTranslation();
3063    this.translate(tx, ty);
3064    (0, _tools.bindEvents)(this, this.div, ["dragstart", "pointerdown"]);
3065    return this.div;
3066  }
3067  pointerdown(event) {
3068    const {
3069      isMac
3070    } = _util.FeatureTest.platform;
3071    if (event.button !== 0 || event.ctrlKey && isMac) {
3072      event.preventDefault();
3073      return;
3074    }
3075    if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
3076      this.parent.toggleSelected(this);
3077    } else {
3078      this.parent.setSelected(this);
3079    }
3080    this.#hasBeenSelected = true;
3081  }
3082  getRect(tx, ty) {
3083    const scale = this.parentScale;
3084    const [pageWidth, pageHeight] = this.pageDimensions;
3085    const [pageX, pageY] = this.pageTranslation;
3086    const shiftX = tx / scale;
3087    const shiftY = ty / scale;
3088    const x = this.x * pageWidth;
3089    const y = this.y * pageHeight;
3090    const width = this.width * pageWidth;
3091    const height = this.height * pageHeight;
3092    switch (this.rotation) {
3093      case 0:
3094        return [x + shiftX + pageX, pageHeight - y - shiftY - he
3094ight + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
3095      case 90:
3096        return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
3097      case 180:
3098        return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
3099      case 270:
3100        return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
3101      default:
3102        throw new Error("Invalid rotation");
3103    }
3104  }
3105  getRectInCurrentCoords(rect, pageHeight) {
3106    const [x1, y1, x2, y2] = rect;
3107    const width = x2 - x1;
3108    const height = y2 - y1;
3109    switch (this.rotation) {
3110      case 0:
3111        return [x1, pageHeight - y2, width, height];
3112      case 90:
3113        return [x1, pageHeight - y1, height, width];
3114      case 180:
3115        return [x2, pageHeight - y1, width, height];
3116      case 270:
3117        return [x2, pageHeight - y2, height, width];
3118      default:
3119        throw new Error("Invalid rotation");
3120    }
3121  }
3122  onceAdded() {}
3123  isEmpty() {
3124    return false;
3125  }
3126  enableEditMode() {
3127    this.#isInEditMode = true;
3128  }
3129  disableEditMode() {
3130    this.#isInEditMode = false;
3131  }
3132  isInEditMode() {
3133    return this.#isInEditMode;
3134  }
3135  shouldGetKeyboardEvents() {
3136    return false;
3137  }
3138  needsToBeRebuilt() {
3139    return this.div && !this.isAttachedToDOM;
3140  }
3141  rebuild() {
3142    this.div?.addEventListener("focusin", this.#boundFocusin);
3143  }
3144  serialize() {
3145    (0, _util.unreachable)("An editor must be serializable");
3146  }
3147  static deserialize(data, parent, uiManager) {
3148    const editor = new this.prototype.constructor({
3149      parent,
3150      id: parent.getNextId(),
3151      uiManager
3152    });
3153    editor.rotation = data.rotation;
3154    const [pageWidth, pageHeight] = editor.pageDimensions;
3155    const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
3156    editor.x = x / pageWidth;
3157    editor.y = y / pageHeight;
3158    editor.width = width / pageWidth;
3159    editor.height = height / pageHeight;
3160    return editor;
3161  }
3162  remove() {
3163    this.div.removeEventListener("focusin", this.#boundFocusin);
3164    this.div.removeEventListener("focusout", this.#boundFocusout);
3165    if (!this.isEmpty()) {
3166      this.commit();
3167    }
3168    this.parent.remove(this);
3169  }
3170  select() {
3171    this.div?.classList.add("selectedEditor");
3172  }
3173  unselect() {
3174    this.div?.classList.remove("selectedEditor");
3175  }
3176  updateParams(type, value) {}
3177  disableEditing() {}
3178  enableEditing() {}
3179  get propertiesToUpdate() {
3180    return {};
3181  }
3182  get contentDiv() {
3183    return this.div;
3184  }
3185  get isEditing() {
3186    return this.#isEditing;
3187  }
3188  set isEditing(value) {
3189    this.#isEditing = value;
3190    if (value) {
3191      this.parent.setSelected(this);
3192      this.parent.setActiveEditor(this);
3193    } else {
3194      this.parent.setActiveEditor(null);
3195    }
3196  }
3197}
3198exports.AnnotationEditor = AnnotationEditor;
3199
3200/***/ }),
3201/* 5 */
3202/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
3203
3204
3205
3206Object.defineProperty(exports, "__esModule", ({
3207  value: true
3208}));
3209exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
3210exports.bindEvents = bindEvents;
3211exports.opacityToHex = opacityToHex;
3212var _util = __w_pdfjs_require__(1);
3213var _display_utils = __w_pdfjs_require__(6);
3214function bindEvents(obj, element, names) {
3215  for (const name of names) {
3216    element.addEventListener(name, obj[name].bind(obj));
3217  }
3218}
3219function opacityToHex(opacity) {
3220  return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
3221}
3222class IdManager {
3223  #id = 0;
3224  getId() {
3225    return `${_util.AnnotationEditorPrefix}${this.#id++}`;
3226  }
3227}
3228class CommandManager {
3229  #commands = [];
3230  #locked = false;
3231  #maxSize;
3232  #position = -1;
3233  constructor(maxSize = 128) {
3234    this.#maxSize = maxSize;
3235  }
3236  add({
3237    cmd,
3238    undo,
3239    mustExec,
3240    type = NaN,
3241    overwriteIfSameType = false,
3242    keepUndo = false
3243  }) {
3244    if (mustExec) {
3245      cmd();
3246    }
3247    if (this.#locked) {
3248      return;
3249    }
3250    const save = {
3251      cmd,
3252      undo,
3253      type
3254    };
3255    if (this.#position === -1) {
3256      if (this.#commands.length > 0) {
3257        this.#commands.length = 0;
3258      }
3259      this.#position = 0;
3260      this.#commands.push(save);
3261      return;
3262    }
3263    if (overwriteIfSameType && this.#commands[this.#position].type === type) {
3264      if (keepUndo) {
3265        save.undo = this.#commands[this.#position].undo;
3266      }
3267      this.#commands[this.#position] = save;
3268      return;
3269    }
3270    const next = this.#position + 1;
3271    if (next === this.#maxSize) {
3272      this.#commands.splice(0, 1);
3273    } else {
3274      this.#position = next;
3275      if (next < this.#commands.length) {
3276        this.#commands.splice(next);
3277      }
3278    }
3279    this.#commands.push(save);
3280  }
3281  undo() {
3282    if (this.#position === -1) {
3283      return;
3284    }
3285    this.#locked = true;
3286    this.#commands[this.#position].undo();
3287    this.#locked = false;
3288    this.#position -= 1;
3289  }
3290  redo() {
3291    if (this.#position < this.#commands.length - 1) {
3292      this.#position += 1;
3293      this.#locked = true;
3294      this.#commands[this.#position].cmd();
3295      this.#locked = false;
3296    }
3297  }
3298  hasSomethingToUndo() {
3299    return this.#position !== -1;
3300  }
3301  hasSomethingToRedo() {
3302    return this.#position < this.#commands.length - 1;
3303  }
3304  destroy() {
3305    this.#commands = null;
3306  }
3307}
3308exports.CommandManager = CommandManager;
3309class KeyboardManager {
3310  constructor(callbacks) {
3311    this.buffer = [];
3312    this.callbacks = new Map();
3313    this.allKeys = new Set();
3314    const {
3315      isMac
3316    } = _util.FeatureTest.platform;
3317    for (const [keys, callback] of callbacks) {
3318      for (const key of keys) {
3319        const isMacKey = key.startsWith("mac+");
3320        if (isMac && isMacKey) {
3321          this.callbacks.set(key.slice(4), callback);
3322          this.allKeys.add(key.split("+").at(-1));
3323        } else if (!isMac && !isMacKey) {
3324          this.callbacks.set(key, callback);
3325          this.allKeys.add(key.split("+").at(-1));
3326        }
3327      }
3328    }
3329  }
3330  #serialize(event) {
3331    if (event.altKey) {
3332      this.buffer.push("alt");
3333    }
3334    if (event.ctrlKey) {
3335      this.buffer.push("ctrl");
3336    }
3337    if (event.metaKey) {
3338      this.buffer.push("meta");
3339    }
3340    if (event.shiftKey) {
3341      this.buffer.push("shift");
3342    }
3343    this.buffer.push(event.key);
3344    const str = this.buffer.join("+");
3345    this.buffer.length = 0;
3346    return str;
3347  }
3348  exec(self, event) {
3349    if (!this.allKeys.has(event.key)) {
3350      return;
3351    }
3352    const callback = this.callbacks.get(this.#serialize(event));
3353    if (!callback) {
3354      return;
3355    }
3356    callback.bind(self)();
3357    event.stopPropagation();
3358    event.preventDefault();
3359  }
3360}
3361exports.KeyboardManager = KeyboardManager;
3362class ColorManager {
3363  static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
3364  get _colors() {
3365    const colors = new Map([["CanvasText", null], ["Canvas", null]]);
3366    (0, _display_utils.getColorValues)(colors);
3367    return (0, _util.shadow)(this, "_colors", colors);
3368  }
3369  convert(color) {
3370    const rgb = (0, _display_utils.getRGB)(color);
3371    if (!window.matchMedia("(forced-colors: active)").matches) {
3372      return rgb;
3373    }
3374    for (const [name, RGB] of this._colors) {
3375      if (RGB.every((x, i) => x === rgb[i])) {
3376        return ColorManager._colorsMapping.get(name);
3377      }
3378    }
3379    return rgb;
3380  }
3381  getHexCode(name) {
3382    const rgb = this._colors.get(name);
3383    if (!rgb) {
3384      return name;
3385    }
3386    return _util.Util.makeHexColor(...rgb);
3387  }
3388}
3389exports.ColorManager = ColorManager;
3390class AnnotationEditorUIManager {
3391  #activeEditor = null;
3392  #allEditors = new Map();
3393  #allLayers = new Map();
3394  #annotationStorage = null;
3395  #commandManager = new CommandManager();
3396  #currentPageIndex = 0;
3397  #editorTypes = null;
3398  #editorsToRescale = new Set();
3399  #eventBus = null;
3400  #idManager = new IdManager();
3401  #isEnabled = false;
3402  #mode = _util.AnnotationEditorType.NONE;
3403  #selectedEditors = new Set();
3404  #boundCopy = this.copy.bind(this);
3405  #boundCut = this.cut.bind(this);
3406  #boundPaste = this.paste.bind(this);
3407  #boundKeydown = this.keydown.bind(this);
3408  #boundOnEditingAction = this.onEditingAction.bind(this);
3409  #boundOnPageChanging = this.onPageChanging.bind(this);
3410  #boundOnScaleChanging = this.onScaleChanging.bind(this);
3411  #boundOnRotationChanging = this.onRotationChanging.bind(this);
3412  #previousStates = {
3413    isEditing: false,
3414    isEmpty: true,
3415    hasSomethingToUndo: false,
3416    hasSomethingToRedo: false,
3417    hasSelectedEditor: false
3418  };
3419  #container = null;
3420  static _keyboardManager = new KeyboardManager([[["ctrl+a", "mac+meta+a"], AnnotationEditorUIManager.prototype.selectAll], [["ctrl+z", "mac+meta+z"], AnnotationEditorUIManager.prototype.undo], [["ctrl+y", "ctrl+shift+Z", "mac+meta+shift+Z"], AnnotationEditorUIManager.prototype.redo], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete"], AnnotationEditorUIManager.prototype.delete], [["Escape", "mac+Escape"], AnnotationEditorUIManager.prototype.unselectAll]]);
3421  constructor(container, eventBus, annotationStorage) {
3422    this.#container = container;
3423    this.#eventBus = eventBus;
3424    this.#eventBus._on("editingaction", this.#boundOnEditingAction);
3425    this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
3426    this.#eventBus._on("scalechanging", this.#boundOnScaleChanging);
3427    this.#eventBus._on("rotationchanging", this.#boundOnRotationChanging);
3428    this.#annotationStorage = annotationStorage;
3429    this.viewParameters = {
3430      realScale: _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS,
3431      rotation: 0
3432    };
3433  }
3434  destroy() {
3435    this.#removeKeyboardManager();
3436    this.#eventBus._off("editingaction", this.#boundOnEditingAction);
3437    this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
3438    this.#eventBus._off("scalechanging", this.#boundOnScaleChanging);
3439    this.#eventBus._off("rotationchanging", this.#boundOnRotationChanging);
3440    for (const layer of this.#allLayers.values()) {
3441      layer.destroy();
3442    }
3443    this.#allLayers.clear();
3444    this.#allEditors.clear();
3445    this.#editorsToRescale.clear();
3446    this.#activeEditor = null;
3447    this.#selectedEditors.clear();
3448    this.#commandManager.destroy();
3449  }
3450  onPageChanging({
3451    pageNumber
3452  }) {
3453    this.#currentPageIndex = pageNumber - 1;
3454  }
3455  focusMainContainer() {
3456    this.#container.focus();
3457  }
3458  addShouldRescale(editor) {
3459    this.#editorsToRescale.add(editor);
3460  }
3461  removeShouldRescale(editor) {
3462    this.#editorsToRescale.delete(editor);
3463  }
3464  onScaleChanging({
3465    scale
3466  }) {
3467    this.commitOrRemove();
3468    this.viewParameters.realScale = scale * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS;
3469    for (const editor of this.#editorsToRescale) {
3470      editor.onScaleChanging();
3471    }
3472  }
3473  onRotationChanging({
3474    pagesRotation
3475  }) {
3476    this.commitOrRemove();
3477    this.viewParameters.rotation = pagesRotation;
3478  }
3479  addToAnnotationStorage(editor) {
3480    if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
3481      this.#annotationStorage.setValue(editor.id, editor);
3482    }
3483  }
3484  #addKeyboardManager() {
3485    this.#container.addEventListener("keydown", this.#boundKeydown);
3486  }
3487  #removeKeyboardManager() {
3488    this.#container.removeEventListener("keydown", this.#boundKeydown);
3489  }
3490  #addCopyPasteListeners() {
3491    document.addEventListener("copy", this.#boundCopy);
3492    document.addEventListener("cut", this.#boundCut);
3493    document.addEventListener("paste", this.#boundPaste);
3494  }
3495  #removeCopyPasteListeners() {
3496    document.removeEventListener("copy", this.#boundCopy);
3497    document.removeEventListener("cut", this.#boundCut);
3498    document.removeEventListener("paste", this.#boundPaste);
3499  }
3500  copy(event) {
3501    event.preventDefault();
3502    if (this.#activeEditor) {
3503      this.#activeEditor.commitOrRemove();
3504    }
3505    if (!this.hasSelection) {
3506      return;
3507    }
3508    const editors = [];
3509    for (const editor of this.#selectedEditors) {
3510      if (!editor.isEmpty()) {
3511        editors.push(editor.serialize());
3512      }
3513    }
3514    if (editors.length === 0) {
3515      return;
3516    }
3517    event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
3518  }
3519  cut(event) {
3520    this.copy(event);
3521    this.delete();
3522  }
3523  paste(event) {
3524    event.preventDefault();
3525    let data = event.clipboardData.getData("application/pdfjs");
3526    if (!data) {
3527      return;
3528    }
3529    try {
3530      data = JSON.parse(data);
3531    } catch (ex) {
3532      (0, _util.warn)(`paste: "${ex.message}".`);
3533      return;
3534    }
3535    if (!Array.isArray(data)) {
3536      return;
3537    }
3538    this.unselectAll();
3539    const layer = this.#allLayers.get(this.#currentPageIndex);
3540    try {
3541      const newEditors = [];
3542      for (const editor of data) {
3543        const deserializedEditor = layer.deserialize(editor);
3544        if (!deserializedEditor) {
3545          return;
3546        }
3547        newEditors.push(deserializedEditor);
3548      }
3549      const cmd = () => {
3550        for (const editor of newEditors) {
3551          this.#addEditorToLayer(editor);
3552        }
3553        this.#selectEditors(newEditors);
3554      };
3555      const undo = () => {
3556        for (const editor of newEditors) {
3557          editor.remove();
3558        }
3559      };
3560      this.addCommands({
3561        cmd,
3562        undo,
3563        mustExec: true
3564      });
3565    } catch (ex) {
3566      (0, _util.warn)(`paste: "${ex.message}".`);
3567    }
3568  }
3569  keydown(event) {
3570    if (!this.getActive()?.shouldGetKeyboardEvents()) {
3571      AnnotationEditorUIManager._keyboardManager.exec(this, event);
3572    }
3573  }
3574  onEditingAction(details) {
3575    if (["undo", "redo", "delete", "selectAll"].includes(details.name)) {
3576      this[details.name]();
3577    }
3578  }
3579  #dispatchUpdateStates(details) {
3580    const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
3581    if (hasChanged) {
3582      this.#eventBus.dispatch("annotationeditorstateschanged", {
3583        source: this,
3584        details: Object.assign(this.#previousStates, details)
3585      });
3586    }
3587  }
3588  #dispatchUpdateUI(details) {
3589    this.#eventBus.dispatch("annotationeditorparamschanged", {
3590      source: this,
3591      details
3592    });
3593  }
3594  setEditingState(isEditing) {
3595    if (isEditing) {
3596      this.#addKeyboardManager();
3597      this.#addCopyPasteListeners();
3598      this.#dispatchUpdateStates({
3599        isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
3600        isEmpty: this.#isEmpty(),
3601        hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
3602        hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
3603        hasSelectedEditor: false
3604      });
3605    } else {
3606      this.#removeKeyboardManager();
3607      this.#removeCopyPasteListeners();
3608      this.#dispatchUpdateStates({
3609        isEditing: false
3610      });
3611    }
3612  }
3613  registerEditorTypes(types) {
3614    if (this.#editorTypes) {
3615      return;
3616    }
3617    this.#editorTypes = types;
3618    for (const editorType of this.#editorTypes) {
3619      this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
3620    }
3621  }
3622  getId() {
3623    return this.#idManager.getId();
3624  }
3625  get currentLayer() {
3626    return this.#allLayers.get(this.#currentPageIndex);
3627  }
3628  get currentPageIndex() {
3629    return this.#currentPageIndex;
3630  }
3631  addLayer(layer) {
3632    this.#allLayers.set(layer.pageIndex, layer);
3633    if (this.#isEnabled) {
3634      layer.enable();
3635    } else {
3636      layer.disable();
3637    }
3638  }
3639  removeLayer(layer) {
3640    this.#allLayers.delete(layer.pageIndex);
3641  }
3642  updateMode(mode) {
3643    this.#mode = mode;
3644    if (mode === _util.AnnotationEditorType.NONE) {
3645      this.setEditingState(false);
3646      this.#disableAll();
3647    } else {
3648      this.setEditingState(true);
3649      this.#enableAll();
3650      for (const layer of this.#allLayers.values()) {
3651        layer.updateMode(mode);
3652      }
3653    }
3654  }
3655  updateToolbar(mode) {
3656    if (mode === this.#mode) {
3657      return;
3658    }
3659    this.#eventBus.dispatch("switchannotationeditormode", {
3660      source: this,
3661      mode
3662    });
3663  }
3664  updateParams(type, value) {
3665    if (!this.#editorTypes) {
3666      return;
3667    }
3668    for (const editor of this.#selectedEditors) {
3669      editor.updateParams(type, value);
3670    }
3671    for (const editorType of this.#editorTypes) {
3672      editorType.updateDefaultParams(type, value);
3673    }
3674  }
3675  #enableAll() {
3676    if (!this.#isEnabled) {
3677      this.#isEnabled = true;
3678      for (const layer of this.#allLayers.values()) {
3679        layer.enable();
3680      }
3681    }
3682  }
3683  #disableAll() {
3684    this.unselectAll();
3685    if (this.#isEnabled) {
3686      this.#isEnabled = false;
3687      for (const layer of this.#allLayers.values()) {
3688        layer.disable();
3689      }
3690    }
3691  }
3692  getEditors(pageIndex) {
3693    const editors = [];
3694    for (const editor of this.#allEditors.values()) {
3695      if (editor.pageIndex === pageIndex) {
3696        editors.push(editor);
3697      }
3698    }
3699    return editors;
3700  }
3701  getEditor(id) {
3702    return this.#allEditors.get(id);
3703  }
3704  addEditor(editor) {
3705    this.#allEditors.set(editor.id, editor);
3706  }
3707  removeEditor(editor) {
3708    this.#allEditors.delete(editor.id);
3709    this.unselect(editor);
3710    this.#annotationStorage?.remove(editor.id);
3711  }
3712  #addEditorToLayer(editor) {
3713    const layer = this.#allLayers.get(editor.pageIndex);
3714    if (layer) {
3715      layer.addOrRebuild(editor);
3716    } else {
3717      this.addEditor(editor);
3718    }
3719  }
3720  setActiveEditor(editor) {
3721    if (this.#activeEditor === editor) {
3722      return;
3723    }
3724    this.#activeEditor = editor;
3725    if (editor) {
3726      this.#dispatchUpdateUI(editor.propertiesToUpdate);
3727    }
3728  }
3729  toggleSelected(editor) {
3730    if (this.#selectedEditors.has(editor)) {
3731      this.#selectedEditors.delete(editor);
3732      editor.unselect();
3733      this.#dispatchUpdateStates({
3734        hasSelectedEditor: this.hasSelection
3735      });
3736      return;
3737    }
3738    this.#selectedEditors.add(editor);
3739    editor.select();
3740    this.#dispatchUpdateUI(editor.propertiesToUpdate);
3741    this.#dispatchUpdateStates({
3742      hasSelectedEditor: true
3743    });
3744  }
3745  setSelected(editor) {
3746    for (const ed of this.#selectedEditors) {
3747      if (ed !== editor) {
3748        ed.unselect();
3749      }
3750    }
3751    this.#selectedEditors.clear();
3752    this.#selectedEditors.add(editor);
3753    editor.select();
3754    this.#dispatchUpdateUI(editor.propertiesToUpdate);
3755    this.#dispatchUpdateStates({
3756      hasSelectedEditor: true
3757    });
3758  }
3759  isSelected(editor) {
3760    return this.#selectedEditors.has(editor);
3761  }
3762  unselect(editor) {
3763    editor.unselect();
3764    this.#selectedEditors.delete(editor);
3765    this.#dispatchUpdateStates({
3766      hasSelectedEditor: this.hasSelection
3767    });
3768  }
3769  get hasSelection() {
3770    return this.#selectedEditors.size !== 0;
3771  }
3772  undo() {
3773    this.#commandManager.undo();
3774    this.#dispatchUpdateStates({
3775      hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
3776      hasSomethingToRedo: true,
3777      isEmpty: this.#isEmpty()
3778    });
3779  }
3780  redo() {
3781    this.#commandManager.redo();
3782    this.#dispatchUpdateStates({
3783      hasSomethingToUndo: true,
3784      hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
3785      isEmpty: this.#isEmpty()
3786    });
3787  }
3788  addCommands(params) {
3789    this.#commandManager.add(params);
3790    this.#dispatchUpdateStates({
3791      hasSomethingToUndo: true,
3792      hasSomethingToRedo: false,
3793      isEmpty: this.#isEmpty()
3794    });
3795  }
3796  #isEmpty() {
3797    if (this.#allEditors.size === 0) {
3798      return true;
3799    }
3800    if (this.#allEditors.size === 1) {
3801      for (const editor of this.#allEditors.values()) {
3802        return editor.isEmpty();
3803      }
3804    }
3805    return false;
3806  }
3807  delete() {
3808    this.commitOrRemove();
3809    if (!this.hasSelection) {
3810      return;
3811    }
3812    const editors = [...this.#selectedEditors];
3813    const cmd = () => {
3814      for (const editor of editors) {
3815        editor.remove();
3816      }
3817    };
3818    const undo = () => {
3819      for (const editor of editors) {
3820        this.#addEditorToLayer(editor);
3821      }
3822    };
3823    this.addCommands({
3824      cmd,
3825      undo,
3826      mustExec: true
3827    });
3828  }
3829  commitOrRemove() {
3830    this.#activeEditor?.commitOrRemove();
3831  }
3832  #selectEditors(editors) {
3833    this.#selectedEditors.clear();
3834    for (const editor of editors) {
3835      if (editor.isEmpty()) {
3836        continue;
3837      }
3838      this.#selectedEditors.add(editor);
3839      editor.select();
3840    }
3841    this.#dispatchUpdateStates({
3842      hasSelectedEditor: true
3843    });
3844  }
3845  selectAll() {
3846    for (const editor of this.#selectedEditors) {
3847      editor.commit();
3848    }
3849    this.#selectEditors(this.#allEditors.values());
3850  }
3851  unselectAll() {
3852    if (this.#activeEditor) {
3853      this.#activeEditor.commitOrRemove();
3854      return;
3855    }
3856    if (this.#selectedEditors.size === 0) {
3857      return;
3858    }
3859    for (const editor of this.#selectedEditors) {
3860      editor.unselect();
3861    }
3862    this.#selectedEditors.clear();
3863    this.#dispatchUpdateStates({
3864      hasSelectedEditor: false
3865    });
3866  }
3867  isActive(editor) {
3868    return this.#activeEditor === editor;
3869  }
3870  getActive() {
3871    return this.#activeEditor;
3872  }
3873  getMode() {
3874    return this.#mode;
3875  }
3876}
3877exports.AnnotationEditorUIManager = AnnotationEditorUIManager;
3878
3879/***/ }),
3880/* 6 */
3881/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
3882
3883
3884
3885Object.defineProperty(exports, "__esModule", ({
3886  value: true
3887}));
3888exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = exports.AnnotationPrefix = void 0;
3889exports.deprecated = deprecated;
3890exports.getColorValues = getColorValues;
3891exports.getCurrentTransform = getCurrentTransform;
3892exports.getCurrentTransformInverse = getCurrentTransformInverse;
3893exports.getFilenameFromUrl = getFilenameFromUrl;
3894exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
3895exports.getRGB = getRGB;
3896exports.getXfaPageViewport = getXfaPageViewport;
3897exports.isDataScheme = isDataScheme;
3898exports.isPdfFile = isPdfFile;
3899exports.isValidFetchUrl = isValidFetchUrl;
3900exports.loadScript = loadScript;
3901exports.setLayerDimensions = setLayerDimensions;
3902var _base_factory = __w_pdfjs_require__(7);
3903var _util = __w_pdfjs_require__(1);
3904const SVG_NS = "http://www.w3.org/2000/svg";
3905const AnnotationPrefix = "pdfjs_internal_id_";
3906exports.AnnotationPrefix = AnnotationPrefix;
3907class PixelsPerInch {
3908  static CSS = 96.0;
3909  static PDF = 72.0;
3910  static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
3911}
3912exports.PixelsPerInch = PixelsPerInch;
3913class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
3914  constructor({
3915    ownerDocument = globalThis.document
3916  } = {}) {
3917    super();
3918    this._document = ownerDocument;
3919  }
3920  _createCanvas(width, height) {
3921    const canvas = this._document.createElement("canvas");
3922    canvas.width = width;
3923    canvas.height = height;
3924    return canvas;
3925  }
3926}
3927exports.DOMCanvasFactory = DOMCanvasFactory;
3928async function fetchData(url, asTypedArray = false) {
3929  if (isValidFetchUrl(url, document.baseURI)) {
3930    const response = await fetch(url);
3931    if (!response.ok) {
3932      throw new Error(response.statusText);
3933    }
3934    return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
3935  }
3936  return new Promise((resolve, reject) => {
3937    const request = new XMLHttpRequest();
3938    request.open("GET", url, true);
3939    if (asTypedArray) {
3940      request.responseType = "arraybuffer";
3941    }
3942    request.onreadystatechange = () => {
3943      if (request.readyState !== XMLHttpRequest.DONE) {
3944        return;
3945      }
3946      if (request.status === 200 || request.status === 0) {
3947        let data;
3948        if (asTypedArray && request.response) {
3949          data = new Uint8Array(request.response);
3950        } else if (!asTypedArray && request.responseText) {
3951          data = (0, _util.stringToBytes)(request.responseText);
3952        }
3953        if (data) {
3954          resolve(data);
3955          return;
3956        }
3957      }
3958      reject(new Error(request.statusText));
3959    };
3960    request.send(null);
3961  });
3962}
3963class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
3964  _fetchData(url, compressionType) {
3965    return fetchData(url, this.isCompressed).then(data => {
3966      return {
3967        cMapData: data,
3968        compressionType
3969      };
3970    });
3971  }
3972}
3973exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
3974class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
3975  _fetchData(url) {
3976    return fetchData(url, true);
3977  }
3978}
3979exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
3980class DOMSVGFactory extends _base_factory.BaseSVGFactory {
3981  _createSVG(type) {
3982    return document.createElementNS(SVG_NS, type);
3983  }
3984}
3985exports.DOMSVGFactory = DOMSVGFactory;
3986class PageViewport {
3987  constructor({
3988    viewBox,
3989    scale,
3990    rotation,
3991    offsetX = 0,
3992    offsetY = 0,
3993    dontFlip = false
3994  }) {
3995    this.viewBox = viewBox;
3996    this.scale = scale;
3997    this.rotation = rotation;
3998    this.offsetX = offsetX;
3999    this.offsetY = offsetY;
4000    const centerX = (viewBox[2] + viewBox[0]) / 2;
4001    const centerY = (viewBox[3] + viewBox[1]) / 2;
4002    let rotateA, rotateB, rotateC, rotateD;
4003    rotation %= 360;
4004    if (rotation < 0) {
4005      rotation += 360;
4006    }
4007    switch (rotation) {
4008      case 180:
4009        rotateA = -1;
4010        rotateB = 0;
4011        rotateC = 0;
4012        rotateD = 1;
4013        break;
4014      case 90:
4015        rotateA = 0;
4016        rotateB = 1;
4017        rotateC = 1;
4018        rotateD = 0;
4019        break;
4020      case 270:
4021        rotateA = 0;
4022        rotateB = -1;
4023        rotateC = -1;
4024        rotateD = 0;
4025        break;
4026      case 0:
4027        rotateA = 1;
4028        rotateB = 0;
4029        rotateC = 0;
4030        rotateD = -1;
4031        break;
4032      default:
4033        throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
4034    }
4035    if (dontFlip) {
4036      rotateC = -rotateC;
4037      rotateD = -rotateD;
4038    }
4039    let offsetCanvasX, offsetCanvasY;
4040    let width, height;
4041    if (rotateA === 0) {
4042      offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
4043      offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
4044      width = (viewBox[3] - viewBox[1]) * scale;
4045      height = (viewBox[2] - viewBox[0]) * scale;
4046    } else {
4047      offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
4048      offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
4049      width = (viewBox[2] - viewBox[0]) * scale;
4050      height = (viewBox[3] - viewBox[1]) * scale;
4051    }
4052    this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
4053    this.width = width;
4054    this.height = height;
4055  }
4056  get rawDims() {
4057    const {
4058      viewBox
4059    } = this;
4060    return (0, _util.shadow)(this, "rawDims", {
4061      pageWidth: viewBox[2] - viewBox[0],
4062      pageHeight: viewBox[3] - viewBox[1],
4063      pageX: viewBox[0],
4064      pageY: viewBox[1]
4065    });
4066  }
4067  clone({
4068    scale = this.scale,
4069    rotation = this.rotation,
4070    offsetX = this.offsetX,
4071    offsetY = this.offsetY,
4072    dontFlip = false
4073  } = {}) {
4074    return new PageViewport({
4075      viewBox: this.viewBox.slice(),
4076      scale,
4077      rotation,
4078      offsetX,
4079      offsetY,
4080      dontFlip
4081    });
4082  }
4083  convertToViewportPoint(x, y) {
4084    return _util.Util.applyTransform([x, y], this.transform);
4085  }
4086  convertToViewportRectangle(rect) {
4087    const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
4088    const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
4089    return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
4090  }
4091  convertToPdfPoint(x, y) {
4092    return _util.Util.applyInverseTransform([x, y], this.transform);
4093  }
4094}
4095exports.PageViewport = PageViewport;
4096class RenderingCancelledException extends _util.BaseException {
4097  constructor(msg, type, extraDelay = 0) {
4098    super(msg, "RenderingCancelledException");
4099    this.type = type;
4100    this.extraDelay = extraDelay;
4101  }
4102}
4103exports.RenderingCancelledException = RenderingCancelledException;
4104function isDataScheme(url) {
4105  const ii = url.length;
4106  let i = 0;
4107  while (i < ii && url[i].trim() === "") {
4108    i++;
4109  }
4110  return url.substring(i, i + 5).toLowerCase() === "data:";
4111}
4112function isPdfFile(filename) {
4113  return typeof filename === "string" && /\.pdf$/i.test(filename);
4114}
4115function getFilenameFromUrl(url, onlyStripPath = false) {
4116  if (!onlyStripPath) {
4117    [url] = url.split(/[#?]/, 1);
4118  }
4119  return url.substring(url.lastIndexOf("/") + 1);
4120}
4121function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
4122  if (typeof url !== "string") {
4123    return defaultFilename;
4124  }
4125  if (isDataScheme(url)) {
4126    (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
4127    return defaultFilename;
4128  }
4129  const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
4130  const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
4131  const splitURI = reURI.exec(url);
4132  let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
4133  if (suggestedFilename) {
4134    suggestedFilename = suggestedFilename[0];
4135    if (suggestedFilename.includes("%")) {
4136      try {
4137        suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
4138      } catch (ex) {}
4139    }
4140  }
4141  return suggestedFilename || defaultFilename;
4142}
4143class StatTimer {
4144  started = Object.create(null);
4145  times = [];
4146  time(name) {
4147    if (name in this.started) {
4148      (0, _util.warn)(`Timer is already running for ${name}`);
4149    }
4150    this.started[name] = Date.now();
4151  }
4152  timeEnd(name) {
4153    if (!(name in this.started)) {
4154      (0, _util.warn)(`Timer has not been started for ${name}`);
4155    }
4156    this.times.push({
4157      name,
4158      start: this.started[name],
4159      end: Date.now()
4160    });
4161    delete this.started[name];
4162  }
4163  toString() {
4164    const outBuf = [];
4165    let longest = 0;
4166    for (const {
4167      name
4168    } of this.times) {
4169      longest = Math.max(name.length, longest);
4170    }
4171    for (const {
4172      name,
4173      start,
4174      end
4175    } of this.times) {
4176      outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
4177    }
4178    return outBuf.join("");
4179  }
4180}
4181exports.StatTimer = StatTimer;
4182function isValidFetchUrl(url, baseUrl) {
4183  try {
4184    const {
4185      protocol
4186    } = baseUrl ? new URL(url, baseUrl) : new URL(url);
4187    return protocol === "http:" || protocol === "https:";
4188  } catch (ex) {
4189    return false;
4190  }
4191}
4192function loadScript(src, removeScriptElement = false) {
4193  return new Promise((resolve, reject) => {
4194    const script = document.createElement("script");
4195    script.src = src;
4196    script.onload = function (evt) {
4197      if (removeScriptElement) {
4198        script.remove();
4199      }
4200      resolve(evt);
4201    };
4202    script.onerror = function () {
4203      reject(new Error(`Cannot load script at: ${script.src}`));
4204    };
4205    (document.head || document.documentElement).append(script);
4206  });
4207}
4208function deprecated(details) {
4209  console.log("Deprecated API usage: " + details);
4210}
4211let pdfDateStringRegex;
4212class PDFDateString {
4213  static toDateObject(input) {
4214    if (!input || typeof input !== "string") {
4215      return null;
4216    }
4217    if (!pdfDateStringRegex) {
4218      pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
4219    }
4220    const matches = pdfDateStringRegex.exec(input);
4221    if (!matches) {
4222      return null;
4223    }
4224    const year = parseInt(matches[1], 10);
4225    let month = parseInt(matches[2], 10);
4226    month = month >= 1 && month <= 12 ? month - 1 : 0;
4227    let day = parseInt(matches[3], 10);
4228    day = day >= 1 && day <= 31 ? day : 1;
4229    let hour = parseInt(matches[4], 10);
4230    hour = hour >= 0 && hour <= 23 ? hour : 0;
4231    let minute = parseInt(matches[5], 10);
4232    minute = minute >= 0 && minute <= 59 ? minute : 0;
4233    let second = parseInt(matches[6], 10);
4234    second = second >= 0 && second <= 59 ? second : 0;
4235    const universalTimeRelation = matches[7] || "Z";
4236    let offsetHour = parseInt(matches[8], 10);
4237    offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
4238    let offsetMinute = parseInt(matches[9], 10) || 0;
4239    offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
4240    if (universalTimeRelation === "-") {
4241      hour += offsetHour;
4242      minute += offsetMinute;
4243    } else if (universalTimeRelation === "+") {
4244      hour -= offsetHour;
4245      minute -= offsetMinute;
4246    }
4247    return new Date(Date.UTC(year, month, day, hour, minute, second));
4248  }
4249}
4250exports.PDFDateString = PDFDateString;
4251function getXfaPageViewport(xfaPage, {
4252  scale = 1,
4253  rotation = 0
4254}) {
4255  const {
4256    width,
4257    height
4258  } = xfaPage.attributes.style;
4259  const viewBox = [0, 0, parseInt(width), parseInt(height)];
4260  return new PageViewport({
4261    viewBox,
4262    scale,
4263    rotation
4264  });
4265}
4266function getRGB(color) {
4267  if (color.startsWith("#")) {
4268    const colorRGB = parseInt(color.slice(1), 16);
4269    return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
4270  }
4271  if (color.startsWith("rgb(")) {
4272    return color.slice(4, -1).split(",").map(x => parseInt(x));
4273  }
4274  if (color.startsWith("rgba(")) {
4275    return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
4276  }
4277  (0, _util.warn)(`Not a valid color format: "${color}"`);
4278  return [0, 0, 0];
4279}
4280function getColorValues(colors) {
4281  const span = document.createElement("span");
4282  span.style.visibility = "hidden";
4283  document.body.append(span);
4284  for (const name of colors.keys()) {
4285    span.style.color = name;
4286    const computedColor = window.getComputedStyle(span).color;
4287    colors.set(name, getRGB(computedColor));
4288  }
4289  span.remove();
4290}
4291function getCurrentTransform(ctx) {
4292  const {
4293    a,
4294    b,
4295    c,
4296    d,
4297    e,
4298    f
4299  } = ctx.getTransform();
4300  return [a, b, c, d, e, f];
4301}
4302function getCurrentTransformInverse(ctx) {
4303  const {
4304    a,
4305    b,
4306    c,
4307    d,
4308    e,
4309    f
4310  } = ctx.getTransform().invertSelf();
4311  return [a, b, c, d, e, f];
4312}
4313function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
4314  if (viewport instanceof PageViewport) {
4315    const {
4316      pageWidth,
4317      pageHeight
4318    } = viewport.rawDims;
4319    const {
4320      style
4321    } = div;
4322    const widthStr = `calc(var(--scale-factor) * ${pageWidth}px)`;
4323    const heightStr = `calc(var(--scale-factor) * ${pageHeight}px)`;
4324    if (!mustFlip || viewport.rotation % 180 === 0) {
4325      style.width = widthStr;
4326      style.height = heightStr;
4327    } else {
4328      style.width = heightStr;
4329      style.height = widthStr;
4330    }
4331  }
4332  if (mustRotate) {
4333    div.setAttribute("data-main-rotation", viewport.rotation);
4334  }
4335}
4336
4337/***/ }),
4338/* 7 */
4339/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4340
4341
4342
4343Object.defineProperty(exports, "__esModule", ({
4344  value: true
4345}));
4346exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
4347var _util = __w_pdfjs_require__(1);
4348class BaseCanvasFactory {
4349  constructor() {
4350    if (this.constructor === BaseCanvasFactory) {
4351      (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
4352    }
4353  }
4354  create(width, height) {
4355    if (width <= 0 || height <= 0) {
4356      throw new Error("Invalid canvas size");
4357    }
4358    const canvas = this._createCanvas(width, height);
4359    return {
4360      canvas,
4361      context: canvas.getContext("2d")
4362    };
4363  }
4364  reset(canvasAndContext, width, height) {
4365    if (!canvasAndContext.canvas) {
4366      throw new Error("Canvas is not specified");
4367    }
4368    if (width <= 0 || height <= 0) {
4369      throw new Error("Invalid canvas size");
4370    }
4371    canvasAndContext.canvas.width = width;
4372    canvasAndContext.canvas.height = height;
4373  }
4374  destroy(canvasAndContext) {
4375    if (!canvasAndContext.canvas) {
4376      throw new Error("Canvas is not specified");
4377    }
4378    canvasAndContext.canvas.width = 0;
4379    canvasAndContext.canvas.height = 0;
4380    canvasAndContext.canvas = null;
4381    canvasAndContext.context = null;
4382  }
4383  _createCanvas(width, height) {
4384    (0, _util.unreachable)("Abstract method `_createCanvas` called.");
4385  }
4386}
4387exports.BaseCanvasFactory = BaseCanvasFactory;
4388class BaseCMapReaderFactory {
4389  constructor({
4390    baseUrl = null,
4391    isCompressed = true
4392  }) {
4393    if (this.constructor === BaseCMapReaderFactory) {
4394      (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
4395    }
4396    this.baseUrl = baseUrl;
4397    this.isCompressed = isCompressed;
4398  }
4399  async fetch({
4400    name
4401  }) {
4402    if (!this.baseUrl) {
4403      throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
4404    }
4405    if (!name) {
4406      throw new Error("CMap name must be specified.");
4407    }
4408    const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
4409    const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
4410    return this._fetchData(url, compressionType).catch(reason => {
4411      throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
4412    });
4413  }
4414  _fetchData(url, compressionType) {
4415    (0, _util.unreachable)("Abstract method `_fetchData` called.");
4416  }
4417}
4418exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
4419class BaseStandardFontDataFactory {
4420  constructor({
4421    baseUrl = null
4422  }) {
4423    if (this.constructor === BaseStandardFontDataFactory) {
4424      (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
4425    }
4426    this.baseUrl = baseUrl;
4427  }
4428  async fetch({
4429    filename
4430  }) {
4431    if (!this.baseUrl) {
4432      throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
4433    }
4434    if (!filename) {
4435      throw new Error("Font filename must be specified.");
4436    }
4437    const url = `${this.baseUrl}${filename}`;
4438    return this._fetchData(url).catch(reason => {
4439      throw new Error(`Unable to load font data at: ${url}`);
4440    });
4441  }
4442  _fetchData(url) {
4443    (0, _util.unreachable)("Abstract method `_fetchData` called.");
4444  }
4445}
4446exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
4447class BaseSVGFactory {
4448  constructor() {
4449    if (this.constructor === BaseSVGFactory) {
4450      (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
4451    }
4452  }
4453  create(width, height, skipDimensions = false) {
4454    if (width <= 0 || height <= 0) {
4455      throw new Error("Invalid SVG dimensions");
4456    }
4457    const svg = this._createSVG("svg:svg");
4458    svg.setAttribute("version", "1.1");
4459    if (!skipDimensions) {
4460      svg.setAttribute("width", `${width}px`);
4461      svg.setAttribute("height", `${height}px`);
4462    }
4463    svg.setAttribute("preserveAspectRatio", "none");
4464    svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
4465    return svg;
4466  }
4467  createElement(type) {
4468    if (typeof type !== "string") {
4469      throw new Error("Invalid SVG element type");
4470    }
4471    return this._createSVG(type);
4472  }
4473  _createSVG(type) {
4474    (0, _util.unreachable)("Abstract method `_createSVG` called.");
4475  }
4476}
4477exports.BaseSVGFactory = BaseSVGFactory;
4478
4479/***/ }),
4480/* 8 */
4481/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4482
4483
4484
4485Object.defineProperty(exports, "__esModule", ({
4486  value: true
4487}));
4488exports.MurmurHash3_64 = void 0;
4489var _util = __w_pdfjs_require__(1);
4490const SEED = 0xc3d2e1f0;
4491const MASK_HIGH = 0xffff0000;
4492const MASK_LOW = 0xffff;
4493class MurmurHash3_64 {
4494  constructor(seed) {
4495    this.h1 = seed ? seed & 0xffffffff : SEED;
4496    this.h2 = seed ? seed & 0xffffffff : SEED;
4497  }
4498  update(input) {
4499    let data, length;
4500    if (typeof input === "string") {
4501      data = new Uint8Array(input.length * 2);
4502      length = 0;
4503      for (let i = 0, ii = input.length; i < ii; i++) {
4504        const code = input.charCodeAt(i);
4505        if (code <= 0xff) {
4506          data[length++] = code;
4507        } else {
4508          data[length++] = code >>> 8;
4509          data[length++] = code & 0xff;
4510        }
4511      }
4512    } else if ((0, _util.isArrayBuffer)(input)) {
4513      data = input.slice();
4514      length = data.byteLength;
4515    } else {
4516      throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
4517    }
4518    const blockCounts = length >> 2;
4519    const tailLength = length - blockCounts * 4;
4520    const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
4521    let k1 = 0,
4522      k2 = 0;
4523    let h1 = this.h1,
4524      h2 = this.h2;
4525    const C1 = 0xcc9e2d51,
4526      C2 = 0x1b873593;
4527    const C1_LOW = C1 & MASK_LOW,
4528      C2_LOW = C2 & MASK_LOW;
4529    for (let i = 0; i < blockCounts; i++) {
4530      if (i & 1) {
4531        k1 = dataUint32[i];
4532        k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
4533        k1 = k1 << 15 | k1 >>> 17;
4534        k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
4535        h1 ^= k1;
4536        h1 = h1 << 13 | h1 >>> 19;
4537        h1 = h1 * 5 + 0xe6546b64;
4538      } else {
4539        k2 = dataUint32[i];
4540        k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
4541        k2 = k2 << 15 | k2 >>> 17;
4542        k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
4543        h2 ^= k2;
4544        h2 = h2 << 13 | h2 >>> 19;
4545        h2 = h2 * 5 + 0xe6546b64;
4546      }
4547    }
4548    k1 = 0;
4549    switch (tailLength) {
4550      case 3:
4551        k1 ^= data[blockCounts * 4 + 2] << 16;
4552      case 2:
4553        k1 ^= data[blockCounts * 4 + 1] << 8;
4554      case 1:
4555        k1 ^= data[blockCounts * 4];
4556        k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
4557        k1 = k1 << 15 | k1 >>> 17;
4558        k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
4559        if (blockCounts & 1) {
4560          h1 ^= k1;
4561        } else {
4562          h2 ^= k1;
4563        }
4564    }
4565    this.h1 = h1;
4566    this.h2 = h2;
4567  }
4568  hexdigest() {
4569    let h1 = this.h1,
4570      h2 = this.h2;
4571    h1 ^= h2 >>> 1;
4572    h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
4573    h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
4574    h1 ^= h2 >>> 1;
4575    h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
4576    h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
4577    h1 ^= h2 >>> 1;
4578    return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
4579  }
4580}
4581exports.MurmurHash3_64 = MurmurHash3_64;
4582
4583/***/ }),
4584/* 9 */
4585/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4586
4587
4588
4589Object.defineProperty(exports, "__esModule", ({
4590  value: true
4591}));
4592exports.FontLoader = exports.FontFaceObject = void 0;
4593var _util = __w_pdfjs_require__(1);
4594var _is_node = __w_pdfjs_require__(10);
4595class FontLoader {
4596  constructor({
4597    onUnsupportedFeature,
4598    ownerDocument = globalThis.document,
4599    styleElement = null
4600  }) {
4601    this._onUnsupportedFeature = onUnsupportedFeature;
4602    this._document = ownerDocument;
4603    this.nativeFontFaces = [];
4604    this.styleElement = null;
4605    this.loadingRequests = [];
4606    this.loadTestFontId = 0;
4607  }
4608  addNativeFontFace(nativeFontFace) {
4609    this.nativeFontFaces.push(nativeFontFace);
4610    this._document.fonts.add(nativeFontFace);
4611  }
4612  insertRule(rule) {
4613    if (!this.styleElement) {
4614      this.styleElement = this._document.createElement("style");
4615      this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
4616    }
4617    const styleSheet = this.styleElement.sheet;
4618    styleSheet.insertRule(rule, styleSheet.cssRules.length);
4619  }
4620  clear() {
4621    for (const nativeFontFace of this.nativeFontFaces) {
4622      this._document.fonts.delete(nativeFontFace);
4623    }
4624    this.nativeFontFaces.length = 0;
4625    if (this.styleElement) {
4626      this.styleElement.remove();
4627      this.styleElement = null;
4628    }
4629  }
4630  async bind(font) {
4631    if (font.attached || font.missingFile) {
4632      return;
4633    }
4634    font.attached = true;
4635    if (this.isFontLoadingAPISupported) {
4636      const nativeFontFace = font.createNativeFontFace();
4637      if (nativeFontFace) {
4638        this.addNativeFontFace(nativeFontFace);
4639        try {
4640          await nativeFontFace.loaded;
4641        } catch (ex) {
4642          this._onUnsupportedFeature({
4643            featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
4644          });
4645          (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
4646          font.disableFontFace = true;
4647          throw ex;
4648        }
4649      }
4650      return;
4651    }
4652    const rule = font.createFontFaceRule();
4653    if (rule) {
4654      this.insertRule(rule);
4655      if (this.isSyncFontLoadingSupported) {
4656        return;
4657      }
4658      await new Promise(resolve => {
4659        const request = this._queueLoadingCallback(resolve);
4660        this._prepareFontLoadEvent(font, request);
4661      });
4662    }
4663  }
4664  get isFontLoadingAPISupported() {
4665    const hasFonts = !!this._document?.fonts;
4666    return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
4667  }
4668  get isSyncFontLoadingSupported() {
4669    let supported = false;
4670    if (_is_node.isNodeJS) {
4671      supported = true;
4672    } else if (typeof navigator !== "undefined" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
4673      supported = true;
4674    }
4675    return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
4676  }
4677  _queueLoadingCallback(callback) {
4678    function completeRequest() {
4679      (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
4680      request.done = true;
4681      while (loadingRequests.length > 0 && loadingRequests[0].done) {
4682        const otherRequest = loadingRequests.shift();
4683        setTimeout(otherRequest.callback, 0);
4684      }
4685    }
4686    const {
4687      loadingRequests
4688    } = this;
4689    const request = {
4690      done: false,
4691      complete: completeRequest,
4692      callback
4693    };
4694    loadingRequests.push(request);
4695    return request;
4696  }
4697  get _loadTestFont() {
4698    const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
4699    return (0, _util.shadow)(this, "_loadTestFont", testFont);
4700  }
4701  _prepareFontLoadEvent(font, request) {
4702    function int32(data, offset) {
4703      return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
4704    }
4705    function spliceString(s, offset, remove, insert) {
4706      const chunk1 = s.substring(0, offset);
4707      const chunk2 = s.substring(offset + remove);
4708      return chunk1 + insert + chunk2;
4709    }
4710    let i, ii;
4711    const canvas = this._document.createElement("canvas");
4712    canvas.width = 1;
4713    canvas.height = 1;
4714    const ctx = canvas.getContext("2d");
4715    let called = 0;
4716    function isFontReady(name, callback) {
4717      if (++called > 30) {
4718        (0, _util.warn)("Load test font never loaded.");
4719        callback();
4720        return;
4721      }
4722      ctx.font = "30px " + name;
4723      ctx.fillText(".", 0, 20);
4724      const imageData = ctx.getImageData(0, 0, 1, 1);
4725      if (imageData.data[3] > 0) {
4726        callback();
4727        return;
4728      }
4729      setTimeout(isFontReady.bind(null, name, callback));
4730    }
4731    const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
4732    let data = this._loadTestFont;
4733    const COMMENT_OFFSET = 976;
4734    data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
4735    const CFF_CHECKSUM_OFFSET = 16;
4736    const XXXX_VALUE = 0x58585858;
4737    let checksum = int32(data, CFF_CHECKSUM_OFFSET);
4738    for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
4739      checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
4740    }
4741    if (i < loadTestFontId.length) {
4742      checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
4743    }
4744    data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
4745    const url = `url(data:font/opentype;base64,${btoa(data)});`;
4746    const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
4747    this.insertRule(rule);
4748    const div = this._document.createElement("div");
4749    div.style.visibility = "hidden";
4750    div.style.width = div.style.height = "10px";
4751    div.style.position = "absolute";
4752    div.style.top = div.style.left = "0px";
4753    for (const name of [font.loadedName, loadTestFontId]) {
4754      const span = this._document.createElement("span");
4755      span.textContent = "Hi";
4756      span.style.fontFamily = name;
4757      div.append(span);
4758    }
4759    this._document.body.append(div);
4760    isFontReady(loadTestFontId, () => {
4761      div.remove();
4762      request.complete();
4763    });
4764  }
4765}
4766exports.FontLoader = FontLoader;
4767class FontFaceObject {
4768  constructor(translatedData, {
4769    isEvalSupported = true,
4770    disableFontFace = false,
4771    ignoreErrors = false,
4772    onUnsupportedFeature,
4773    fontRegistry = null
4774  }) {
4775    this.compiledGlyphs = Object.create(null);
4776    for (const i in translatedData) {
4777      this[i] = translatedData[i];
4778    }
4779    this.isEvalSupported = isEvalSupported !== false;
4780    this.disableFontFace = disableFontFace === true;
4781    this.ignoreErrors = ignoreErrors === true;
4782    this._onUnsupportedFeature = onUnsupportedFeature;
4783    this.fontRegistry = fontRegistry;
4784  }
4785  createNativeFontFace() {
4786    if (!this.data || this.disableFontFace) {
4787      return null;
4788    }
4789    let nativeFontFace;
4790    if (!this.cssFontInfo) {
4791      nativeFontFace = new FontFace(this.loadedName, this.data, {});
4792    } else {
4793      const css = {
4794        weight: this.cssFontInfo.fontWeight
4795      };
4796      if (this.cssFontInfo.italicAngle) {
4797        css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
4798      }
4799      nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
4800    }
4801    this.fontRegistry?.registerFont(this);
4802    return nativeFontFace;
4803  }
4804  createFontFaceRule() {
4805    if (!this.data || this.disableFontFace) {
4806      return null;
4807    }
4808    const data = (0, _util.bytesToString)(this.data);
4809    const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
4810    let rule;
4811    if (!this.cssFontInfo) {
4812      rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
4813    } else {
4814      let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
4815      if (this.cssFontInfo.italicAngle) {
4816        css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
4817      }
4818      rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
4819    }
4820    this.fontRegistry?.registerFont(this, url);
4821    return rule;
4822  }
4823  getPathGenerator(objs, character) {
4824    if (this.compiledGlyphs[character] !== undefined) {
4825      return this.compiledGlyphs[character];
4826    }
4827    let cmds;
4828    try {
4829      cmds = objs.get(this.loadedName + "_path_" + character);
4830    } catch (ex) {
4831      if (!this.ignoreErrors) {
4832        throw ex;
4833      }
4834      this._onUnsupportedFeature({
4835        featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
4836      });
4837      (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
4838      return this.compiledGlyphs[character] = function (c, size) {};
4839    }
4840    if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
4841      const jsBuf = [];
4842      for (const current of cmds) {
4843        const args = current.args !== undefined ? current.args.join(",") : "";
4844        jsBuf.push("c.", current.cmd, "(", args, ");\n");
4845      }
4846      return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
4847    }
4848    return this.compiledGlyphs[character] = function (c, size) {
4849      for (const current of cmds) {
4850        if (current.cmd === "scale") {
4851          current.args = [size, -size];
4852        }
4853        c[current.cmd].apply(c, current.args);
4854      }
4855    };
4856  }
4857}
4858exports.FontFaceObject = FontFaceObject;
4859
4860/***/ }),
4861/* 10 */
4862/***/ ((__unused_webpack_module, exports) => {
4863
4864
4865
4866Object.defineProperty(exports, "__esModule", ({
4867  value: true
4868}));
4869exports.isNodeJS = void 0;
4870const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
4871exports.isNodeJS = isNodeJS;
4872
4873/***/ }),
4874/* 11 */
4875/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4876
4877
4878
4879Object.defineProperty(exports, "__esModule", ({
4880  value: true
4881}));
4882exports.CanvasGraphics = void 0;
4883var _util = __w_pdfjs_require__(1);
4884var _display_utils = __w_pdfjs_require__(6);
4885var _pattern_helper = __w_pdfjs_require__(12);
4886var _image_utils = __w_pdfjs_require__(13);
4887const MIN_FONT_SIZE = 16;
4888const MAX_FONT_SIZE = 100;
4889const MAX_GROUP_SIZE = 4096;
4890const EXECUTION_TIME = 15;
4891const EXECUTION_STEPS = 10;
4892const MAX_SIZE_TO_COMPILE = 1000;
4893const FULL_CHUNK_HEIGHT = 16;
4894function mirrorContextOperations(ctx, destCtx) {
4895  if (ctx._removeMirroring) {
4896    throw new Error("Context is already forwarding operations.");
4897  }
4898  ctx.__originalSave = ctx.save;
4899  ctx.__originalRestore = ctx.restore;
4900  ctx.__originalRotate = ctx.rotate;
4901  ctx.__originalScale = ctx.scale;
4902  ctx.__originalTranslate = ctx.translate;
4903  ctx.__originalTransform = ctx.transform;
4904  ctx.__originalSetTransform = ctx.setTransform;
4905  ctx.__originalResetTransform = ctx.resetTransform;
4906  ctx.__originalClip = ctx.clip;
4907  ctx.__originalMoveTo = ctx.moveTo;
4908  ctx.__originalLineTo = ctx.lineTo;
4909  ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
4910  ctx.__originalRect = ctx.rect;
4911  ctx.__originalClosePath = ctx.closePath;
4912  ctx.__originalBeginPath = ctx.beginPath;
4913  ctx._removeMirroring = () => {
4914    ctx.save = ctx.__originalSave;
4915    ctx.restore = ctx.__originalRestore;
4916    ctx.rotate = ctx.__originalRotate;
4917    ctx.scale = ctx.__originalScale;
4918    ctx.translate = ctx.__originalTranslate;
4919    ctx.transform = ctx.__originalTransform;
4920    ctx.setTransform = ctx.__originalSetTransform;
4921    ctx.resetTransform = ctx.__originalResetTransform;
4922    ctx.clip = ctx.__originalClip;
4923    ctx.moveTo = ctx.__originalMoveTo;
4924    ctx.lineTo = ctx.__originalLineTo;
4925    ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
4926    ctx.rect = ctx.__originalRect;
4927    ctx.closePath = ctx.__originalClosePath;
4928    ctx.beginPath = ctx.__originalBeginPath;
4929    delete ctx._removeMirroring;
4930  };
4931  ctx.save = function ctxSave() {
4932    destCtx.save();
4933    this.__originalSave();
4934  };
4935  ctx.restore = function ctxRestore() {
4936    destCtx.restore();
4937    this.__originalRestore();
4938  };
4939  ctx.translate = function ctxTranslate(x, y) {
4940    destCtx.translate(x, y);
4941    this.__originalTranslate(x, y);
4942  };
4943  ctx.scale = function ctxScale(x, y) {
4944    destCtx.scale(x, y);
4945    this.__originalScale(x, y);
4946  };
4947  ctx.transform = function ctxTransform(a, b, c, d, e, f) {
4948    destCtx.transform(a, b, c, d, e, f);
4949    this.__originalTransform(a, b, c, d, e, f);
4950  };
4951  ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
4952    destCtx.setTransform(a, b, c, d, e, f);
4953    this.__originalSetTransform(a, b, c, d, e, f);
4954  };
4955  ctx.resetTransform = function ctxResetTransform() {
4956    destCtx.resetTransform();
4957    this.__originalResetTransform();
4958  };
4959  ctx.rotate = function ctxRotate(angle) {
4960    destCtx.rotate(angle);
4961    this.__originalRotate(angle);
4962  };
4963  ctx.clip = function ctxRotate(rule) {
4964    destCtx.clip(rule);
4965    this.__originalClip(rule);
4966  };
4967  ctx.moveTo = function (x, y) {
4968    destCtx.moveTo(x, y);
4969    this.__originalMoveTo(x, y);
4970  };
4971  ctx.lineTo = function (x, y) {
4972    destCtx.lineTo(x, y);
4973    this.__originalLineTo(x, y);
4974  };
4975  ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
4976    destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
4977    this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
4978  };
4979  ctx.rect = function (x, y, width, height) {
4980    destCtx.rect(x, y, width, height);
4981    this.__originalRect(x, y, width, height);
4982  };
4983  ctx.closePath = function () {
4984    destCtx.closePath();
4985    this.__originalClosePath();
4986  };
4987  ctx.beginPath = function () {
4988    destCtx.beginPath();
4989    this.__originalBeginPath();
4990  };
4991}
4992class CachedCanvases {
4993  constructor(canvasFactory) {
4994    this.canvasFactory = canvasFactory;
4995    this.cache = Object.create(null);
4996  }
4997  getCanvas(id, width, height) {
4998    let canvasEntry;
4999    if (this.cache[id] !== undefined) {
5000      canvasEntry = this.cache[id];
5001      this.canvasFactory.reset(canvasEntry, width, height);
5002    } else {
5003      canvasEntry = this.canvasFactory.create(width, height);
5004      this.cache[id] = canvasEntry;
5005    }
5006    return canvasEntry;
5007  }
5008  delete(id) {
5009    delete this.cache[id];
5010  }
5011  clear() {
5012    for (const id in this.cache) {
5013      const canvasEntry = this.cache[id];
5014      this.canvasFactory.destroy(canvasEntry);
5015      delete this.cache[id];
5016    }
5017  }
5018}
5019function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
5020  const [a, b, c, d, tx, ty] = (0, _display_utils.getCurrentTransform)(ctx);
5021  if (b === 0 && c === 0) {
5022    const tlX = destX * a + tx;
5023    const rTlX = Math.round(tlX);
5024    const tlY = destY * d + ty;
5025    const rTlY = Math.round(tlY);
5026    const brX = (destX + destW) * a + tx;
5027    const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
5028    const brY = (destY + destH) * d + ty;
5029    const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
5030    ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
5031    ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
5032    ctx.setTransform(a, b, c, d, tx, ty);
5033    return [rWidth, rHeight];
5034  }
5035  if (a === 0 && d === 0) {
5036    const tlX = destY * c + tx;
5037    const rTlX = Math.round(tlX);
5038    const tlY = destX * b + ty;
5039    const rTlY = Math.round(tlY);
5040    const brX = (destY + destH) * c + tx;
5041    const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
5042    const brY = (destX + destW) * b + ty;
5043    const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
5044    ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
5045    ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
5046    ctx.setTransform(a, b, c, d, tx, ty);
5047    return [rHeight, rWidth];
5048  }
5049  ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
5050  const scaleX = Math.hypot(a, b);
5051  const scaleY = Math.hypot(c, d);
5052  return [scaleX * destW, scaleY * destH];
5053}
5054function compileType3Glyph(imgData) {
5055  const {
5056    width,
5057    height
5058  } = imgData;
5059  if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
5060    return null;
5061  }
5062  const POINT_TO_PROCESS_LIMIT = 1000;
5063  const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
5064  const width1 = width + 1;
5065  let points = new Uint8Array(width1 * (height + 1));
5066  let i, j, j0;
5067  const lineSize = width + 7 & ~7;
5068  let data = new Uint8Array(lineSize * height),
5069    pos = 0;
5070  for (const elem of imgData.data) {
5071    let mask = 128;
5072    while (mask > 0) {
5073      data[pos++] = elem & mask ? 0 : 255;
5074      mask >>= 1;
5075    }
5076  }
5077  let count = 0;
5078  pos = 0;
5079  if (data[pos] !== 0) {
5080    points[0] = 1;
5081    ++count;
5082  }
5083  for (j = 1; j < width; j++) {
5084    if (data[pos] !== data[pos + 1]) {
5085      points[j] = data[pos] ? 2 : 1;
5086      ++count;
5087    }
5088    pos++;
5089  }
5090  if (data[pos] !== 0) {
5091    points[j] = 2;
5092    ++count;
5093  }
5094  for (i = 1; i < height; i++) {
5095    pos = i * lineSize;
5096    j0 = i * width1;
5097    if (data[pos - lineSize] !== data[pos]) {
5098      points[j0] = data[pos] ? 1 : 8;
5099      ++count;
5100    }
5101    let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
5102    for (j = 1; j < width; j++) {
5103      sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
5104      if (POINT_TYPES[sum]) {
5105        points[j0 + j] = POINT_TYPES[sum];
5106        ++count;
5107      }
5108      pos++;
5109    }
5110    if (data[pos - lineSize] !== data[pos]) {
5111      points[j0 + j] = data[pos] ? 2 : 4;
5112      ++count;
5113    }
5114    if (count > POINT_TO_PROCESS_LIMIT) {
5115      return null;
5116    }
5117  }
5118  pos = lineSize * (height - 1);
5119  j0 = i * width1;
5120  if (data[pos] !== 0) {
5121    points[j0] = 8;
5122    ++count;
5123  }
5124  for (j = 1; j < width; j++) {
5125    if (data[pos] !== data[pos + 1]) {
5126      points[j0 + j] = data[pos] ? 4 : 8;
5127      ++count;
5128    }
5129    pos++;
5130  }
5131  if (data[pos] !== 0) {
5132    points[j0 + j] = 4;
5133    ++count;
5134  }
5135  if (count > POINT_TO_PROCESS_LIMIT) {
5136    return null;
5137  }
5138  const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
5139  const path = new Path2D();
5140  for (i = 0; count && i <= height; i++) {
5141    let p = i * width1;
5142    const end = p + width;
5143    while (p < end && !points[p]) {
5144      p++;
5145    }
5146    if (p === end) {
5147      continue;
5148    }
5149    path.moveTo(p % width1, i);
5150    const p0 = p;
5151    let type = points[p];
5152    do {
5153      const step = steps[type];
5154      do {
5155        p += step;
5156      } while (!points[p]);
5157      const pp = points[p];
5158      if (pp !== 5 && pp !== 10) {
5159        type = pp;
5160        points[p] = 0;
5161      } else {
5162        type = pp & 0x33 * type >> 4;
5163        points[p] &= type >> 2 | type << 2;
5164      }
5165      path.lineTo(p % width1, p / width1 | 0);
5166      if (!points[p]) {
5167        --count;
5168      }
5169    } while (p0 !== p);
5170    --i;
5171  }
5172  data = null;
5173  points = null;
5174  const drawOutline = function (c) {
5175    c.save();
5176    c.scale(1 / width, -1 / height);
5177    c.translate(0, -height);
5178    c.fill(path);
5179    c.beginPath();
5180    c.restore();
5181  };
5182  return drawOutline;
5183}
5184class CanvasExtraState {
5185  constructor(width, height) {
5186    this.alphaIsShape = false;
5187    this.fontSize = 0;
5188    this.fontSizeScale = 1;
5189    this.textMatrix = _util.IDENTITY_MATRIX;
5190    this.textMatrixScale = 1;
5191    this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
5192    this.leading = 0;
5193    this.x = 0;
5194    this.y = 0;
5195    this.lineX = 0;
5196    this.lineY = 0;
5197    this.charSpacing = 0;
5198    this.wordSpacing = 0;
5199    this.textHScale = 1;
5200    this.textRenderingMode = _util.TextRenderingMode.FILL;
5201    this.textRise = 0;
5202    this.fillColor = "#000000";
5203    this.strokeColor = "#000000";
5204    this.patternFill = false;
5205    this.fillAlpha = 1;
5206    this.strokeAlpha = 1;
5207    this.lineWidth = 1;
5208    this.activeSMask = null;
5209    this.transferMaps = null;
5210    this.startNewPathAndClipBox([0, 0, width, height]);
5211  }
5212  clone() {
5213    const clone = Object.create(this);
5214    clone.clipBox = this.clipBox.slice();
5215    return clone;
5216  }
5217  setCurrentPoint(x, y) {
5218    this.x = x;
5219    this.y = y;
5220  }
5221  updatePathMinMax(transform, x, y) {
5222    [x, y] = _util.Util.applyTransform([x, y], transform);
5223    this.minX = Math.min(this.minX, x);
5224    this.minY = Math.min(this.minY, y);
5225    this.maxX = Math.max(this.maxX, x);
5226    this.maxY = Math.max(this.maxY, y);
5227  }
5228  updateRectMinMax(transform, rect) {
5229    const p1 = _util.Util.applyTransform(rect, transform);
5230    const p2 = _util.Util.applyTransform(rect.slice(2), transform);
5231    this.minX = Math.min(this.minX, p1[0], p2[0]);
5232    this.minY = Math.min(this.minY, p1[1], p2[1]);
5233    this.maxX = Math.max(this.maxX, p1[0], p2[0]);
5234    this.maxY = Math.max(this.maxY, p1[1], p2[1]);
5235  }
5236  updateScalingPathMinMax(transform, minMax) {
5237    _util.Util.scaleMinMax(transform, minMax);
5238    this.minX = Math.min(this.minX, minMax[0]);
5239    this.maxX = Math.max(this.maxX, minMax[1]);
5240    this.minY = Math.min(this.minY, minMax[2]);
5241    this.maxY = Math.max(this.maxY, minMax[3]);
5242  }
5243  updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
5244    const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
5245    if (minMax) {
5246      minMax[0] = Math.min(minMax[0], box[0], box[2]);
5247      minMax[1] = Math.max(minMax[1], box[0], box[2]);
5248      minMax[2] = Math.min(minMax[2], box[1], box[3]);
5249      minMax[3] = Math.max(minMax[3], box[1], box[3]);
5250      return;
5251    }
5252    this.updateRectMinMax(transform, box);
5253  }
5254  getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
5255    const box = [this.minX, this.minY, this.maxX, this.maxY];
5256    if (pathType === _pattern_helper.PathType.STROKE) {
5257      if (!transform) {
5258        (0, _util.unreachable)("Stroke bounding box must include transform.");
5259      }
5260      const scale = _util.Util.singularValueDecompose2dScale(transform);
5261      const xStrokePad = scale[0] * this.lineWidth / 2;
5262      const yStrokePad = scale[1] * this.lineWidth / 2;
5263      box[0] -= xStrokePad;
5264      box[1] -= yStrokePad;
5265      box[2] += xStrokePad;
5266      box[3] += yStrokePad;
5267    }
5268    return box;
5269  }
5270  updateClipFromPath() {
5271    const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
5272    this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
5273  }
5274  isEmptyClip() {
5275    return this.minX === Infinity;
5276  }
5277  startNewPathAndClipBox(box) {
5278    this.clipBox = box;
5279    this.minX = Infinity;
5280    this.minY = Infinity;
5281    this.maxX = 0;
5282    this.maxY = 0;
5283  }
5284  getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
5285    return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
5286  }
5287}
5288function putBinaryImageData(ctx, imgData, transferMaps = null) {
5289  if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
5290    ctx.putImageData(imgData, 0, 0);
5291    return;
5292  }
5293  const height = imgData.height,
5294    width = imgData.width;
5295  const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
5296  const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
5297  const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
5298  const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
5299  let srcPos = 0,
5300    destPos;
5301  const src = imgData.data;
5302  const dest = chunkImgData.data;
5303  let i, j, thisChunkHeight, elemsInThisChunk;
5304  let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
5305  if (transferMaps) {
5306    switch (transferMaps.length) {
5307      case 1:
5308        transferMapRed = transferMaps[0];
5309        transferMapGreen = transferMaps[0];
5310        transferMapBlue = transferMaps[0];
5311        transferMapGray = transferMaps[0];
5312        break;
5313      case 4:
5314        transferMapRed = transferMaps[0];
5315        transferMapGreen = transferMaps[1];
5316        transferMapBlue = transferMaps[2];
5317        transferMapGray = transferMaps[3];
5318        break;
5319    }
5320  }
5321  if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
5322    const srcLength = src.byteLength;
5323    const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
5324    const dest32DataLength = dest32.length;
5325    const fullSrcDiff = width + 7 >> 3;
5326    let white = 0xffffffff;
5327    let black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
5328    if (transferMapGray) {
5329      if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
5330        [white, black] = [black, white];
5331      }
5332    }
5333    for (i = 0; i < totalChunks; i++) {
5334      thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
5335      destPos = 0;
5336      for (j = 0; j < thisChunkHeight; j++) {
5337        const srcDiff = srcLength - srcPos;
5338        let k = 0;
5339        const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
5340        const kEndUnrolled = kEnd & ~7;
5341        let mask = 0;
5342        let srcByte = 0;
5343        for (; k < kEndUnrolled; k += 8) {
5344          srcByte = src[srcPos++];
5345          dest32[destPos++] = srcByte & 128 ? white : black;
5346          dest32[destPos++] = srcByte & 64 ? white : black;
5347          dest32[destPos++] = srcByte & 32 ? white : black;
5348          dest32[destPos++] = srcByte & 16 ? white : black;
5349          dest32[destPos++] = srcByte & 8 ? white : black;
5350          dest32[destPos++] = srcByte & 4 ? white : black;
5351          dest32[destPos++] = srcByte & 2 ? white : black;
5352          dest32[destPos++] = srcByte & 1 ? white : black;
5353        }
5354        for (; k < kEnd; k++) {
5355          if (mask === 0) {
5356            srcByte = src[srcPos++];
5357            mask = 128;
5358          }
5359          dest32[destPos++] = srcByte & mask ? white : black;
5360          mask >>= 1;
5361        }
5362      }
5363      while (destPos < dest32DataLength) {
5364        dest32[destPos++] = 0;
5365      }
5366      ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5367    }
5368  } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
5369    const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
5370    j = 0;
5371    elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
5372    for (i = 0; i < fullChunks; i++) {
5373      dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
5374      srcPos += elemsInThisChunk;
5375      if (hasTransferMaps) {
5376        for (let k = 0; k < elemsInThisChunk; k += 4) {
5377          if (transferMapRed) {
5378            dest[k + 0] = transferMapRed[dest[k + 0]];
5379          }
5380          if (transferMapGreen) {
5381            dest[k + 1] = transferMapGreen[dest[k + 1]];
5382          }
5383          if (transferMapBlue) {
5384            dest[k + 2] = transferMapBlue[dest[k + 2]];
5385          }
5386        }
5387      }
5388      ctx.putImageData(chunkImgData, 0, j);
5389      j += FULL_CHUNK_HEIGHT;
5390    }
5391    if (i < totalChunks) {
5392      elemsInThisChunk = width * partialChunkHeight * 4;
5393      dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
5394      if (hasTransferMaps) {
5395        for (let k = 0; k < elemsInThisChunk; k += 4) {
5396          if (transferMapRed) {
5397            dest[k + 0] = transferMapRed[dest[k + 0]];
5398          }
5399          if (transferMapGreen) {
5400            dest[k + 1] = transferMapGreen[dest[k + 1]];
5401          }
5402          if (transferMapBlue) {
5403            dest[k + 2] = transferMapBlue[dest[k + 2]];
5404          }
5405        }
5406      }
5407      ctx.putImageData(chunkImgData, 0, j);
5408    }
5409  } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
5410    const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
5411    thisChunkHeight = FULL_CHUNK_HEIGHT;
5412    elemsInThisChunk = width * thisChunkHeight;
5413    for (i = 0; i < totalChunks; i++) {
5414      if (i >= fullChunks) {
5415        thisChunkHeight = partialChunkHeight;
5416        elemsInThisChunk = width * thisChunkHeight;
5417      }
5418      destPos = 0;
5419      for (j = elemsInThisChunk; j--;) {
5420        dest[destPos++] = src[srcPos++];
5421        dest[destPos++] = src[srcPos++];
5422        dest[destPos++] = src[srcPos++];
5423        dest[destPos++] = 255;
5424      }
5425      if (hasTransferMaps) {
5426        for (let k = 0; k < destPos; k += 4) {
5427          if (transferMapRed) {
5428            dest[k + 0] = transferMapRed[dest[k + 0]];
5429          }
5430          if (transferMapGreen) {
5431            dest[k + 1] = transferMapGreen[dest[k + 1]];
5432          }
5433          if (transferMapBlue) {
5434            dest[k + 2] = transferMapBlue[dest[k + 2]];
5435          }
5436        }
5437      }
5438      ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5439    }
5440  } else {
5441    throw new Error(`bad image kind: ${imgData.kind}`);
5442  }
5443}
5444function putBinaryImageMask(ctx, imgData) {
5445  if (imgData.bitmap) {
5446    ctx.drawImage(imgData.bitmap, 0, 0);
5447    return;
5448  }
5449  const height = imgData.height,
5450    width = imgData.width;
5451  const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
5452  const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
5453  const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
5454  const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
5455  let srcPos = 0;
5456  const src = imgData.data;
5457  const dest = chunkImgData.data;
5458  for (let i = 0; i < totalChunks; i++) {
5459    const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
5460    ({
5461      srcPos
5462    } = (0, _image_utils.applyMaskImageData)({
5463      src,
5464      srcPos,
5465      dest,
5466      width,
5467      height: thisChunkHeight
5468    }));
5469    ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5470  }
5471}
5472function copyCtxState(sourceCtx, destCtx) {
5473  const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
5474  for (const property of properties) {
5475    if (sourceCtx[property] !== undefined) {
5476      destCtx[property] = sourceCtx[property];
5477    }
5478  }
5479  if (sourceCtx.setLineDash !== undefined) {
5480    destCtx.setLineDash(sourceCtx.getLineDash());
5481    destCtx.lineDashOffset = sourceCtx.lineDashOffset;
5482  }
5483}
5484function resetCtxToDefault(ctx, foregroundColor) {
5485  ctx.strokeStyle = ctx.fillStyle = foregroundColor || "#000000";
5486  ctx.fillRule = "nonzero";
5487  ctx.globalAlpha = 1;
5488  ctx.lineWidth = 1;
5489  ctx.lineCap = "butt";
5490  ctx.lineJoin = "miter";
5491  ctx.miterLimit = 10;
5492  ctx.globalCompositeOperation = "source-over";
5493  ctx.font = "10px sans-serif";
5494  if (ctx.setLineDash !== undefined) {
5495    ctx.setLineDash([]);
5496    ctx.lineDashOffset = 0;
5497  }
5498}
5499function composeSMaskBackdrop(bytes, r0, g0, b0) {
5500  const length = bytes.length;
5501  for (let i = 3; i < length; i += 4) {
5502    const alpha = bytes[i];
5503    if (alpha === 0) {
5504      bytes[i - 3] = r0;
5505      bytes[i - 2] = g0;
5506      bytes[i - 1] = b0;
5507    } else if (alpha < 255) {
5508      const alpha_ = 255 - alpha;
5509      bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
5510      bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
5511      bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
5512    }
5513  }
5514}
5515function composeSMaskAlpha(maskData, layerData, transferMap) {
5516  const length = maskData.length;
5517  const scale = 1 / 255;
5518  for (let i = 3; i < length; i += 4) {
5519    const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
5520    layerData[i] = layerData[i] * alpha * scale | 0;
5521  }
5522}
5523function composeSMaskLuminosity(maskData, layerData, transferMap) {
5524  const length = maskData.length;
5525  for (let i = 3; i < length; i += 4) {
5526    const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
5527    layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
5528  }
5529}
5530function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
5531  const hasBackdrop = !!backdrop;
5532  const r0 = hasBackdrop ? backdrop[0] : 0;
5533  const g0 = hasBackdrop ? backdrop[1] : 0;
5534  const b0 = hasBackdrop ? backdrop[2] : 0;
5535  let composeFn;
5536  if (subtype === "Luminosity") {
5537    composeFn = composeSMaskLuminosity;
5538  } else {
5539    composeFn = composeSMaskAlpha;
5540  }
5541  const PIXELS_TO_PROCESS = 1048576;
5542  const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
5543  for (let row = 0; row < height; row += chunkSize) {
5544    const chunkHeight = Math.min(chunkSize, height - row);
5545    const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
5546    const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
5547    if (hasBackdrop) {
5548      composeSMaskBackdrop(maskData.data, r0, g0, b0);
5549    }
5550    composeFn(maskData.data, layerData.data, transferMap);
5551    layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
5552  }
5553}
5554function composeSMask(ctx, smask, layerCtx, layerBox) {
5555  const layerOffsetX = layerBox[0];
5556  const layerOffsetY = layerBox[1];
5557  const layerWidth = layerBox[2] - layerOffsetX;
5558  const layerHeight = layerBox[3] - layerOffsetY;
5559  if (layerWidth === 0 || layerHeight === 0) {
5560    return;
5561  }
5562  genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
5563  ctx.save();
5564  ctx.globalAlpha = 1;
5565  ctx.globalCompositeOperation = "source-over";
5566  ctx.setTransform(1, 0, 0, 1, 0, 0);
5567  ctx.drawImage(layerCtx.canvas, 0, 0);
5568  ctx.restore();
5569}
5570function getImageSmoothingEnabled(transform, interpolate) {
5571  const scale = _util.Util.singularValueDecompose2dScale(transform);
5572  scale[0] = Math.fround(scale[0]);
5573  scale[1] = Math.fround(scale[1]);
5574  const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
5575  if (interpolate !== undefined) {
5576    return interpolate;
5577  } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
5578    return true;
5579  }
5580  return false;
5581}
5582const LINE_CAP_STYLES = ["butt", "round", "square"];
5583const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
5584const NORMAL_CLIP = {};
5585const EO_CLIP = {};
5586class CanvasGraphics {
5587  constructor(canvasCtx, commonObjs, objs, canvasFactory, {
5588    optionalContentConfig,
5589    markedContentStack = null
5590  }, annotationCanvasMap, pageColors) {
5591    this.ctx = canvasCtx;
5592    this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
5593    this.stateStack = [];
5594    this.pendingClip = null;
5595    this.pendingEOFill = false;
5596    this.res = null;
5597    this.xobjs = null;
5598    this.commonObjs = commonObjs;
5599    this.objs = objs;
5600    this.canvasFactory = canvasFactory;
5601    this.groupStack = [];
5602    this.processingType3 = null;
5603    this.baseTransform = null;
5604    this.baseTransformStack = [];
5605    this.groupLevel = 0;
5606    this.smaskStack = [];
5607    this.smaskCounter = 0;
5608    this.tempSMask = null;
5609    this.suspendedCtx = null;
5610    this.contentVisible = true;
5611    this.markedContentStack = markedContentStack || [];
5612    this.optionalContentConfig = optionalContentConfig;
5613    this.cachedCanvases = new CachedCanvases(this.canvasFactory);
5614    this.cachedPatterns = new Map();
5615    this.annotationCanvasMap = annotationCanvasMap;
5616    this.viewportScale = 1;
5617    this.outputScaleX = 1;
5618    this.outputScaleY = 1;
5619    this.backgroundColor = pageColors?.background || null;
5620    this.foregroundColor = pageColors?.foreground || null;
5621    this._cachedScaleForStroking = null;
5622    this._cachedGetSinglePixelWidth = null;
5623    this._cachedBitmapsMap = new Map();
5624  }
5625  getObject(data, fallback = null) {
5626    if (typeof data === "string") {
5627      return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
5628    }
5629    return fallback;
5630  }
5631  beginDrawing({
5632    transform,
5633    viewport,
5634    transparency = false,
5635    background = null
5636  }) {
5637    const width = this.ctx.canvas.width;
5638    const height = this.ctx.canvas.height;
5639    const defaultBackgroundColor = background || "#ffffff";
5640    this.ctx.save();
5641    if (this.foregroundColor && this.backgroundColor) {
5642      this.ctx.fillStyle = this.foregroundColor;
5643      const fg = this.foregroundColor = this.ctx.fillStyle;
5644      this.ctx.fillStyle = this.backgroundColor;
5645      const bg = this.backgroundColor = this.ctx.fillStyle;
5646      let isValidDefaultBg = true;
5647      let defaultBg = defaultBackgroundColor;
5648      this.ctx.fillStyle = defaultBackgroundColor;
5649      defaultBg = this.ctx.fillStyle;
5650      isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
5651      if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
5652        this.foregroundColor = this.backgroundColor = null;
5653      } else {
5654        const [rB, gB, bB] = (0, _display_utils.getRGB)(defaultBg);
5655        const newComp = x => {
5656          x /= 255;
5657          return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
5658        };
5659        const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
5660        this.selectColor = (r, g, b) => {
5661          const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
5662          return Math.round(lumC) === lumB ? bg : fg;
5663        };
5664      }
5665    }
5666    this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
5667    this.ctx.fillRect(0, 0, width, height);
5668    this.ctx.restore();
5669    if (transparency) {
5670      const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
5671      this.compositeCtx = this.ctx;
5672      this.transparentCanvas = transparentCanvas.canvas;
5673      this.ctx = transparentCanvas.context;
5674      this.ctx.save();
5675      this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx));
5676    }
5677    this.ctx.save();
5678    resetCtxToDefault(this.ctx, this.foregroundColor);
5679    if (transform) {
5680      this.ctx.transform(...transform);
5681      this.outputScaleX = transform[0];
5682      this.outputScaleY = transform[0];
5683    }
5684    this.ctx.transform(...viewport.transform);
5685    this.viewportScale = viewport.scale;
5686    this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
5687  }
5688  executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
5689    const argsArray = operatorList.argsArray;
5690    const fnArray = operatorList.fnArray;
5691    let i = executionStartIdx || 0;
5692    const argsArrayLen = argsArray.length;
5693    if (argsArrayLen === i) {
5694      return i;
5695    }
5696    const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
5697    const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
5698    let steps = 0;
5699    const commonObjs = this.commonObjs;
5700    const objs = this.objs;
5701    let fnId;
5702    while (true) {
5703      if (stepper !== undefined && i === stepper.nextBreakPoint) {
5704        stepper.breakIt(i, continueCallback);
5705        return i;
5706      }
5707      fnId = fnArray[i];
5708      if (fnId !== _util.OPS.dependency) {
5709        this[fnId].apply(this, argsArray[i]);
5710      } else {
5711        for (const depObjId of argsArray[i]) {
5712          const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
5713          if (!objsPool.has(depObjId)) {
5714            objsPool.get(depObjId, continueCallback);
5715            return i;
5716          }
5717        }
5718      }
5719      i++;
5720      if (i === argsArrayLen) {
5721        return i;
5722      }
5723      if (chunkOperations && ++steps > EXECUTION_STEPS) {
5724        if (Date.now() > endTime) {
5725          continueCallback();
5726          return i;
5727        }
5728        steps = 0;
5729      }
5730    }
5731  }
5732  #restoreInitialState() {
5733    while (this.stateStack.length || this.inSMaskMode) {
5734      this.restore();
5735    }
5736    this.ctx.restore();
5737    if (this.transparentCanvas) {
5738      this.ctx = this.compositeCtx;
5739      this.ctx.save();
5740      this.ctx.setTransform(1, 0, 0, 1, 0, 0);
5741      this.ctx.drawImage(this.transparentCanvas, 0, 0);
5742      this.ctx.restore();
5743      this.transparentCanvas = null;
5744    }
5745  }
5746  endDrawing() {
5747    this.#restoreInitialState();
5748    this.cachedCanvases.clear();
5749    this.cachedPatterns.clear();
5750    for (const cache of this._cachedBitmapsMap.values()) {
5751      for (const canvas of cache.values()) {
5752        if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
5753          canvas.width = canvas.height = 0;
5754        }
5755      }
5756      cache.clear();
5757    }
5758    this._cachedBitmapsMap.clear();
5759  }
5760  _scaleImage(img, inverseTransform) {
5761    const width = img.width;
5762    const height = img.height;
5763    let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
5764    let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
5765    let paintWidth = width,
5766      paintHeight = height;
5767    let tmpCanvasId = "prescale1";
5768    let tmpCanvas, tmpCtx;
5769    while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
5770      let newWidth = paintWidth,
5771        newHeight = paintHeight;
5772      if (widthScale > 2 && paintWidth > 1) {
5773        newWidth = Math.ceil(paintWidth / 2);
5774        widthScale /= paintWidth / newWidth;
5775      }
5776      if (heightScale > 2 && paintHeight > 1) {
5777        newHeight = Math.ceil(paintHeight / 2);
5778        heightScale /= paintHeight / newHeight;
5779      }
5780      tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
5781      tmpCtx = tmpCanvas.context;
5782      tmpCtx.clearRect(0, 0, newWidth, newHeight);
5783      tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
5784      img = tmpCanvas.canvas;
5785      paintWidth = newWidth;
5786      paintHeight = newHeight;
5787      tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
5788    }
5789    return {
5790      img,
5791      paintWidth,
5792      paintHeight
5793    };
5794  }
5795  _createMaskCanvas(img) {
5796    const ctx = this.ctx;
5797    const {
5798      width,
5799      height
5800    } = img;
5801    const fillColor = this.current.fillColor;
5802    const isPatternFill = this.current.patternFill;
5803    const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
5804    let cache, cacheKey, scaled, maskCanvas;
5805    if ((img.bitmap || img.data) && img.count > 1) {
5806      const mainKey = img.bitmap || img.data.buffer;
5807      cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
5808      cache = this._cachedBitmapsMap.get(mainKey);
5809      if (!cache) {
5810        cache = new Map();
5811        this._cachedBitmapsMap.set(mainKey, cache);
5812      }
5813      const cachedImage = cache.get(cacheKey);
5814      if (cachedImage && !isPatternFill) {
5815        const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
5816        const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
5817        return {
5818          canvas: cachedImage,
5819          offsetX,
5820          offsetY
5821        };
5822      }
5823      scaled = cachedImage;
5824    }
5825    if (!scaled) {
5826      maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
5827      putBinaryImageMask(maskCanvas.context, img);
5828    }
5829    let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
5830    maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
5831    const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
5832    const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
5833    const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
5834    const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
5835    const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
5836    const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
5837    const fillCtx = fillCanvas.context;
5838    const offsetX = Math.min(cord1[0], cord2[0]);
5839    const offsetY = Math.min(cord1[1], cord2[1]);
5840    fillCtx.translate(-offsetX, -offsetY);
5841    fillCtx.transform(...maskToCanvas);
5842    if (!scaled) {
5843      scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx));
5844      scaled = scaled.img;
5845      if (cache && isPatternFill) {
5846        cache.set(cacheKey, scaled);
5847      }
5848    }
5849    fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate);
5850    drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
5851    fillCtx.globalCompositeOperation = "source-in";
5852    const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
5853    fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
5854    fillCtx.fillRect(0, 0, width, height);
5855    if (cache && !isPatternFill) {
5856      this.cachedCanvases.delete("fillCanvas");
5857      cache.set(cacheKey, fillCanvas.canvas);
5858    }
5859    return {
5860      canvas: fillCanvas.canvas,
5861      offsetX: Math.round(offsetX),
5862      offsetY: Math.round(offsetY)
5863    };
5864  }
5865  setLineWidth(width) {
5866    if (width !== this.current.lineWidth) {
5867      this._cachedScaleForStroking = null;
5868    }
5869    this.current.lineWidth = width;
5870    this.ctx.lineWidth = width;
5871  }
5872  setLineCap(style) {
5873    this.ctx.lineCap = LINE_CAP_STYLES[style];
5874  }
5875  setLineJoin(style) {
5876    this.ctx.lineJoin = LINE_JOIN_STYLES[style];
5877  }
5878  setMiterLimit(limit) {
5879    this.ctx.miterLimit = limit;
5880  }
5881  setDash(dashArray, dashPhase) {
5882    const ctx = this.ctx;
5883    if (ctx.setLineDash !== undefined) {
5884      ctx.setLineDash(dashArray);
5885      ctx.lineDashOffset = dashPhase;
5886    }
5887  }
5888  setRenderingIntent(intent) {}
5889  setFlatness(flatness) {}
5890  setGState(states) {
5891    for (const [key, value] of states) {
5892      switch (key) {
5893        case "LW":
5894          this.setLineWidth(value);
5895          break;
5896        case "LC":
5897          this.setLineCap(value);
5898          break;
5899        case "LJ":
5900          this.setLineJoin(value);
5901          break;
5902        case "ML":
5903          this.setMiterLimit(value);
5904          break;
5905        case "D":
5906          this.setDash(value[0], value[1]);
5907          break;
5908        case "RI":
5909          this.setRenderingIntent(value);
5910          break;
5911        case "FL":
5912          this.setFlatness(value);
5913          break;
5914        case "Font":
5915          this.setFont(value[0], value[1]);
5916          break;
5917        case "CA":
5918          this.current.strokeAlpha = value;
5919          break;
5920        case "ca":
5921          this.current.fillAlpha = value;
5922          this.ctx.globalAlpha = value;
5923          break;
5924        case "BM":
5925          this.ctx.globalCompositeOperation = value;
5926          break;
5927        case "SMask":
5928          this.current.activeSMask = value ? this.tempSMask : null;
5929          this.tempSMask = null;
5930          this.checkSMaskState();
5931          break;
5932        case "TR":
5933          this.current.transferMaps = value;
5934      }
5935    }
5936  }
5937  get inSMaskMode() {
5938    return !!this.suspendedCtx;
5939  }
5940  checkSMaskState() {
5941    const inSMaskMode = this.inSMaskMode;
5942    if (this.current.activeSMask && !inSMaskMode) {
5943      this.beginSMaskMode();
5944    } else if (!this.current.activeSMask && inSMaskMode) {
5945      this.endSMaskMode();
5946    }
5947  }
5948  beginSMaskMode() {
5949    if (this.inSMaskMode) {
5950      throw new Error("beginSMaskMode called while already in smask mode");
5951    }
5952    const drawnWidth = this.ctx.canvas.width;
5953    const drawnHeight = this.ctx.canvas.height;
5954    const cacheId = "smaskGroupAt" + this.groupLevel;
5955    const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
5956    this.suspendedCtx = this.ctx;
5957    this.ctx = scratchCanvas.context;
5958    const ctx = this.ctx;
5959    ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx));
5960    copyCtxState(this.suspendedCtx, ctx);
5961    mirrorContextOperations(ctx, this.suspendedCtx);
5962    this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
5963  }
5964  endSMaskMode() {
5965    if (!this.inSMaskMode) {
5966      throw new Error("endSMaskMode called while not in smask mode");
5967    }
5968    this.ctx._removeMirroring();
5969    copyCtxState(this.ctx, this.suspendedCtx);
5970    this.ctx = this.suspendedCtx;
5971    this.suspendedCtx = null;
5972  }
5973  compose(dirtyBox) {
5974    if (!this.current.activeSMask) {
5975      return;
5976    }
5977    if (!dirtyBox) {
5978      dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
5979    } else {
5980      dirtyBox[0] = Math.floor(dirtyBox[0]);
5981      dirtyBox[1] = Math.floor(dirtyBox[1]);
5982      dirtyBox[2] = Math.ceil(dirtyBox[2]);
5983      dirtyBox[3] = Math.ceil(dirtyBox[3]);
5984    }
5985    const smask = this.current.activeSMask;
5986    const suspendedCtx = this.suspendedCtx;
5987    composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
5988    this.ctx.save();
5989    this.ctx.setTransform(1, 0, 0, 1, 0, 0);
5990    this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
5991    this.ctx.restore();
5992  }
5993  save() {
5994    if (this.inSMaskMode) {
5995      copyCtxState(this.ctx, this.suspendedCtx);
5996      this.suspendedCtx.save();
5997    } else {
5998      this.ctx.save();
5999    }
6000    const old = this.current;
6001    this.stateStack.push(old);
6002    this.current = old.clone();
6003  }
6004  restore() {
6005    if (this.stateStack.length === 0 && this.inSMaskMode) {
6006      this.endSMaskMode();
6007    }
6008    if (this.stateStack.length !== 0) {
6009      this.current = this.stateStack.pop();
6010      if (this.inSMaskMode) {
6011        this.suspendedCtx.restore();
6012        copyCtxState(this.suspendedCtx, this.ctx);
6013      } else {
6014        this.ctx.restore();
6015      }
6016      this.checkSMaskState();
6017      this.pendingClip = null;
6018      this._cachedScaleForStroking = null;
6019      this._cachedGetSinglePixelWidth = null;
6020    }
6021  }
6022  transform(a, b, c, d, e, f) {
6023    this.ctx.transform(a, b, c, d, e, f);
6024    this._cachedScaleForStroking = null;
6025    this._cachedGetSinglePixelWidth = null;
6026  }
6027  constructPath(ops, args, minMax) {
6028    const ctx = this.ctx;
6029    const current = this.current;
6030    let x = current.x,
6031      y = current.y;
6032    let startX, startY;
6033    const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
6034    const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
6035    const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
6036    for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
6037      switch (ops[i] | 0) {
6038        case _util.OPS.rectangle:
6039          x = args[j++];
6040          y = args[j++];
6041          const width = args[j++];
6042          const height = args[j++];
6043          const xw = x + width;
6044          const yh = y + height;
6045          ctx.moveTo(x, y);
6046          if (width === 0 || height === 0) {
6047            ctx.lineTo(xw, yh);
6048          } else {
6049            ctx.lineTo(xw, y);
6050            ctx.lineTo(xw, yh);
6051            ctx.lineTo(x, yh);
6052          }
6053          if (!isScalingMatrix) {
6054            current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
6055          }
6056          ctx.closePath();
6057          break;
6058        case _util.OPS.moveTo:
6059          x = args[j++];
6060          y = args[j++];
6061          ctx.moveTo(x, y);
6062          if (!isScalingMatrix) {
6063            current.updatePathMinMax(currentTransform, x, y);
6064          }
6065          break;
6066        case _util.OPS.lineTo:
6067          x = args[j++];
6068          y = args[j++];
6069          ctx.lineTo(x, y);
6070          if (!isScalingMatrix) {
6071            current.updatePathMinMax(currentTransform, x, y);
6072          }
6073          break;
6074        case _util.OPS.curveTo:
6075          startX = x;
6076          startY = y;
6077          x = args[j + 4];
6078          y = args[j + 5];
6079          ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
6080          current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
6081          j += 6;
6082          break;
6083        case _util.OPS.curveTo2:
6084          startX = x;
6085          startY = y;
6086          ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
6087          current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
6088          x = args[j + 2];
6089          y = args[j + 3];
6090          j += 4;
6091          break;
6092        case _util.OPS.curveTo3:
6093          startX = x;
6094          startY = y;
6095          x = args[j + 2];
6096          y = args[j + 3];
6097          ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
6098          current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
6099          j += 4;
6100          break;
6101        case _util.OPS.closePath:
6102          ctx.closePath();
6103          break;
6104      }
6105    }
6106    if (isScalingMatrix) {
6107      current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
6108    }
6109    current.setCurrentPoint(x, y);
6110  }
6111  closePath() {
6112    this.ctx.closePath();
6113  }
6114  stroke(consumePath = true) {
6115    const ctx = this.ctx;
6116    const strokeColor = this.current.strokeColor;
6117    ctx.globalAlpha = this.current.strokeAlpha;
6118    if (this.contentVisible) {
6119      if (typeof strokeColor === "object" && strokeColor?.getPattern) {
6120        ctx.save();
6121        ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE);
6122        this.rescaleAndStroke(false);
6123        ctx.restore();
6124      } else {
6125        this.rescaleAndStroke(true);
6126      }
6127    }
6128    if (consumePath) {
6129      this.consumePath(this.current.getClippedPathBoundingBox());
6130    }
6131    ctx.globalAlpha = this.current.fillAlpha;
6132  }
6133  closeStroke() {
6134    this.closePath();
6135    this.stroke();
6136  }
6137  fill(consumePath = true) {
6138    const ctx = this.ctx;
6139    const fillColor = this.current.fillColor;
6140    const isPatternFill = this.current.patternFill;
6141    let needRestore = false;
6142    if (isPatternFill) {
6143      ctx.save();
6144      ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
6145      needRestore = true;
6146    }
6147    const intersect = this.current.getClippedPathBoundingBox();
6148    if (this.contentVisible && intersect !== null) {
6149      if (this.pendingEOFill) {
6150        ctx.fill("evenodd");
6151        this.pendingEOFill = false;
6152      } else {
6153        ctx.fill();
6154      }
6155    }
6156    if (needRestore) {
6157      ctx.restore();
6158    }
6159    if (consumePath) {
6160      this.consumePath(intersect);
6161    }
6162  }
6163  eoFill() {
6164    this.pendingEOFill = true;
6165    this.fill();
6166  }
6167  fillStroke() {
6168    this.fill(false);
6169    this.stroke(false);
6170    this.consumePath();
6171  }
6172  eoFillStroke() {
6173    this.pendingEOFill = true;
6174    this.fillStroke();
6175  }
6176  closeFillStroke() {
6177    this.closePath();
6178    this.fillStroke();
6179  }
6180  closeEOFillStroke() {
6181    this.pendingEOFill = true;
6182    this.closePath();
6183    this.fillStroke();
6184  }
6185  endPath() {
6186    this.consumePath();
6187  }
6188  clip() {
6189    this.pendingClip = NORMAL_CLIP;
6190  }
6191  eoClip() {
6192    this.pendingClip = EO_CLIP;
6193  }
6194  beginText() {
6195    this.current.textMatrix = _util.IDENTITY_MATRIX;
6196    this.current.textMatrixScale = 1;
6197    this.current.x = this.current.lineX = 0;
6198    this.current.y = this.current.lineY = 0;
6199  }
6200  endText() {
6201    const paths = this.pendingTextPaths;
6202    const ctx = this.ctx;
6203    if (paths === undefined) {
6204      ctx.beginPath();
6205      return;
6206    }
6207    ctx.save();
6208    ctx.beginPath();
6209    for (const path of paths) {
6210      ctx.setTransform(...path.transform);
6211      ctx.translate(path.x, path.y);
6212      path.addToPath(ctx, path.fontSize);
6213    }
6214    ctx.restore();
6215    ctx.clip();
6216    ctx.beginPath();
6217    delete this.pendingTextPaths;
6218  }
6219  setCharSpacing(spacing) {
6220    this.current.charSpacing = spacing;
6221  }
6222  setWordSpacing(spacing) {
6223    this.current.wordSpacing = spacing;
6224  }
6225  setHScale(scale) {
6226    this.current.textHScale = scale / 100;
6227  }
6228  setLeading(leading) {
6229    this.current.leading = -leading;
6230  }
6231  setFont(fontRefName, size) {
6232    const fontObj = this.commonObjs.get(fontRefName);
6233    const current = this.current;
6234    if (!fontObj) {
6235      throw new Error(`Can't find font for ${fontRefName}`);
6236    }
6237    current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
6238    if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
6239      (0, _util.warn)("Invalid font matrix for font " + fontRefName);
6240    }
6241    if (size < 0) {
6242      size = -size;
6243      current.fontDirection = -1;
6244    } else {
6245      current.fontDirection = 1;
6246    }
6247    this.current.font = fontObj;
6248    this.current.fontSize = size;
6249    if (fontObj.isType3Font) {
6250      return;
6251    }
6252    const name = fontObj.loadedName || "sans-serif";
6253    let bold = "normal";
6254    if (fontObj.black) {
6255      bold = "900";
6256    } else if (fontObj.bold) {
6257      bold = "bold";
6258    }
6259    const italic = fontObj.italic ? "italic" : "normal";
6260    const typeface = `"${name}", ${fontObj.fallbackName}`;
6261    let browserFontSize = size;
6262    if (size < MIN_FONT_SIZE) {
6263      browserFontSize = MIN_FONT_SIZE;
6264    } else if (size > MAX_FONT_SIZE) {
6265      browserFontSize = MAX_FONT_SIZE;
6266    }
6267    this.current.fontSizeScale = size / browserFontSize;
6268    this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
6269  }
6270  setTextRenderingMode(mode) {
6271    this.current.textRenderingMode = mode;
6272  }
6273  setTextRise(rise) {
6274    this.current.textRise = rise;
6275  }
6276  moveText(x, y) {
6277    this.current.x = this.current.lineX += x;
6278    this.current.y = this.current.lineY += y;
6279  }
6280  setLeadingMoveText(x, y) {
6281    this.setLeading(-y);
6282    this.moveText(x, y);
6283  }
6284  setTextMatrix(a, b, c, d, e, f) {
6285    this.current.textMatrix = [a, b, c, d, e, f];
6286    this.current.textMatrixScale = Math.hypot(a, b);
6287    this.current.x = this.current.lineX = 0;
6288    this.current.y = this.current.lineY = 0;
6289  }
6290  nextLine() {
6291    this.moveText(0, this.current.leading);
6292  }
6293  paintChar(character, x, y, patternTransform) {
6294    const ctx = this.ctx;
6295    const current = this.current;
6296    const font = current.font;
6297    const textRenderingMode = current.textRenderingMode;
6298    const fontSize = current.fontSize / current.fontSizeScale;
6299    const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
6300    const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
6301    const patternFill = current.patternFill && !font.missingFile;
6302    let addToPath;
6303    if (font.disableFontFace || isAddToPathSet || patternFill) {
6304      addToPath = font.getPathGenerator(this.commonObjs, character);
6305    }
6306    if (font.disableFontFace || patternFill) {
6307      ctx.save();
6308      ctx.translate(x, y);
6309      ctx.beginPath();
6310      addToPath(ctx, fontSize);
6311      if (patternTransform) {
6312        ctx.setTransform(...patternTransform);
6313      }
6314      if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6315        ctx.fill();
6316      }
6317      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6318        ctx.stroke();
6319      }
6320      ctx.restore();
6321    } else {
6322      if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6323        ctx.fillText(character, x, y);
6324      }
6325      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6326        ctx.strokeText(character, x, y);
6327      }
6328    }
6329    if (isAddToPathSet) {
6330      const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
6331      paths.push({
6332        transform: (0, _display_utils.getCurrentTransform)(ctx),
6333        x,
6334        y,
6335        fontSize,
6336        addToPath
6337      });
6338    }
6339  }
6340  get isFontSubpixelAAEnabled() {
6341    const {
6342      context: ctx
6343    } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
6344    ctx.scale(1.5, 1);
6345    ctx.fillText("I", 0, 10);
6346    const data = ctx.getImageData(0, 0, 10, 10).data;
6347    let enabled = false;
6348    for (let i = 3; i < data.length; i += 4) {
6349      if (data[i] > 0 && data[i] < 255) {
6350        enabled = true;
6351        break;
6352      }
6353    }
6354    return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
6355  }
6356  showText(glyphs) {
6357    const current = this.current;
6358    const font = current.font;
6359    if (font.isType3Font) {
6360      return this.showType3Text(glyphs);
6361    }
6362    const fontSize = current.fontSize;
6363    if (fontSize === 0) {
6364      return undefined;
6365    }
6366    const ctx = this.ctx;
6367    const fontSizeScale = current.fontSizeScale;
6368    const charSpacing = current.charSpacing;
6369    const wordSpacing = current.wordSpacing;
6370    const fontDirection = current.fontDirection;
6371    const textHScale = current.textHScale * fontDirection;
6372    const glyphsLength = glyphs.length;
6373    const vertical = font.vertical;
6374    const spacingDir = vertical ? 1 : -1;
6375    const defaultVMetrics = font.defaultVMetrics;
6376    const widthAdvanceScale = fontSize * current.fontMatrix[0];
6377    const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
6378    ctx.save();
6379    ctx.transform(...current.textMatrix);
6380    ctx.translate(current.x, current.y + current.textRise);
6381    if (fontDirection > 0) {
6382      ctx.scale(textHScale, -1);
6383    } else {
6384      ctx.scale(textHScale, 1);
6385    }
6386    let patternTransform;
6387    if (current.patternFill) {
6388      ctx.save();
6389      const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
6390      patternTransform = (0, _display_utils.getCurrentTransform)(ctx);
6391      ctx.restore();
6392      ctx.fillStyle = pattern;
6393    }
6394    let lineWidth = current.lineWidth;
6395    const scale = current.textMatrixScale;
6396    if (scale === 0 || lineWidth === 0) {
6397      const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
6398      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6399        lineWidth = this.getSinglePixelWidth();
6400      }
6401    } else {
6402      lineWidth /= scale;
6403    }
6404    if (fontSizeScale !== 1.0) {
6405      ctx.scale(fontSizeScale, fontSizeScale);
6406      lineWidth /= fontSizeScale;
6407    }
6408    ctx.lineWidth = lineWidth;
6409    if (font.isInvalidPDFjsFont) {
6410      const chars = [];
6411      let width = 0;
6412      for (const glyph of glyphs) {
6413        chars.push(glyph.unicode);
6414        width += glyph.width;
6415      }
6416      ctx.fillText(chars.join(""), 0, 0);
6417      current.x += width * widthAdvanceScale * textHScale;
6418      ctx.restore();
6419      this.compose();
6420      return undefined;
6421    }
6422    let x = 0,
6423      i;
6424    for (i = 0; i < glyphsLength; ++i) {
6425      const glyph = glyphs[i];
6426      if (typeof glyph === "number") {
6427        x += spacingDir * glyph * fontSize / 1000;
6428        continue;
6429      }
6430      let restoreNeeded = false;
6431      const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
6432      const character = glyph.fontChar;
6433      const accent = glyph.accent;
6434      let scaledX, scaledY;
6435      let width = glyph.width;
6436      if (vertical) {
6437        const vmetric = glyph.vmetric || defaultVMetrics;
6438        const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
6439        const vy = vmetric[2] * widthAdvanceScale;
6440        width = vmetric ? -vmetric[0] : width;
6441        scaledX = vx / fontSizeScale;
6442        scaledY = (x + vy) / fontSizeScale;
6443      } else {
6444        scaledX = x / fontSizeScale;
6445        scaledY = 0;
6446      }
6447      if (font.remeasure && width > 0) {
6448        const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
6449        if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
6450          const characterScaleX = width / measuredWidth;
6451          restoreNeeded = true;
6452          ctx.save();
6453          ctx.scale(characterScaleX, 1);
6454          scaledX /= characterScaleX;
6455        } else if (width !== measuredWidth) {
6456          scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
6457        }
6458      }
6459      if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
6460        if (simpleFillText && !accent) {
6461          ctx.fillText(character, scaledX, scaledY);
6462        } else {
6463          this.paintChar(character, scaledX, scaledY, patternTransform);
6464          if (accent) {
6465            const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
6466            const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
6467            this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
6468          }
6469        }
6470      }
6471      let charWidth;
6472      if (vertical) {
6473        charWidth = width * widthAdvanceScale - spacing * fontDirection;
6474      } else {
6475        charWidth = width * widthAdvanceScale + spacing * fontDirection;
6476      }
6477      x += charWidth;
6478      if (restoreNeeded) {
6479        ctx.restore();
6480      }
6481    }
6482    if (vertical) {
6483      current.y -= x;
6484    } else {
6485      current.x += x * textHScale;
6486    }
6487    ctx.restore();
6488    this.compose();
6489    return undefined;
6490  }
6491  showType3Text(glyphs) {
6492    const ctx = this.ctx;
6493    const current = this.current;
6494    const font = current.font;
6495    const fontSize = current.fontSize;
6496    const fontDirection = current.fontDirection;
6497    const spacingDir = font.vertical ? 1 : -1;
6498    const charSpacing = current.charSpacing;
6499    const wordSpacing = current.wordSpacing;
6500    const textHScale = current.textHScale * fontDirection;
6501    const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
6502    const glyphsLength = glyphs.length;
6503    const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
6504    let i, glyph, width, spacingLength;
6505    if (isTextInvisible || fontSize === 0) {
6506      return;
6507    }
6508    this._cachedScaleForStroking = null;
6509    this._cachedGetSinglePixelWidth = null;
6510    ctx.save();
6511    ctx.transform(...current.textMatrix);
6512    ctx.translate(current.x, current.y);
6513    ctx.scale(textHScale, fontDirection);
6514    for (i = 0; i < glyphsLength; ++i) {
6515      glyph = glyphs[i];
6516      if (typeof glyph === "number") {
6517        spacingLength = spacingDir * glyph * fontSize / 1000;
6518        this.ctx.translate(spacingLength, 0);
6519        current.x += spacingLength * textHScale;
6520        continue;
6521      }
6522      const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
6523      const operatorList = font.charProcOperatorList[glyph.operatorListId];
6524      if (!operatorList) {
6525        (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
6526        continue;
6527      }
6528      if (this.contentVisible) {
6529        this.processingType3 = glyph;
6530        this.save();
6531        ctx.scale(fontSize, fontSize);
6532        ctx.transform(...fontMatrix);
6533        this.executeOperatorList(operatorList);
6534        this.restore();
6535      }
6536      const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
6537      width = transformed[0] * fontSize + spacing;
6538      ctx.translate(width, 0);
6539      current.x += width * textHScale;
6540    }
6541    ctx.restore();
6542    this.processingType3 = null;
6543  }
6544  setCharWidth(xWidth, yWidth) {}
6545  setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
6546    this.ctx.rect(llx, lly, urx - llx, ury - lly);
6547    this.ctx.clip();
6548    this.endPath();
6549  }
6550  getColorN_Pattern(IR) {
6551    let pattern;
6552    if (IR[0] === "TilingPattern") {
6553      const color = IR[1];
6554      const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx);
6555      const canvasGraphicsFactory = {
6556        createCanvasGraphics: ctx => {
6557          return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, {
6558            optionalContentConfig: this.optionalContentConfig,
6559            markedContentStack: this.markedContentStack
6560          });
6561        }
6562      };
6563      pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
6564    } else {
6565      pattern = this._getPattern(IR[1], IR[2]);
6566    }
6567    return pattern;
6568  }
6569  setStrokeColorN() {
6570    this.current.strokeColor = this.getColorN_Pattern(arguments);
6571  }
6572  setFillColorN() {
6573    this.current.fillColor = this.getColorN_Pattern(arguments);
6574    this.current.patternFill = true;
6575  }
6576  setStrokeRGBColor(r, g, b) {
6577    const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
6578    this.ctx.strokeStyle = color;
6579    this.current.strokeColor = color;
6580  }
6581  setFillRGBColor(r, g, b) {
6582    const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
6583    this.ctx.fillStyle = color;
6584    this.current.fillColor = color;
6585    this.current.patternFill = false;
6586  }
6587  _getPattern(objId, matrix = null) {
6588    let pattern;
6589    if (this.cachedPatterns.has(objId)) {
6590      pattern = this.cachedPatterns.get(objId);
6591    } else {
6592      pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
6593      this.cachedPatterns.set(objId, pattern);
6594    }
6595    if (matrix) {
6596      pattern.matrix = matrix;
6597    }
6598    return pattern;
6599  }
6600  shadingFill(objId) {
6601    if (!this.contentVisible) {
6602      return;
6603    }
6604    const ctx = this.ctx;
6605    this.save();
6606    const pattern = this._getPattern(objId);
6607    ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING);
6608    const inv = (0, _display_utils.getCurrentTransformInverse)(ctx);
6609    if (inv) {
6610      const canvas = ctx.canvas;
6611      const width = canvas.width;
6612      const height = canvas.height;
6613      const bl = _util.Util.applyTransform([0, 0], inv);
6614      const br = _util.Util.applyTransform([0, height], inv);
6615      const ul = _util.Util.applyTransform([width, 0], inv);
6616      const ur = _util.Util.applyTransform([width, height], inv);
6617      const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
6618      const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
6619      const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
6620      const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
6621      this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
6622    } else {
6623      this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
6624    }
6625    this.compose(this.current.getClippedPathBoundingBox());
6626    this.restore();
6627  }
6628  beginInlineImage() {
6629    (0, _util.unreachable)("Should not call beginInlineImage");
6630  }
6631  beginImageData() {
6632    (0, _util.unreachable)("Should not call beginImageData");
6633  }
6634  paintFormXObjectBegin(matrix, bbox) {
6635    if (!this.contentVisible) {
6636      return;
6637    }
6638    this.save();
6639    this.baseTransformStack.push(this.baseTransform);
6640    if (Array.isArray(matrix) && matrix.length === 6) {
6641      this.transform(...matrix);
6642    }
6643    this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
6644    if (bbox) {
6645      const width = bbox[2] - bbox[0];
6646      const height = bbox[3] - bbox[1];
6647      this.ctx.rect(bbox[0], bbox[1], width, height);
6648      this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox);
6649      this.clip();
6650      this.endPath();
6651    }
6652  }
6653  paintFormXObjectEnd() {
6654    if (!this.contentVisible) {
6655      return;
6656    }
6657    this.restore();
6658    this.baseTransform = this.baseTransformStack.pop();
6659  }
6660  beginGroup(group) {
6661    if (!this.contentVisible) {
6662      return;
6663    }
6664    this.save();
6665    if (this.inSMaskMode) {
6666      this.endSMaskMode();
6667      this.current.activeSMask = null;
6668    }
6669    const currentCtx = this.ctx;
6670    if (!group.isolated) {
6671      (0, _util.info)("TODO: Support non-isolated groups.");
6672    }
6673    if (group.knockout) {
6674      (0, _util.warn)("Knockout groups not supported.");
6675    }
6676    const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx);
6677    if (group.matrix) {
6678      currentCtx.transform(...group.matrix);
6679    }
6680    if (!group.bbox) {
6681      throw new Error("Bounding box is required.");
6682    }
6683    let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx));
6684    const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
6685    bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
6686    const offsetX = Math.floor(bounds[0]);
6687    const offsetY = Math.floor(bounds[1]);
6688    let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
6689    let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
6690    let scaleX = 1,
6691      scaleY = 1;
6692    if (drawnWidth > MAX_GROUP_SIZE) {
6693      scaleX = drawnWidth / MAX_GROUP_SIZE;
6694      drawnWidth = MAX_GROUP_SIZE;
6695    }
6696    if (drawnHeight > MAX_GROUP_SIZE) {
6697      scaleY = drawnHeight / MAX_GROUP_SIZE;
6698      drawnHeight = MAX_GROUP_SIZE;
6699    }
6700    this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
6701    let cacheId = "groupAt" + this.groupLevel;
6702    if (group.smask) {
6703      cacheId += "_smask_" + this.smaskCounter++ % 2;
6704    }
6705    const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
6706    const groupCtx = scratchCanvas.context;
6707    groupCtx.scale(1 / scaleX, 1 / scaleY);
6708    groupCtx.translate(-offsetX, -offsetY);
6709    groupCtx.transform(...currentTransform);
6710    if (group.smask) {
6711      this.smaskStack.push({
6712        canvas: scratchCanvas.canvas,
6713        context: groupCtx,
6714        offsetX,
6715        offsetY,
6716        scaleX,
6717        scaleY,
6718        subtype: group.smask.subtype,
6719        backdrop: group.smask.backdrop,
6720        transferMap: group.smask.transferMap || null,
6721        startTransformInverse: null
6722      });
6723    } else {
6724      currentCtx.setTransform(1, 0, 0, 1, 0, 0);
6725      currentCtx.translate(offsetX, offsetY);
6726      currentCtx.scale(scaleX, scaleY);
6727      currentCtx.save();
6728    }
6729    copyCtxState(currentCtx, groupCtx);
6730    this.ctx = groupCtx;
6731    this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
6732    this.groupStack.push(currentCtx);
6733    this.groupLevel++;
6734  }
6735  endGroup(group) {
6736    if (!this.contentVisible) {
6737      return;
6738    }
6739    this.groupLevel--;
6740    const groupCtx = this.ctx;
6741    const ctx = this.groupStack.pop();
6742    this.ctx = ctx;
6743    this.ctx.imageSmoothingEnabled = false;
6744    if (group.smask) {
6745      this.tempSMask = this.smaskStack.pop();
6746      this.restore();
6747    } else {
6748      this.ctx.restore();
6749      const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx);
6750      this.restore();
6751      this.ctx.save();
6752      this.ctx.setTransform(...currentMtx);
6753      const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
6754      this.ctx.drawImage(groupCtx.canvas, 0, 0);
6755      this.ctx.restore();
6756      this.compose(dirtyBox);
6757    }
6758  }
6759  beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
6760    this.#restoreInitialState();
6761    resetCtxToDefault(this.ctx, this.foregroundColor);
6762    this.ctx.save();
6763    this.save();
6764    if (this.baseTransform) {
6765      this.ctx.setTransform(...this.baseTransform);
6766    }
6767    if (Array.isArray(rect) && rect.length === 4) {
6768      const width = rect[2] - rect[0];
6769      const height = rect[3] - rect[1];
6770      if (hasOwnCanvas && this.annotationCanvasMap) {
6771        transform = transform.slice();
6772        transform[4] -= rect[0];
6773        transform[5] -= rect[1];
6774        rect = rect.slice();
6775        rect[0] = rect[1] = 0;
6776        rect[2] = width;
6777        rect[3] = height;
6778        const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx));
6779        const {
6780          viewportScale
6781        } = this;
6782        const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
6783        const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
6784        this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
6785        const {
6786          canvas,
6787          context
6788        } = this.annotationCanvas;
6789        this.annotationCanvasMap.set(id, canvas);
6790        this.annotationCanvas.savedCtx = this.ctx;
6791        this.ctx = context;
6792        this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
6793        resetCtxToDefault(this.ctx, this.foregroundColor);
6794      } else {
6795        resetCtxToDefault(this.ctx, this.foregroundColor);
6796        this.ctx.rect(rect[0], rect[1], width, height);
6797        this.ctx.clip();
6798        this.endPath();
6799      }
6800    }
6801    this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
6802    this.transform(...transform);
6803    this.transform(...matrix);
6804  }
6805  endAnnotation() {
6806    if (this.annotationCanvas) {
6807      this.ctx = this.annotationCanvas.savedCtx;
6808      delete this.annotationCanvas.savedCtx;
6809      delete this.annotationCanvas;
6810    }
6811  }
6812  paintImageMaskXObject(img) {
6813    if (!this.contentVisible) {
6814      return;
6815    }
6816    const count = img.count;
6817    img = this.getObject(img.data, img);
6818    img.count = count;
6819    const ctx = this.ctx;
6820    const glyph = this.processingType3;
6821    if (glyph) {
6822      if (glyph.compiled === undefined) {
6823        glyph.compiled = compileType3Glyph(img);
6824      }
6825      if (glyph.compiled) {
6826        glyph.compiled(ctx);
6827        return;
6828      }
6829    }
6830    const mask = this._createMaskCanvas(img);
6831    const maskCanvas = mask.canvas;
6832    ctx.save();
6833    ctx.setTransform(1, 0, 0, 1, 0, 0);
6834    ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
6835    ctx.restore();
6836    this.compose();
6837  }
6838  paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
6839    if (!this.contentVisible) {
6840      return;
6841    }
6842    img = this.getObject(img.data, img);
6843    const ctx = this.ctx;
6844    ctx.save();
6845    const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
6846    ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
6847    const mask = this._createMaskCanvas(img);
6848    ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
6849    for (let i = 0, ii = positions.length; i < ii; i += 2) {
6850      const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
6851      const [x, y] = _util.Util.applyTransform([0, 0], trans);
6852      ctx.drawImage(mask.canvas, x, y);
6853    }
6854    ctx.restore();
6855    this.compose();
6856  }
6857  paintImageMaskXObjectGroup(images) {
6858    if (!this.contentVisible) {
6859      return;
6860    }
6861    const ctx = this.ctx;
6862    const fillColor = this.current.fillColor;
6863    const isPatternFill = this.current.patternFill;
6864    for (const image of images) {
6865      const {
6866        data,
6867        width,
6868        height,
6869        transform
6870      } = image;
6871      const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
6872      const maskCtx = maskCanvas.context;
6873      maskCtx.save();
6874      const img = this.getObject(data, image);
6875      putBinaryImageMask(maskCtx, img);
6876      maskCtx.globalCompositeOperation = "source-in";
6877      maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor;
6878      maskCtx.fillRect(0, 0, width, height);
6879      maskCtx.restore();
6880      ctx.save();
6881      ctx.transform(...transform);
6882      ctx.scale(1, -1);
6883      drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
6884      ctx.restore();
6885    }
6886    this.compose();
6887  }
6888  paintImageXObject(objId) {
6889    if (!this.contentVisible) {
6890      return;
6891    }
6892    const imgData = this.getObject(objId);
6893    if (!imgData) {
6894      (0, _util.warn)("Dependent image isn't ready yet");
6895      return;
6896    }
6897    this.paintInlineImageXObject(imgData);
6898  }
6899  paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
6900    if (!this.contentVisible) {
6901      return;
6902    }
6903    const imgData = this.getObject(objId);
6904    if (!imgData) {
6905      (0, _util.warn)("Dependent image isn't ready yet");
6906      return;
6907    }
6908    const width = imgData.width;
6909    const height = imgData.height;
6910    const map = [];
6911    for (let i = 0, ii = positions.length; i < ii; i += 2) {
6912      map.push({
6913        transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
6914        x: 0,
6915        y: 0,
6916        w: width,
6917        h: height
6918      });
6919    }
6920    this.paintInlineImageXObjectGroup(imgData, map);
6921  }
6922  paintInlineImageXObject(imgData) {
6923    if (!this.contentVisible) {
6924      return;
6925    }
6926    const width = imgData.width;
6927    const height = imgData.height;
6928    const ctx = this.ctx;
6929    this.save();
6930    ctx.scale(1 / width, -1 / height);
6931    let imgToPaint;
6932    if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
6933      imgToPaint = imgData;
6934    } else {
6935      const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
6936      const tmpCtx = tmpCanvas.context;
6937      putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
6938      imgToPaint = tmpCanvas.canvas;
6939    }
6940    const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx));
6941    ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate);
6942    drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
6943    this.compose();
6944    this.restore();
6945  }
6946  paintInlineImageXObjectGroup(imgData, map) {
6947    if (!this.contentVisible) {
6948      return;
6949    }
6950    const ctx = this.ctx;
6951    const w = imgData.width;
6952    const h = imgData.height;
6953    const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
6954    const tmpCtx = tmpCanvas.context;
6955    putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
6956    for (const entry of map) {
6957      ctx.save();
6958      ctx.transform(...entry.transform);
6959      ctx.scale(1, -1);
6960      drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
6961      ctx.restore();
6962    }
6963    this.compose();
6964  }
6965  paintSolidColorImageMask() {
6966    if (!this.contentVisible) {
6967      return;
6968    }
6969    this.ctx.fillRect(0, 0, 1, 1);
6970    this.compose();
6971  }
6972  markPoint(tag) {}
6973  markPointProps(tag, properties) {}
6974  beginMarkedContent(tag) {
6975    this.markedContentStack.push({
6976      visible: true
6977    });
6978  }
6979  beginMarkedContentProps(tag, properties) {
6980    if (tag === "OC") {
6981      this.markedContentStack.push({
6982        visible: this.optionalContentConfig.isVisible(properties)
6983      });
6984    } else {
6985      this.markedContentStack.push({
6986        visible: true
6987      });
6988    }
6989    this.contentVisible = this.isContentVisible();
6990  }
6991  endMarkedContent() {
6992    this.markedContentStack.pop();
6993    this.contentVisible = this.isContentVisible();
6994  }
6995  beginCompat() {}
6996  endCompat() {}
6997  consumePath(clipBox) {
6998    const isEmpty = this.current.isEmptyClip();
6999    if (this.pendingClip) {
7000      this.current.updateClipFromPath();
7001    }
7002    if (!this.pendingClip) {
7003      this.compose(clipBox);
7004    }
7005    const ctx = this.ctx;
7006    if (this.pendingClip) {
7007      if (!isEmpty) {
7008        if (this.pendingClip === EO_CLIP) {
7009          ctx.clip("evenodd");
7010        } else {
7011          ctx.clip();
7012        }
7013      }
7014      this.pendingClip = null;
7015    }
7016    this.current.startNewPathAndClipBox(this.current.clipBox);
7017    ctx.beginPath();
7018  }
7019  getSinglePixelWidth() {
7020    if (!this._cachedGetSinglePixelWidth) {
7021      const m = (0, _display_utils.getCurrentTransform)(this.ctx);
7022      if (m[1] === 0 && m[2] === 0) {
7023        this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
7024      } else {
7025        const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
7026        const normX = Math.hypot(m[0], m[2]);
7027        const normY = Math.hypot(m[1], m[3]);
7028        this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
7029      }
7030    }
7031    return this._cachedGetSinglePixelWidth;
7032  }
7033  getScaleForStroking() {
7034    if (!this._cachedScaleForStroking) {
7035      const {
7036        lineWidth
7037      } = this.current;
7038      const m = (0, _display_utils.getCurrentTransform)(this.ctx);
7039      let scaleX, scaleY;
7040      if (m[1] === 0 && m[2] === 0) {
7041        const normX = Math.abs(m[0]);
7042        const normY = Math.abs(m[3]);
7043        if (lineWidth === 0) {
7044          scaleX = 1 / normX;
7045          scaleY = 1 / normY;
7046        } else {
7047          const scaledXLineWidth = normX * lineWidth;
7048          const scaledYLineWidth = normY * lineWidth;
7049          scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
7050          scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
7051        }
7052      } else {
7053        const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
7054        const normX = Math.hypot(m[0], m[1]);
7055        const normY = Math.hypot(m[2], m[3]);
7056        if (lineWidth === 0) {
7057          scaleX = normY / absDet;
7058          scaleY = normX / absDet;
7059        } else {
7060          const baseArea = lineWidth * absDet;
7061          scaleX = normY > baseArea ? normY / baseArea : 1;
7062          scaleY = normX > baseArea ? normX / baseArea : 1;
7063        }
7064      }
7065      this._cachedScaleForStroking = [scaleX, scaleY];
7066    }
7067    return this._cachedScaleForStroking;
7068  }
7069  rescaleAndStroke(saveRestore) {
7070    const {
7071      ctx
7072    } = this;
7073    const {
7074      lineWidth
7075    } = this.current;
7076    const [scaleX, scaleY] = this.getScaleForStroking();
7077    ctx.lineWidth = lineWidth || 1;
7078    if (scaleX === 1 && scaleY === 1) {
7079      ctx.stroke();
7080      return;
7081    }
7082    let savedMatrix, savedDashes, savedDashOffset;
7083    if (saveRestore) {
7084      savedMatrix = (0, _display_utils.getCurrentTransform)(ctx);
7085      savedDashes = ctx.getLineDash().slice();
7086      savedDashOffset = ctx.lineDashOffset;
7087    }
7088    ctx.scale(scaleX, scaleY);
7089    const scale = Math.max(scaleX, scaleY);
7090    ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
7091    ctx.lineDashOffset /= scale;
7092    ctx.stroke();
7093    if (saveRestore) {
7094      ctx.setTransform(...savedMatrix);
7095      ctx.setLineDash(savedDashes);
7096      ctx.lineDashOffset = savedDashOffset;
7097    }
7098  }
7099  isContentVisible() {
7100    for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
7101      if (!this.markedContentStack[i].visible) {
7102        return false;
vendor: 7,548 bytes, lines 7103-7358
7103      }
7104    }
7105    return true;
7106  }
7107}
7108exports.CanvasGraphics = CanvasGraphics;
7109for (const op in _util.OPS) {
7110  if (CanvasGraphics.prototype[op] !== undefined) {
7111    CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
7112  }
7113}
7114
7115/***/ }),
7116/* 12 */
7117/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7118
7119
7120
7121Object.defineProperty(exports, "__esModule", ({
7122  value: true
7123}));
7124exports.TilingPattern = exports.PathType = void 0;
7125exports.getShadingPattern = getShadingPattern;
7126var _util = __w_pdfjs_require__(1);
7127var _display_utils = __w_pdfjs_require__(6);
7128const PathType = {
7129  FILL: "Fill",
7130  STROKE: "Stroke",
7131  SHADING: "Shading"
7132};
7133exports.PathType = PathType;
7134function applyBoundingBox(ctx, bbox) {
7135  if (!bbox) {
7136    return;
7137  }
7138  const width = bbox[2] - bbox[0];
7139  const height = bbox[3] - bbox[1];
7140  const region = new Path2D();
7141  region.rect(bbox[0], bbox[1], width, height);
7142  ctx.clip(region);
7143}
7144class BaseShadingPattern {
7145  constructor() {
7146    if (this.constructor === BaseShadingPattern) {
7147      (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
7148    }
7149  }
7150  getPattern() {
7151    (0, _util.unreachable)("Abstract method `getPattern` called.");
7152  }
7153}
7154class RadialAxialShadingPattern extends BaseShadingPattern {
7155  constructor(IR) {
7156    super();
7157    this._type = IR[1];
7158    this._bbox = IR[2];
7159    this._colorStops = IR[3];
7160    this._p0 = IR[4];
7161    this._p1 = IR[5];
7162    this._r0 = IR[6];
7163    this._r1 = IR[7];
7164    this.matrix = null;
7165  }
7166  _createGradient(ctx) {
7167    let grad;
7168    if (this._type === "axial") {
7169      grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
7170    } else if (this._type === "radial") {
7171      grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
7172    }
7173    for (const colorStop of this._colorStops) {
7174      grad.addColorStop(colorStop[0], colorStop[1]);
7175    }
7176    return grad;
7177  }
7178  getPattern(ctx, owner, inverse, pathType) {
7179    let pattern;
7180    if (pathType === PathType.STROKE || pathType === PathType.FILL) {
7181      const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, (0, _display_utils.getCurrentTransform)(ctx)) || [0, 0, 0, 0];
7182      const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
7183      const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
7184      const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
7185      const tmpCtx = tmpCanvas.context;
7186      tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
7187      tmpCtx.beginPath();
7188      tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
7189      tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
7190      inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
7191      tmpCtx.transform(...owner.baseTransform);
7192      if (this.matrix) {
7193        tmpCtx.transform(...this.matrix);
7194      }
7195      applyBoundingBox(tmpCtx, this._bbox);
7196      tmpCtx.fillStyle = this._createGradient(tmpCtx);
7197      tmpCtx.fill();
7198      pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
7199      const domMatrix = new DOMMatrix(inverse);
7200      pattern.setTransform(domMatrix);
7201    } else {
7202      applyBoundingBox(ctx, this._bbox);
7203      pattern = this._createGradient(ctx);
7204    }
7205    return pattern;
7206  }
7207}
7208function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
7209  const coords = context.coords,
7210    colors = context.colors;
7211  const bytes = data.data,
7212    rowSize = data.width * 4;
7213  let tmp;
7214  if (coords[p1 + 1] > coords[p2 + 1]) {
7215    tmp = p1;
7216    p1 = p2;
7217    p2 = tmp;
7218    tmp = c1;
7219    c1 = c2;
7220    c2 = tmp;
7221  }
7222  if (coords[p2 + 1] > coords[p3 + 1]) {
7223    tmp = p2;
7224    p2 = p3;
7225    p3 = tmp;
7226    tmp = c2;
7227    c2 = c3;
7228    c3 = tmp;
7229  }
7230  if (coords[p1 + 1] > coords[p2 + 1]) {
7231    tmp = p1;
7232    p1 = p2;
7233    p2 = tmp;
7234    tmp = c1;
7235    c1 = c2;
7236    c2 = tmp;
7237  }
7238  const x1 = (coords[p1] + context.offsetX) * context.scaleX;
7239  const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
7240  const x2 = (coords[p2] + context.offsetX) * context.scaleX;
7241  const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
7242  const x3 = (coords[p3] + context.offsetX) * context.scaleX;
7243  const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
7244  if (y1 >= y3) {
7245    return;
7246  }
7247  const c1r = colors[c1],
7248    c1g = colors[c1 + 1],
7249    c1b = colors[c1 + 2];
7250  const c2r = colors[c2],
7251    c2g = colors[c2 + 1],
7252    c2b = colors[c2 + 2];
7253  const c3r = colors[c3],
7254    c3g = colors[c3 + 1],
7255    c3b = colors[c3 + 2];
7256  const minY = Math.round(y1),
7257    maxY = Math.round(y3);
7258  let xa, car, cag, cab;
7259  let xb, cbr, cbg, cbb;
7260  for (let y = minY; y <= maxY; y++) {
7261    if (y < y2) {
7262      let k;
7263      if (y < y1) {
7264        k = 0;
7265      } else {
7266        k = (y1 - y) / (y1 - y2);
7267      }
7268      xa = x1 - (x1 - x2) * k;
7269      car = c1r - (c1r - c2r) * k;
7270      cag = c1g - (c1g - c2g) * k;
7271      cab = c1b - (c1b - c2b) * k;
7272    } else {
7273      let k;
7274      if (y > y3) {
7275        k = 1;
7276      } else if (y2 === y3) {
7277        k = 0;
7278      } else {
7279        k = (y2 - y) / (y2 - y3);
7280      }
7281      xa = x2 - (x2 - x3) * k;
7282      car = c2r - (c2r - c3r) * k;
7283      cag = c2g - (c2g - c3g) * k;
7284      cab = c2b - (c2b - c3b) * k;
7285    }
7286    let k;
7287    if (y < y1) {
7288      k = 0;
7289    } else if (y > y3) {
7290      k = 1;
7291    } else {
7292      k = (y1 - y) / (y1 - y3);
7293    }
7294    xb = x1 - (x1 - x3) * k;
7295    cbr = c1r - (c1r - c3r) * k;
7296    cbg = c1g - (c1g - c3g) * k;
7297    cbb = c1b - (c1b - c3b) * k;
7298    const x1_ = Math.round(Math.min(xa, xb));
7299    const x2_ = Math.round(Math.max(xa, xb));
7300    let j = rowSize * y + x1_ * 4;
7301    for (let x = x1_; x <= x2_; x++) {
7302      k = (xa - x) / (xa - xb);
7303      if (k < 0) {
7304        k = 0;
7305      } else if (k > 1) {
7306        k = 1;
7307      }
7308      bytes[j++] = car - (car - cbr) * k | 0;
7309      bytes[j++] = cag - (cag - cbg) * k | 0;
7310      bytes[j++] = cab - (cab - cbb) * k | 0;
7311      bytes[j++] = 255;
7312    }
7313  }
7314}
7315function drawFigure(data, figure, context) {
7316  const ps = figure.coords;
7317  const cs = figure.colors;
7318  let i, ii;
7319  switch (figure.type) {
7320    case "lattice":
7321      const verticesPerRow = figure.verticesPerRow;
7322      const rows = Math.floor(ps.length / verticesPerRow) - 1;
7323      const cols = verticesPerRow - 1;
7324      for (i = 0; i < rows; i++) {
7325        let q = i * verticesPerRow;
7326        for (let j = 0; j < cols; j++, q++) {
7327          drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
7328          drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
7329        }
7330      }
7331      break;
7332    case "triangles":
7333      for (i = 0, ii = ps.length; i < ii; i += 3) {
7334        drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
7335      }
7336      break;
7337    default:
7338      throw new Error("illegal figure");
7339  }
7340}
7341class MeshShadingPattern extends BaseShadingPattern {
7342  constructor(IR) {
7343    super();
7344    this._coords = IR[2];
7345    this._colors = IR[3];
7346    this._figures = IR[4];
7347    this._bounds = IR[5];
7348    this._bbox = IR[7];
7349    this._background = IR[8];
7350    this.matrix = null;
7351  }
7352  _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
7353    const EXPECTED_SCALE = 1.1;
7354    const MAX_PATTERN_SIZE = 3000;
7355    const BORDER_SIZE = 2;
7356    const offsetX = Math.floor(this._bounds[0]);
7357    const offsetY = Math.floor(this._bounds[1]);
7358    const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
7359    const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
7360    const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
7361    const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
7362    const scaleX = boundsWidth / width;
7363    const scaleY = boundsHeight / height;
7364    const context = {
7365      coords: this._coords,
7366      colors: this._colors,
7367      offsetX: -offsetX,
7368      offsetY: -offsetY,
7369      scaleX: 1 / scaleX,
7370      scaleY: 1 / scaleY
7371    };
7372    const paddedWidth = width + BORDER_SIZE * 2;
7373    const paddedHeight = height + BORDER_SIZE * 2;
7374    const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
7375    const tmpCtx = tmpCanvas.context;
7376    const data = tmpCtx.createImageData(width, height);
7377    if (backgroundColor) {
7378      const bytes = data.data;
7379      for (let i = 0, ii = bytes.length; i < ii; i += 4) {
7380        bytes[i] = backgroundColor[0];
7381        bytes[i + 1] = backgroundColor[1];
7382        bytes[i + 2] = backgroundColor[2];
7383        bytes[i + 3] = 255;
7384      }
7385    }
7386    for (const figure of this._figures) {
7387      drawFigure(data, figure, context);
7388    }
7389    tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
7390    const canvas = tmpCanvas.canvas;
7391    return {
7392      canvas,
7393      offsetX: offsetX - BORDER_SIZE * scaleX,
7394      offsetY: offsetY - BORDER_SIZE * scaleY,
7395      scaleX,
7396      scaleY
7397    };
7398  }
7399  getPattern(ctx, owner, inverse, pathType) {
7400    applyBoundingBox(ctx, this._bbox);
7401    let scale;
7402    if (pathType === PathType.SHADING) {
7403      scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx));
7404    } else {
7405      scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
7406      if (this.matrix) {
7407        const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
7408        scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
7409      }
7410    }
7411    const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
7412    if (pathType !== PathType.SHADING) {
7413      ctx.setTransform(...owner.baseTransform);
7414      if (this.matrix) {
7415        ctx.transform(...this.matrix);
7416      }
7417    }
7418    ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
7419    ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
7420    return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
7421  }
7422}
7423class DummyShadingPattern extends BaseShadingPattern {
7424  getPattern() {
7425    return "hotpink";
7426  }
7427}
7428function getShadingPattern(IR) {
7429  switch (IR[0]) {
7430    case "RadialAxial":
7431      return new RadialAxialShadingPattern(IR);
7432    case "Mesh":
7433      return new MeshShadingPattern(IR);
7434    case "Dummy":
7435      return new DummyShadingPattern();
7436  }
7437  throw new Error(`Unknown IR type: ${IR[0]}`);
7438}
7439const PaintType = {
7440  COLORED: 1,
7441  UNCOLORED: 2
7442};
7443class TilingPattern {
7444  static get MAX_PATTERN_SIZE() {
7445    return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
7446  }
7447  constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
7448    this.operatorList = IR[2];
7449    this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
7450    this.bbox = IR[4];
7451    this.xstep = IR[5];
7452    this.ystep = IR[6];
7453    this.paintType = IR[7];
7454    this.tilingType = IR[8];
7455    this.color = color;
7456    this.ctx = ctx;
7457    this.canvasGraphicsFactory = canvasGraphicsFactory;
7458    this.baseTransform = baseTransform;
7459  }
7460  createPatternCanvas(owner) {
7461    const operatorList = this.operatorList;
7462    const bbox = this.bbox;
7463    const xstep = this.xstep;
7464    const ystep = this.ystep;
7465    const paintType = this.paintType;
7466    const tilingType = this.tilingType;
7467    const color = this.color;
7468    const canvasGraphicsFactory = this.canvasGraphicsFactory;
7469    (0, _util.info)("TilingType: " + tilingType);
7470    const x0 = bbox[0],
7471      y0 = bbox[1],
7472      x1 = bbox[2],
7473      y1 = bbox[3];
7474    const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
7475    const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
7476    const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
7477    const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
7478    const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
7479    const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
7480    const tmpCtx = tmpCanvas.context;
7481    const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
7482    graphics.groupLevel = owner.groupLevel;
7483    this.setFillAndStrokeStyleToContext(graphics, paintType, color);
7484    let adjustedX0 = x0;
7485    let adjustedY0 = y0;
7486    let adjustedX1 = x1;
7487    let adjustedY1 = y1;
7488    if (x0 < 0) {
7489      adjustedX0 = 0;
7490      adjustedX1 += Math.abs(x0);
7491    }
7492    if (y0 < 0) {
7493      adjustedY0 = 0;
7494      adjustedY1 += Math.abs(y0);
7495    }
7496    tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
7497    graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
7498    tmpCtx.save();
7499    this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
7500    graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx);
7501    graphics.executeOperatorList(operatorList);
7502    graphics.endDrawing();
7503    return {
7504      canvas: tmpCanvas.canvas,
7505      scaleX: dimx.scale,
7506      scaleY: dimy.scale,
7507      offsetX: adjustedX0,
7508      offsetY: adjustedY0
7509    };
7510  }
7511  getSizeAndScale(step, realOutputSize, scale) {
7512    step = Math.abs(step);
7513    const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
7514    let size = Math.ceil(step * scale);
7515    if (size >= maxSize) {
7516      size = maxSize;
7517    } else {
7518      scale = size / step;
7519    }
7520    return {
7521      scale,
7522      size
7523    };
7524  }
7525  clipBbox(graphics, x0, y0, x1, y1) {
7526    const bboxWidth = x1 - x0;
7527    const bboxHeight = y1 - y0;
7528    graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
7529    graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]);
7530    graphics.clip();
7531    graphics.endPath();
7532  }
7533  setFillAndStrokeStyleToContext(graphics, paintType, color) {
7534    const context = graphics.ctx,
7535      current = graphics.current;
7536    switch (paintType) {
7537      case PaintType.COLORED:
7538        const ctx = this.ctx;
7539        context.fillStyle = ctx.fillStyle;
7540        context.strokeStyle = ctx.strokeStyle;
7541        current.fillColor = ctx.fillStyle;
7542        current.strokeColor = ctx.strokeStyle;
7543        break;
7544      case PaintType.UNCOLORED:
7545        const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
7546        context.fillStyle = cssColor;
7547        context.strokeStyle = cssColor;
7548        current.fillColor = cssColor;
7549        current.strokeColor = cssColor;
7550        break;
7551      default:
7552        throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
7553    }
7554  }
7555  getPattern(ctx, owner, inverse, pathType) {
7556    let matrix = inverse;
7557    if (pathType !== PathType.SHADING) {
7558      matrix = _util.Util.transform(matrix, owner.baseTransform);
7559      if (this.matrix) {
7560        matrix = _util.Util.transform(matrix, this.matrix);
7561      }
7562    }
7563    const temporaryPatternCanvas = this.createPatternCanvas(owner);
7564    let domMatrix = new DOMMatrix(matrix);
7565    domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
7566    domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
7567    const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
7568    pattern.setTransform(domMatrix);
7569    return pattern;
7570  }
7571}
7572exports.TilingPattern = TilingPattern;
7573
7574/***/ }),
7575/* 13 */
7576/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7577
7578
7579
7580Object.defineProperty(exports, "__esModule", ({
7581  value: true
7582}));
7583exports.applyMaskImageData = applyMaskImageData;
7584var _util = __w_pdfjs_require__(1);
7585function applyMaskImageData({
7586  src,
7587  srcPos = 0,
7588  dest,
7589  destPos = 0,
7590  width,
7591  height,
7592  inverseDecode = false
7593}) {
7594  const opaque = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
7595  const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
7596  const widthInSource = width >> 3;
7597  const widthRemainder = width & 7;
7598  const srcLength = src.length;
7599  dest = new Uint32Array(dest.buffer);
7600  for (let i = 0; i < height; i++) {
7601    for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
7602      const elem = srcPos < srcLength ? src[srcPos] : 255;
7603      dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
7604      dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
7605      dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
7606      dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
7607      dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
7608      dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
7609      dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
7610      dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
7611    }
7612    if (widthRemainder === 0) {
7613      continue;
7614    }
7615    const elem = srcPos < srcLength ? src[srcPos++] : 255;
7616    for (let j = 0; j < widthRemainder; j++) {
7617      dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
7618    }
7619  }
7620  return {
7621    srcPos,
7622    destPos
7623  };
7624}
7625
7626/***/ }),
7627/* 14 */
vendor: 16,110 bytes, lines 7628-8169
7628/***/ ((__unused_webpack_module, exports) => {
7629
7630
7631
7632Object.defineProperty(exports, "__esModule", ({
7633  value: true
7634}));
7635exports.GlobalWorkerOptions = void 0;
7636const GlobalWorkerOptions = Object.create(null);
7637exports.GlobalWorkerOptions = GlobalWorkerOptions;
7638GlobalWorkerOptions.workerPort = null;
7639GlobalWorkerOptions.workerSrc = "";
7640
7641/***/ }),
7642/* 15 */
7643/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7644
7645
7646
7647Object.defineProperty(exports, "__esModule", ({
7648  value: true
7649}));
7650exports.MessageHandler = void 0;
7651var _util = __w_pdfjs_require__(1);
7652const CallbackKind = {
7653  UNKNOWN: 0,
7654  DATA: 1,
7655  ERROR: 2
7656};
7657const StreamKind = {
7658  UNKNOWN: 0,
7659  CANCEL: 1,
7660  CANCEL_COMPLETE: 2,
7661  CLOSE: 3,
7662  ENQUEUE: 4,
7663  ERROR: 5,
7664  PULL: 6,
7665  PULL_COMPLETE: 7,
7666  START_COMPLETE: 8
7667};
7668function wrapReason(reason) {
7669  if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
7670    (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
7671  }
7672  switch (reason.name) {
7673    case "AbortException":
7674      return new _util.AbortException(reason.message);
7675    case "MissingPDFException":
7676      return new _util.MissingPDFException(reason.message);
7677    case "PasswordException":
7678      return new _util.PasswordException(reason.message, reason.code);
7679    case "UnexpectedResponseException":
7680      return new _util.UnexpectedResponseException(reason.message, reason.status);
7681    case "UnknownErrorException":
7682      return new _util.UnknownErrorException(reason.message, reason.details);
7683    default:
7684      return new _util.UnknownErrorException(reason.message, reason.toString());
7685  }
7686}
7687class MessageHandler {
7688  constructor(sourceName, targetName, comObj) {
7689    this.sourceName = sourceName;
7690    this.targetName = targetName;
7691    this.comObj = comObj;
7692    this.callbackId = 1;
7693    this.streamId = 1;
7694    this.streamSinks = Object.create(null);
7695    this.streamControllers = Object.create(null);
7696    this.callbackCapabilities = Object.create(null);
7697    this.actionHandler = Object.create(null);
7698    this._onComObjOnMessage = event => {
7699      const data = event.data;
7700      if (data.targetName !== this.sourceName) {
7701        return;
7702      }
7703      if (data.stream) {
7704        this._processStreamMessage(data);
7705        return;
7706      }
7707      if (data.callback) {
7708        const callbackId = data.callbackId;
7709        const capability = this.callbackCapabilities[callbackId];
7710        if (!capability) {
7711          throw new Error(`Cannot resolve callback ${callbackId}`);
7712        }
7713        delete this.callbackCapabilities[callbackId];
7714        if (data.callback === CallbackKind.DATA) {
7715          capability.resolve(data.data);
7716        } else if (data.callback === CallbackKind.ERROR) {
7717          capability.reject(wrapReason(data.reason));
7718        } else {
7719          throw new Error("Unexpected callback case");
7720        }
7721        return;
7722      }
7723      const action = this.actionHandler[data.action];
7724      if (!action) {
7725        throw new Error(`Unknown action from worker: ${data.action}`);
7726      }
7727      if (data.callbackId) {
7728        const cbSourceName = this.sourceName;
7729        const cbTargetName = data.sourceName;
7730        new Promise(function (resolve) {
7731          resolve(action(data.data));
7732        }).then(function (result) {
7733          comObj.postMessage({
7734            sourceName: cbSourceName,
7735            targetName: cbTargetName,
7736            callback: CallbackKind.DATA,
7737            callbackId: data.callbackId,
7738            data: result
7739          });
7740        }, function (reason) {
7741          comObj.postMessage({
7742            sourceName: cbSourceName,
7743            targetName: cbTargetName,
7744            callback: CallbackKind.ERROR,
7745            callbackId: data.callbackId,
7746            reason: wrapReason(reason)
7747          });
7748        });
7749        return;
7750      }
7751      if (data.streamId) {
7752        this._createStreamSink(data);
7753        return;
7754      }
7755      action(data.data);
7756    };
7757    comObj.addEventListener("message", this._onComObjOnMessage);
7758  }
7759  on(actionName, handler) {
7760    const ah = this.actionHandler;
7761    if (ah[actionName]) {
7762      throw new Error(`There is already an actionName called "${actionName}"`);
7763    }
7764    ah[actionName] = handler;
7765  }
7766  send(actionName, data, transfers) {
7767    this.comObj.postMessage({
7768      sourceName: this.sourceName,
7769      targetName: this.targetName,
7770      action: actionName,
7771      data
7772    }, transfers);
7773  }
7774  sendWithPromise(actionName, data, transfers) {
7775    const callbackId = this.callbackId++;
7776    const capability = (0, _util.createPromiseCapability)();
7777    this.callbackCapabilities[callbackId] = capability;
7778    try {
7779      this.comObj.postMessage({
7780        sourceName: this.sourceName,
7781        targetName: this.targetName,
7782        action: actionName,
7783        callbackId,
7784        data
7785      }, transfers);
7786    } catch (ex) {
7787      capability.reject(ex);
7788    }
7789    return capability.promise;
7790  }
7791  sendWithStream(actionName, data, queueingStrategy, transfers) {
7792    const streamId = this.streamId++,
7793      sourceName = this.sourceName,
7794      targetName = this.targetName,
7795      comObj = this.comObj;
7796    return new ReadableStream({
7797      start: controller => {
7798        const startCapability = (0, _util.createPromiseCapability)();
7799        this.streamControllers[streamId] = {
7800          controller,
7801          startCall: startCapability,
7802          pullCall: null,
7803          cancelCall: null,
7804          isClosed: false
7805        };
7806        comObj.postMessage({
7807          sourceName,
7808          targetName,
7809          action: actionName,
7810          streamId,
7811          data,
7812          desiredSize: controller.desiredSize
7813        }, transfers);
7814        return startCapability.promise;
7815      },
7816      pull: controller => {
7817        const pullCapability = (0, _util.createPromiseCapability)();
7818        this.streamControllers[streamId].pullCall = pullCapability;
7819        comObj.postMessage({
7820          sourceName,
7821          targetName,
7822          stream: StreamKind.PULL,
7823          streamId,
7824          desiredSize: controller.desiredSize
7825        });
7826        return pullCapability.promise;
7827      },
7828      cancel: reason => {
7829        (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
7830        const cancelCapability = (0, _util.createPromiseCapability)();
7831        this.streamControllers[streamId].cancelCall = cancelCapability;
7832        this.streamControllers[streamId].isClosed = true;
7833        comObj.postMessage({
7834          sourceName,
7835          targetName,
7836          stream: StreamKind.CANCEL,
7837          streamId,
7838          reason: wrapReason(reason)
7839        });
7840        return cancelCapability.promise;
7841      }
7842    }, queueingStrategy);
7843  }
7844  _createStreamSink(data) {
7845    const streamId = data.streamId,
7846      sourceName = this.sourceName,
7847      targetName = data.sourceName,
7848      comObj = this.comObj;
7849    const self = this,
7850      action = this.actionHandler[data.action];
7851    const streamSink = {
7852      enqueue(chunk, size = 1, transfers) {
7853        if (this.isCancelled) {
7854          return;
7855        }
7856        const lastDesiredSize = this.desiredSize;
7857        this.desiredSize -= size;
7858        if (lastDesiredSize > 0 && this.desiredSize <= 0) {
7859          this.sinkCapability = (0, _util.createPromiseCapability)();
7860          this.ready = this.sinkCapability.promise;
7861        }
7862        comObj.postMessage({
7863          sourceName,
7864          targetName,
7865          stream: StreamKind.ENQUEUE,
7866          streamId,
7867          chunk
7868        }, transfers);
7869      },
7870      close() {
7871        if (this.isCancelled) {
7872          return;
7873        }
7874        this.isCancelled = true;
7875        comObj.postMessage({
7876          sourceName,
7877          targetName,
7878          stream: StreamKind.CLOSE,
7879          streamId
7880        });
7881        delete self.streamSinks[streamId];
7882      },
7883      error(reason) {
7884        (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
7885        if (this.isCancelled) {
7886          return;
7887        }
7888        this.isCancelled = true;
7889        comObj.postMessage({
7890          sourceName,
7891          targetName,
7892          stream: StreamKind.ERROR,
7893          streamId,
7894          reason: wrapReason(reason)
7895        });
7896      },
7897      sinkCapability: (0, _util.createPromiseCapability)(),
7898      onPull: null,
7899      onCancel: null,
7900      isCancelled: false,
7901      desiredSize: data.desiredSize,
7902      ready: null
7903    };
7904    streamSink.sinkCapability.resolve();
7905    streamSink.ready = streamSink.sinkCapability.promise;
7906    this.streamSinks[streamId] = streamSink;
7907    new Promise(function (resolve) {
7908      resolve(action(data.data, streamSink));
7909    }).then(function () {
7910      comObj.postMessage({
7911        sourceName,
7912        targetName,
7913        stream: StreamKind.START_COMPLETE,
7914        streamId,
7915        success: true
7916      });
7917    }, function (reason) {
7918      comObj.postMessage({
7919        sourceName,
7920        targetName,
7921        stream: StreamKind.START_COMPLETE,
7922        streamId,
7923        reason: wrapReason(reason)
7924      });
7925    });
7926  }
7927  _processStreamMessage(data) {
7928    const streamId = data.streamId,
7929      sourceName = this.sourceName,
7930      targetName = data.sourceName,
7931      comObj = this.comObj;
7932    const streamController = this.streamControllers[streamId],
7933      streamSink = this.streamSinks[streamId];
7934    switch (data.stream) {
7935      case StreamKind.START_COMPLETE:
7936        if (data.success) {
7937          streamController.startCall.resolve();
7938        } else {
7939          streamController.startCall.reject(wrapReason(data.reason));
7940        }
7941        break;
7942      case StreamKind.PULL_COMPLETE:
7943        if (data.success) {
7944          streamController.pullCall.resolve();
7945        } else {
7946          streamController.pullCall.reject(wrapReason(data.reason));
7947        }
7948        break;
7949      case StreamKind.PULL:
7950        if (!streamSink) {
7951          comObj.postMessage({
7952            sourceName,
7953            targetName,
7954            stream: StreamKind.PULL_COMPLETE,
7955            streamId,
7956            success: true
7957          });
7958          break;
7959        }
7960        if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
7961          streamSink.sinkCapability.resolve();
7962        }
7963        streamSink.desiredSize = data.desiredSize;
7964        new Promise(function (resolve) {
7965          resolve(streamSink.onPull && streamSink.onPull());
7966        }).then(function () {
7967          comObj.postMessage({
7968            sourceName,
7969            targetName,
7970            stream: StreamKind.PULL_COMPLETE,
7971            streamId,
7972            success: true
7973          });
7974        }, function (reason) {
7975          comObj.postMessage({
7976            sourceName,
7977            targetName,
7978            stream: StreamKind.PULL_COMPLETE,
7979            streamId,
7980            reason: wrapReason(reason)
7981          });
7982        });
7983        break;
7984      case StreamKind.ENQUEUE:
7985        (0, _util.assert)(streamController, "enqueue should have stream controller");
7986        if (streamController.isClosed) {
7987          break;
7988        }
7989        streamController.controller.enqueue(data.chunk);
7990        break;
7991      case StreamKind.CLOSE:
7992        (0, _util.assert)(streamController, "close should have stream controller");
7993        if (streamController.isClosed) {
7994          break;
7995        }
7996        streamController.isClosed = true;
7997        streamController.controller.close();
7998        this._deleteStreamController(streamController, streamId);
7999        break;
8000      case StreamKind.ERROR:
8001        (0, _util.assert)(streamController, "error should have stream controller");
8002        streamController.controller.error(wrapReason(data.reason));
8003        this._deleteStreamController(streamController, streamId);
8004        break;
8005      case StreamKind.CANCEL_COMPLETE:
8006        if (data.success) {
8007          streamController.cancelCall.resolve();
8008        } else {
8009          streamController.cancelCall.reject(wrapReason(data.reason));
8010        }
8011        this._deleteStreamController(streamController, streamId);
8012        break;
8013      case StreamKind.CANCEL:
8014        if (!streamSink) {
8015          break;
8016        }
8017        new Promise(function (resolve) {
8018          resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
8019        }).then(function () {
8020          comObj.postMessage({
8021            sourceName,
8022            targetName,
8023            stream: StreamKind.CANCEL_COMPLETE,
8024            streamId,
8025            success: true
8026          });
8027        }, function (reason) {
8028          comObj.postMessage({
8029            sourceName,
8030            targetName,
8031            stream: StreamKind.CANCEL_COMPLETE,
8032            streamId,
8033            reason: wrapReason(reason)
8034          });
8035        });
8036        streamSink.sinkCapability.reject(wrapReason(data.reason));
8037        streamSink.isCancelled = true;
8038        delete this.streamSinks[streamId];
8039        break;
8040      default:
8041        throw new Error("Unexpected stream case");
8042    }
8043  }
8044  async _deleteStreamController(streamController, streamId) {
8045    await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
8046    delete this.streamControllers[streamId];
8047  }
8048  destroy() {
8049    this.comObj.removeEventListener("message", this._onComObjOnMessage);
8050  }
8051}
8052exports.MessageHandler = MessageHandler;
8053
8054/***/ }),
8055/* 16 */
8056/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8057
8058
8059
8060Object.defineProperty(exports, "__esModule", ({
8061  value: true
8062}));
8063exports.Metadata = void 0;
8064var _util = __w_pdfjs_require__(1);
8065class Metadata {
8066  #metadataMap;
8067  #data;
8068  constructor({
8069    parsedData,
8070    rawData
8071  }) {
8072    this.#metadataMap = parsedData;
8073    this.#data = rawData;
8074  }
8075  getRaw() {
8076    return this.#data;
8077  }
8078  get(name) {
8079    return this.#metadataMap.get(name) ?? null;
8080  }
8081  getAll() {
8082    return (0, _util.objectFromMap)(this.#metadataMap);
8083  }
8084  has(name) {
8085    return this.#metadataMap.has(name);
8086  }
8087}
8088exports.Metadata = Metadata;
8089
8090/***/ }),
8091/* 17 */
8092/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8093
8094
8095
8096Object.defineProperty(exports, "__esModule", ({
8097  value: true
8098}));
8099exports.OptionalContentConfig = void 0;
8100var _util = __w_pdfjs_require__(1);
8101var _murmurhash = __w_pdfjs_require__(8);
8102const INTERNAL = Symbol("INTERNAL");
8103class OptionalContentGroup {
8104  #visible = true;
8105  constructor(name, intent) {
8106    this.name = name;
8107    this.intent = intent;
8108  }
8109  get visible() {
8110    return this.#visible;
8111  }
8112  _setVisible(internal, visible) {
8113    if (internal !== INTERNAL) {
8114      (0, _util.unreachable)("Internal method `_setVisible` called.");
8115    }
8116    this.#visible = visible;
8117  }
8118}
8119class OptionalContentConfig {
8120  #cachedGetHash = null;
8121  #groups = new Map();
8122  #initialHash = null;
8123  #order = null;
8124  constructor(data) {
8125    this.name = null;
8126    this.creator = null;
8127    if (data === null) {
8128      return;
8129    }
8130    this.name = data.name;
8131    this.creator = data.creator;
8132    this.#order = data.order;
8133    for (const group of data.groups) {
8134      this.#groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
8135    }
8136    if (data.baseState === "OFF") {
8137      for (const group of this.#groups.values()) {
8138        group._setVisible(INTERNAL, false);
8139      }
8140    }
8141    for (const on of data.on) {
8142      this.#groups.get(on)._setVisible(INTERNAL, true);
8143    }
8144    for (const off of data.off) {
8145      this.#groups.get(off)._setVisible(INTERNAL, false);
8146    }
8147    this.#initialHash = this.getHash();
8148  }
8149  #evaluateVisibilityExpression(array) {
8150    const length = array.length;
8151    if (length < 2) {
8152      return true;
8153    }
8154    const operator = array[0];
8155    for (let i = 1; i < length; i++) {
8156      const element = array[i];
8157      let state;
8158      if (Array.isArray(element)) {
8159        state = this.#evaluateVisibilityExpression(element);
8160      } else if (this.#groups.has(element)) {
8161        state = this.#groups.get(element).visible;
8162      } else {
8163        (0, _util.warn)(`Optional content group not found: ${element}`);
8164        return true;
8165      }
8166      switch (operator) {
8167        case "And":
8168          if (!state) {
8169            return false;
8170          }
8171          break;
8172        case "Or":
8173          if (state) {
8174            return true;
8175          }
8176          break;
8177        case "Not":
8178          return !state;
8179        default:
8180          return true;
8181      }
8182    }
8183    return operator === "And";
8184  }
8185  isVisible(group) {
8186    if (this.#groups.size === 0) {
8187      return true;
8188    }
8189    if (!group) {
8190      (0, _util.warn)("Optional content group not defined.");
8191      return true;
8192    }
8193    if (group.type === "OCG") {
8194      if (!this.#groups.has(group.id)) {
8195        (0, _util.warn)(`Optional content group not found: ${group.id}`);
8196        return true;
8197      }
8198      return this.#groups.get(group.id).visible;
8199    } else if (group.type === "OCMD") {
8200      if (group.expression) {
8201        return this.#evaluateVisibilityExpression(group.expression);
8202      }
8203      if (!group.policy || group.policy === "AnyOn") {
8204        for (const id of group.ids) {
8205          if (!this.#groups.has(id)) {
8206            (0, _util.warn)(`Optional content group not found: ${id}`);
8207            return true;
8208          }
8209          if (this.#groups.get(id).visible) {
8210            return true;
8211          }
8212        }
8213        return false;
8214      } else if (group.policy === "AllOn") {
8215        for (const id of group.ids) {
8216          if (!this.#groups.has(id)) {
8217            (0, _util.warn)(`Optional content group not found: ${id}`);
8218            return true;
8219          }
8220          if (!this.#groups.get(id).visible) {
8221            return false;
8222          }
8223        }
8224        return true;
8225      } else if (group.policy === "AnyOff") {
8226        for (const id of group.ids) {
8227          if (!this.#groups.has(id)) {
8228            (0, _util.warn)(`Optional content group not found: ${id}`);
8229            return true;
8230          }
8231          if (!this.#groups.get(id).visible) {
8232            return true;
8233          }
8234        }
8235        return false;
8236      } else if (group.policy === "AllOff") {
8237        for (const id of group.ids) {
8238          if (!this.#groups.has(id)) {
8239            (0, _util.warn)(`Optional content group not found: ${id}`);
8240            return true;
8241          }
8242          if (this.#groups.get(id).visible) {
8243            return false;
8244          }
8245        }
8246        return true;
8247      }
8248      (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
8249      return true;
8250    }
8251    (0, _util.warn)(`Unknown group type ${group.type}.`);
8252    return true;
8253  }
8254  setVisibility(id, visible = true) {
8255    if (!this.#groups.has(id)) {
8256      (0, _util.warn)(`Optional content group not found: ${id}`);
8257      return;
8258    }
8259    this.#groups.get(id)._setVisible(INTERNAL, !!visible);
8260    this.#cachedGetHash = null;
8261  }
8262  get hasInitialVisibility() {
8263    return this.getHash() === this.#initialHash;
8264  }
8265  getOrder() {
8266    if (!this.#groups.size) {
8267      return null;
8268    }
8269    if (this.#order) {
8270      return this.#order.slice();
8271    }
8272    return [...this.#groups.keys()];
8273  }
8274  getGroups() {
8275    return this.#groups.size > 0 ? (0, _util.objectFromMap)(this.#groups) : null;
8276  }
8277  getGroup(id) {
8278    return this.#groups.get(id) || null;
8279  }
8280  getHash() {
8281    if (this.#cachedGetHash !== null) {
8282      return this.#cachedGetHash;
8283    }
8284    const hash = new _murmurhash.MurmurHash3_64();
8285    for (const [id, group] of this.#groups) {
8286      hash.update(`${id}:${group.visible}`);
8287    }
8288    return this.#cachedGetHash = hash.hexdigest();
8289  }
8290}
8291exports.OptionalContentConfig = OptionalContentConfig;
8292
8293/***/ }),
8294/* 18 */
8295/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8296
8297
8298
8299Object.defineProperty(exports, "__esModule", ({
8300  value: true
8301}));
8302exports.PDFDataTransportStream = void 0;
8303var _util = __w_pdfjs_require__(1);
8304var _display_utils = __w_pdfjs_require__(6);
8305class PDFDataTransportStream {
8306  constructor({
8307    length,
8308    initialData,
8309    progressiveDone = false,
8310    contentDispositionFilename = null,
8311    disableRange = false,
8312    disableStream = false
8313  }, pdfDataRangeTransport) {
8314    (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
8315    this._queuedChunks = [];
8316    this._progressiveDone = progressiveDone;
8317    this._contentDispositionFilename = contentDispositionFilename;
8318    if (initialData?.length > 0) {
8319      const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
8320      this._queuedChunks.push(buffer);
8321    }
8322    this._pdfDataRangeTransport = pdfDataRangeTransport;
8323    this._isStreamingSupported = !disableStream;
8324    this._isRangeSupported = !disableRange;
8325    this._contentLength = length;
8326    this._fullRequestReader = null;
8327    this._rangeReaders = [];
8328    this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
8329      this._onReceiveData({
8330        begin,
8331        chunk
8332      });
8333    });
8334    this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
8335      this._onProgress({
8336        loaded,
8337        total
8338      });
8339    });
8340    this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
8341      this._onReceiveData({
8342        chunk
8343      });
8344    });
8345    this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
8346      this._onProgressiveDone();
8347    });
8348    this._pdfDataRangeTransport.transportReady();
8349  }
8350  _onReceiveData({
8351    begin,
8352    chunk
8353  }) {
8354    const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
8355    if (begin === undefined) {
8356      if (this._fullRequestReader) {
8357        this._fullRequestReader._enqueue(buffer);
8358      } else {
8359        this._queuedChunks.push(buffer);
8360      }
8361    } else {
8362      const found = this._rangeReaders.some(function (rangeReader) {
8363        if (rangeReader._begin !== begin) {
8364          return false;
8365        }
8366        rangeReader._enqueue(buffer);
8367        return true;
8368      });
8369      (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
8370    }
8371  }
8372  get _progressiveDataLength() {
8373    return this._fullRequestReader?._loaded ?? 0;
8374  }
8375  _onProgress(evt) {
8376    if (evt.total === undefined) {
8377      this._rangeReaders[0]?.onProgress?.({
8378        loaded: evt.loaded
8379      });
8380    } else {
8381      this._fullRequestReader?.onProgress?.({
8382        loaded: evt.loaded,
8383        total: evt.total
8384      });
8385    }
8386  }
8387  _onProgressiveDone() {
8388    this._fullRequestReader?.progressiveDone();
8389    this._progressiveDone = true;
8390  }
8391  _removeRangeReader(reader) {
8392    const i = this._rangeReaders.indexOf(reader);
8393    if (i >= 0) {
8394      this._rangeReaders.splice(i, 1);
8395    }
8396  }
8397  getFullReader() {
8398    (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
8399    const queuedChunks = this._queuedChunks;
8400    this._queuedChunks = null;
8401    return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
8402  }
8403  getRangeReader(begin, end) {
8404    if (end <= this._progressiveDataLength) {
8405      return null;
8406    }
8407    const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
8408    this._pdfDataRangeTransport.requestDataRange(begin, end);
8409    this._rangeReaders.push(reader);
8410    return reader;
8411  }
8412  cancelAllRequests(reason) {
8413    this._fullRequestReader?.cancel(reason);
8414    for (const reader of this._rangeReaders.slice(0)) {
8415      reader.cancel(reason);
8416    }
8417    this._pdfDataRangeTransport.abort();
8418  }
8419}
8420exports.PDFDataTransportStream = PDFDataTransportStream;
8421class PDFDataTransportStreamReader {
8422  constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
8423    this._stream = stream;
8424    this._done = progressiveDone || false;
8425    this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
8426    this._queuedChunks = queuedChunks || [];
8427    this._loaded = 0;
8428    for (const chunk of this._queuedChunks) {
8429      this._loaded += chunk.byteLength;
8430    }
8431    this._requests = [];
8432    this._headersReady = Promise.resolve();
8433    stream._fullRequestReader = this;
8434    this.onProgress = null;
8435  }
8436  _enqueue(chunk) {
8437    if (this._done) {
8438      return;
8439    }
8440    if (this._requests.length > 0) {
8441      const requestCapability = this._requests.shift();
8442      requestCapability.resolve({
8443        value: chunk,
8444        done: false
8445      });
8446    } else {
8447      this._queuedChunks.push(chunk);
8448    }
8449    this._loaded += chunk.byteLength;
8450  }
8451  get headersReady() {
8452    return this._headersReady;
8453  }
8454  get filename() {
8455    return this._filename;
8456  }
8457  get isRangeSupported() {
8458    return this._stream._isRangeSupported;
8459  }
8460  get isStreamingSupported() {
8461    return this._stream._isStreamingSupported;
8462  }
8463  get contentLength() {
8464    return this._stream._contentLength;
8465  }
8466  async read() {
8467    if (this._queuedChunks.length > 0) {
8468      const chunk = this._queuedChunks.shift();
8469      return {
8470        value: chunk,
8471        done: false
8472      };
8473    }
8474    if (this._done) {
8475      return {
8476        value: undefined,
8477        done: true
8478      };
8479    }
8480    const requestCapability = (0, _util.createPromiseCapability)();
8481    this._requests.push(requestCapability);
8482    return requestCapability.promise;
8483  }
8484  cancel(reason) {
8485    this._done = true;
8486    for (const requestCapability of this._requests) {
8487      requestCapability.resolve({
8488        value: undefined,
8489        done: true
8490      });
8491    }
8492    this._requests.length = 0;
8493  }
8494  progressiveDone() {
8495    if (this._done) {
8496      return;
8497    }
8498    this._done = true;
8499  }
8500}
8501class PDFDataTransportStreamRangeReader {
8502  constructor(stream, begin, end) {
8503    this._stream = stream;
8504    this._begin = begin;
8505    this._end = end;
8506    this._queuedChunk = null;
8507    this._requests = [];
8508    this._done = false;
8509    this.onProgress = null;
8510  }
8511  _enqueue(chunk) {
8512    if (this._done) {
8513      return;
8514    }
8515    if (this._requests.length === 0) {
8516      this._queuedChunk = chunk;
8517    } else {
8518      const requestsCapability = this._requests.shift();
8519      requestsCapability.resolve({
8520        value: chunk,
8521        done: false
8522      });
8523      for (const requestCapability of this._requests) {
8524        requestCapability.resolve({
8525          value: undefined,
8526          done: true
8527        });
8528      }
8529      this._requests.length = 0;
8530    }
8531    this._done = true;
8532    this._stream._removeRangeReader(this);
8533  }
8534  get isStreamingSupported() {
8535    return false;
8536  }
8537  async read() {
8538    if (this._queuedChunk) {
8539      const chunk = this._queuedChunk;
8540      this._queuedChunk = null;
8541      return {
8542        value: chunk,
8543        done: false
8544      };
8545    }
8546    if (this._done) {
8547      return {
8548        value: undefined,
8549        done: true
8550      };
8551    }
8552    const requestCapability = (0, _util.createPromiseCapability)();
8553    this._requests.push(requestCapability);
8554    return requestCapability.promise;
8555  }
8556  cancel(reason) {
8557    this._done = true;
8558    for (const requestCapability of this._requests) {
8559      requestCapability.resolve({
8560        value: undefined,
8561        done: true
8562      });
8563    }
8564    this._requests.length = 0;
8565    this._stream._removeRangeReader(this);
8566  }
8567}
8568
8569/***/ }),
8570/* 19 */
8571/***/ ((__unused_webpack_module, exports) => {
8572
8573
8574
8575Object.defineProperty(exports, "__esModule", ({
8576  value: true
8577}));
8578exports.XfaText = void 0;
8579class XfaText {
8580  static textContent(xfa) {
8581    const items = [];
8582    const output = {
8583      items,
8584      styles: Object.create(null)
8585    };
8586    function walk(node) {
8587      if (!node) {
8588        return;
8589      }
8590      let str = null;
8591      const name = node.name;
8592      if (name === "#text") {
8593        str = node.value;
8594      } else if (!XfaText.shouldBuildText(name)) {
8595        return;
8596      } else if (node?.attributes?.textContent) {
8597        str = node.attributes.textContent;
8598      } else if (node.value) {
8599        str = node.value;
8600      }
8601      if (str !== null) {
8602        items.push({
8603          str
8604        });
8605      }
8606      if (!node.children) {
8607        return;
8608      }
8609      for (const child of node.children) {
8610        walk(child);
8611      }
8612    }
8613    walk(xfa);
8614    return output;
8615  }
8616  static shouldBuildText(name) {
8617    return !(name === "textarea" || name === "input" || name === "option" || name === "select");
8618  }
8619}
8620exports.XfaText = XfaText;
8621
8622/***/ }),
8623/* 20 */
8624/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8625
8626
8627
8628Object.defineProperty(exports, "__esModule", ({
8629  value: true
8630}));
8631exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
8632var _base_factory = __w_pdfjs_require__(7);
8633;
8634const fetchData = function (url) {
8635  return new Promise((resolve, reject) => {
8636    const fs = require("fs");
8637    fs.readFile(url, (error, data) => {
8638      if (error || !data) {
8639        reject(new Error(error));
8640        return;
8641      }
8642      resolve(new Uint8Array(data));
8643    });
8644  });
8645};
8646class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
8647  _createCanvas(width, height) {
8648    const Canvas = require("canvas");
8649    return Canvas.createCanvas(width, height);
8650  }
8651}
8652exports.NodeCanvasFactory = NodeCanvasFactory;
8653class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
8654  _fetchData(url, compressionType) {
8655    return fetchData(url).then(data => {
8656      return {
8657        cMapData: data,
8658        compressionType
8659      };
8660    });
8661  }
8662}
8663exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
8664class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
8665  _fetchData(url) {
8666    return fetchData(url);
8667  }
8668}
8669exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
8670
8671/***/ }),
8672/* 21 */
8673/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8674
8675
8676
8677Object.defineProperty(exports, "__esModule", ({
8678  value: true
8679}));
8680exports.PDFNodeStream = void 0;
8681var _util = __w_pdfjs_require__(1);
8682var _network_utils = __w_pdfjs_require__(22);
8683;
8684const fs = require("fs");
8685const http = require("http");
8686const https = require("https");
8687const url = require("url");
8688const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
8689function parseUrl(sourceUrl) {
8690  const parsedUrl = url.parse(sourceUrl);
8691  if (parsedUrl.protocol === "file:" || parsedUrl.host) {
8692    return parsedUrl;
8693  }
8694  if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
8695    return url.parse(`file:///${sourceUrl}`);
8696  }
8697  if (!parsedUrl.host) {
8698    parsedUrl.protocol = "file:";
8699  }
8700  return parsedUrl;
8701}
8702class PDFNodeStream {
8703  constructor(source) {
8704    this.source = source;
8705    this.url = parseUrl(source.url);
8706    this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
8707    this.isFsUrl = this.url.protocol === "file:";
8708    this.httpHeaders = this.isHttp && source.httpHeaders || {};
8709    this._fullRequestReader = null;
8710    this._rangeRequestReaders = [];
8711  }
8712  get _progressiveDataLength() {
8713    return this._fullRequestReader?._loaded ?? 0;
8714  }
8715  getFullReader() {
8716    (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
8717    this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
8718    return this._fullRequestReader;
8719  }
8720  getRangeReader(start, end) {
8721    if (end <= this._progressiveDataLength) {
8722      return null;
8723    }
8724    const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
8725    this._rangeRequestReaders.push(rangeReader);
8726    return rangeReader;
8727  }
8728  cancelAllRequests(reason) {
8729    this._fullRequestReader?.cancel(reason);
8730    for (const reader of this._rangeRequestReaders.slice(0)) {
8731      reader.cancel(reason);
8732    }
8733  }
8734}
8735exports.PDFNodeStream = PDFNodeStream;
8736class BaseFullReader {
8737  constructor(stream) {
8738    this._url = stream.url;
8739    this._done = false;
8740    this._storedError = null;
8741    this.onProgress = null;
8742    const source = stream.source;
8743    this._contentLength = source.length;
8744    this._loaded = 0;
8745    this._filename = null;
8746    this._disableRange = source.disableRange || false;
8747    this._rangeChunkSize = source.rangeChunkSize;
8748    if (!this._rangeChunkSize && !this._disableRange) {
8749      this._disableRange = true;
8750    }
8751    this._isStreamingSupported = !source.disableStream;
8752    this._isRangeSupported = !source.disableRange;
8753    this._readableStream = null;
8754    this._readCapability = (0, _util.createPromiseCapability)();
8755    this._headersCapability = (0, _util.createPromiseCapability)();
8756  }
8757  get headersReady() {
8758    return this._headersCapability.promise;
8759  }
8760  get filename() {
8761    return this._filename;
8762  }
8763  get contentLength() {
8764    return this._contentLength;
8765  }
8766  get isRangeSupported() {
8767    return this._isRangeSupported;
8768  }
8769  get isStreamingSupported() {
8770    return this._isStreamingSupported;
8771  }
8772  async read() {
8773    await this._readCapability.promise;
8774    if (this._done) {
8775      return {
8776        value: undefined,
8777        done: true
8778      };
8779    }
8780    if (this._storedError) {
8781      throw this._storedError;
8782    }
8783    const chunk = this._readableStream.read();
8784    if (chunk === null) {
8785      this._readCapability = (0, _util.createPromiseCapability)();
8786      return this.read();
8787    }
8788    this._loaded += chunk.length;
8789    this.onProgress?.({
8790      loaded: this._loaded,
8791      total: this._contentLength
8792    });
8793    const buffer = new Uint8Array(chunk).buffer;
8794    return {
8795      value: buffer,
8796      done: false
8797    };
8798  }
8799  cancel(reason) {
8800    if (!this._readableStream) {
8801      this._error(reason);
8802      return;
8803    }
8804    this._readableStream.destroy(reason);
8805  }
8806  _error(reason) {
8807    this._storedError = reason;
8808    this._readCapability.resolve();
8809  }
8810  _setReadableStream(readableStream) {
8811    this._readableStream = readableStream;
8812    readableStream.on("readable", () => {
8813      this._readCapability.resolve();
8814    });
8815    readableStream.on("end", () => {
8816      readableStream.destroy();
8817      this._done = true;
8818      this._readCapability.resolve();
8819    });
8820    readableStream.on("error", reason => {
8821      this._error(reason);
8822    });
8823    if (!this._isStreamingSupported && this._isRangeSupported) {
8824      this._error(new _util.AbortException("streaming is disabled"));
8825    }
8826    if (this._storedError) {
8827      this._readableStream.destroy(this._storedError);
8828    }
8829  }
8830}
8831class BaseRangeReader {
8832  constructor(stream) {
8833    this._url = stream.url;
8834    this._done = false;
8835    this._storedError = null;
8836    this.onProgress = null;
8837    this._loaded = 0;
8838    this._readableStream = null;
8839    this._readCapability = (0, _util.createPromiseCapability)();
8840    const source = stream.source;
8841    this._isStreamingSupported = !source.disableStream;
8842  }
8843  get isStreamingSupported() {
8844    return this._isStreamingSupported;
8845  }
8846  async read() {
8847    await this._readCapability.promise;
8848    if (this._done) {
8849      return {
8850        value: undefined,
8851        done: true
8852      };
8853    }
8854    if (this._storedError) {
8855      throw this._storedError;
8856    }
8857    const chunk = this._readableStream.read();
8858    if (chunk === null) {
8859      this._readCapability = (0, _util.createPromiseCapability)();
8860      return this.read();
8861    }
8862    this._loaded += chunk.length;
8863    this.onProgress?.({
8864      loaded: this._loaded
8865    });
8866    const buffer = new Uint8Array(chunk).buffer;
8867    return {
8868      value: buffer,
8869      done: false
8870    };
8871  }
8872  cancel(reason) {
8873    if (!this._readableStream) {
8874      this._error(reason);
8875      return;
8876    }
8877    this._readableStream.destroy(reason);
8878  }
8879  _error(reason) {
8880    this._storedError = reason;
8881    this._readCapability.resolve();
8882  }
8883  _setReadableStream(readableStream) {
8884    this._readableStream = readableStream;
8885    readableStream.on("readable", () => {
8886      this._readCapability.resolve();
8887    });
8888    readableStream.on("end", () => {
8889      readableStream.destroy();
8890      this._done = true;
8891      this._readCapability.resolve();
8892    });
8893    readableStream.on("error", reason => {
8894      this._error(reason);
8895    });
8896    if (this._storedError) {
8897      this._readableStream.destroy(this._storedError);
8898    }
8899  }
8900}
8901function createRequestOptions(parsedUrl, headers) {
8902  return {
8903    protocol: parsedUrl.protocol,
8904    auth: parsedUrl.auth,
8905    host: parsedUrl.hostname,
8906    port: parsedUrl.port,
8907    path: parsedUrl.path,
8908    method: "GET",
8909    headers
8910  };
8911}
8912class PDFNodeStreamFullReader extends BaseFullReader {
8913  constructor(stream) {
8914    super(stream);
8915    const handleResponse = response => {
8916      if (response.statusCode === 404) {
8917        const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
8918        this._storedError = error;
8919        this._headersCapability.reject(error);
8920        return;
8921      }
8922      this._headersCapability.resolve();
8923      this._setReadableStream(response);
8924      const getResponseHeader = name => {
8925        return this._readableStream.headers[name.toLowerCase()];
8926      };
8927      const {
8928        allowRangeRequests,
8929        suggestedLength
8930      } = (0, _network_utils.validateRangeRequestCapabilities)({
8931        getResponseHeader,
8932        isHttp: stream.isHttp,
8933        rangeChunkSize: this._rangeChunkSize,
8934        disableRange: this._disableRange
8935      });
8936      this._isRangeSupported = allowRangeRequests;
8937      this._contentLength = suggestedLength || this._contentLength;
8938      this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
8939    };
8940    this._request = null;
8941    if (this._url.protocol === "http:") {
8942      this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
8943    } else {
8944      this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
8945    }
8946    this._request.on("error", reason => {
8947      this._storedError = reason;
8948      this._headersCapability.reject(reason);
8949    });
8950    this._request.end();
8951  }
8952}
8953class PDFNodeStreamRangeReader extends BaseRangeReader {
8954  constructor(stream, start, end) {
8955    super(stream);
8956    this._httpHeaders = {};
8957    for (const property in stream.httpHeaders) {
8958      const value = stream.httpHeaders[property];
8959      if (value === undefined) {
8960        continue;
8961      }
8962      this._httpHeaders[property] = value;
8963    }
8964    this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
8965    const handleResponse = response => {
8966      if (response.statusCode === 404) {
8967        const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
8968        this._storedError = error;
8969        return;
8970      }
8971      this._setReadableStream(response);
8972    };
8973    this._request = null;
8974    if (this._url.protocol === "http:") {
8975      this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
8976    } else {
8977      this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
8978    }
8979    this._request.on("error", reason => {
8980      this._storedError = reason;
8981    });
8982    this._request.end();
8983  }
8984}
8985class PDFNodeStreamFsFullReader extends BaseFullReader {
8986  constructor(stream) {
8987    super(stream);
8988    let path = decodeURIComponent(this._url.path);
8989    if (fileUriRegex.test(this._url.href)) {
8990      path = path.replace(/^\//, "");
8991    }
8992    fs.lstat(path, (error, stat) => {
8993      if (error) {
8994        if (error.code === "ENOENT") {
8995          error = new _util.MissingPDFException(`Missing PDF "${path}".`);
8996        }
8997        this._storedError = error;
8998        this._headersCapability.reject(error);
8999        return;
9000      }
9001      this._contentLength = stat.size;
9002      this._setReadableStream(fs.createReadStream(path));
9003      this._headersCapability.resolve();
9004    });
9005  }
9006}
9007class PDFNodeStreamFsRangeReader extends BaseRangeReader {
9008  constructor(stream, start, end) {
9009    super(stream);
9010    let path = decodeURIComponent(this._url.path);
9011    if (fileUriRegex.test(this._url.href)) {
9012      path = path.replace(/^\//, "");
9013    }
9014    this._setReadableStream(fs.createReadStream(path, {
9015      start,
9016      end: end - 1
9017    }));
9018  }
9019}
9020
9021/***/ }),
9022/* 22 */
9023/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9024
9025
9026
9027Object.defineProperty(exports, "__esModule", ({
9028  value: true
9029}));
9030exports.createResponseStatusError = createResponseStatusError;
9031exports.extractFilenameFromHeader = extractFilenameFromHeader;
9032exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
9033exports.validateResponseStatus = validateResponseStatus;
9034var _util = __w_pdfjs_require__(1);
9035var _content_disposition = __w_pdfjs_require__(23);
9036var _display_utils = __w_pdfjs_require__(6);
9037function validateRangeRequestCapabilities({
9038  getResponseHeader,
9039  isHttp,
9040  rangeChunkSize,
9041  disableRange
9042}) {
9043  const returnValues = {
9044    allowRangeRequests: false,
9045    suggestedLength: undefined
9046  };
9047  const length = parseInt(getResponseHeader("Content-Length"), 10);
9048  if (!Number.isInteger(length)) {
9049    return returnValues;
9050  }
9051  returnValues.suggestedLength = length;
9052  if (length <= 2 * rangeChunkSize) {
9053    return returnValues;
9054  }
9055  if (disableRange || !isHttp) {
9056    return returnValues;
9057  }
9058  if (getResponseHeader("Accept-Ranges") !== "bytes") {
9059    return returnValues;
9060  }
9061  const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
9062  if (contentEncoding !== "identity") {
9063    return returnValues;
9064  }
9065  returnValues.allowRangeRequests = true;
9066  return returnValues;
9067}
9068function extractFilenameFromHeader(getResponseHeader) {
9069  const contentDisposition = getResponseHeader("Content-Disposition");
9070  if (contentDisposition) {
9071    let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
9072    if (filename.includes("%")) {
9073      try {
9074        filename = decodeURIComponent(filename);
9075      } catch (ex) {}
9076    }
9077    if ((0, _display_utils.isPdfFile)(filename)) {
9078      return filename;
9079    }
9080  }
9081  return null;
9082}
9083function createResponseStatusError(status, url) {
9084  if (status === 404 || status === 0 && url.startsWith("file:")) {
9085    return new _util.MissingPDFException('Missing PDF "' + url + '".');
9086  }
9087  return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
9088}
9089function validateResponseStatus(status) {
9090  return status === 200 || status === 206;
9091}
9092
9093/***/ }),
9094/* 23 */
9095/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9096
9097
9098
9099Object.defineProperty(exports, "__esModule", ({
9100  value: true
9101}));
9102exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
9103var _util = __w_pdfjs_require__(1);
9104function getFilenameFromContentDispositionHeader(contentDisposition) {
9105  let needsEncodingFixup = true;
9106  let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
9107  if (tmp) {
9108    tmp = tmp[1];
9109    let filename = rfc2616unquote(tmp);
9110    filename = unescape(filename);
9111    filename = rfc5987decode(filename);
9112    filename = rfc2047decode(filename);
9113    return fixupEncoding(filename);
9114  }
9115  tmp = rfc2231getparam(contentDisposition);
9116  if (tmp) {
9117    const filename = rfc2047decode(tmp);
9118    return fixupEncoding(filename);
9119  }
9120  tmp = toParamRegExp("filename", "i").exec(contentDisposition);
9121  if (tmp) {
9122    tmp = tmp[1];
9123    let filename = rfc2616unquote(tmp);
9124    filename = rfc2047decode(filename);
9125    return fixupEncoding(filename);
9126  }
9127  function toParamRegExp(attributePattern, flags) {
9128    return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
9129  }
9130  function textdecode(encoding, value) {
9131    if (encoding) {
9132      if (!/^[\x00-\xFF]+$/.test(value)) {
9133        return value;
9134      }
9135      try {
9136        const decoder = new TextDecoder(encoding, {
9137          fatal: true
9138        });
9139        const buffer = (0, _util.stringToBytes)(value);
9140        value = decoder.decode(buffer);
9141        needsEncodingFixup = false;
9142      } catch (e) {}
9143    }
9144    return value;
9145  }
9146  function fixupEncoding(value) {
9147    if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
9148      value = textdecode("utf-8", value);
9149      if (needsEncodingFixup) {
9150        value = textdecode("iso-8859-1", value);
9151      }
9152    }
9153    return value;
9154  }
9155  function rfc2231getparam(contentDispositionStr) {
9156    const matches = [];
9157    let match;
9158    const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
9159    while ((match = iter.exec(contentDispositionStr)) !== null) {
9160      let [, n, quot, part] = match;
9161      n = parseInt(n, 10);
9162      if (n in matches) {
9163        if (n === 0) {
9164          break;
9165        }
9166        continue;
9167      }
9168      matches[n] = [quot, part];
9169    }
9170    const parts = [];
9171    for (let n = 0; n < matches.length; ++n) {
9172      if (!(n in matches)) {
9173        break;
9174      }
9175      let [quot, part] = matches[n];
9176      part = rfc2616unquote(part);
9177      if (quot) {
9178        part = unescape(part);
9179        if (n === 0) {
9180          part = rfc5987decode(part);
9181        }
9182      }
9183      parts.push(part);
9184    }
9185    return parts.join("");
9186  }
9187  function rfc2616unquote(value) {
9188    if (value.startsWith('"')) {
9189      const parts = value.slice(1).split('\\"');
9190      for (let i = 0; i < parts.length; ++i) {
9191        const quotindex = parts[i].indexOf('"');
9192        if (quotindex !== -1) {
9193          parts[i] = parts[i].slice(0, quotindex);
9194          parts.length = i + 1;
9195        }
9196        parts[i] = parts[i].replace(/\\(.)/g, "$1");
9197      }
9198      value = parts.join('"');
9199    }
9200    return value;
9201  }
9202  function rfc5987decode(extvalue) {
9203    const encodingend = extvalue.indexOf("'");
9204    if (encodingend === -1) {
9205      return extvalue;
9206    }
9207    const encoding = extvalue.slice(0, encodingend);
9208    const langvalue = extvalue.slice(encodingend + 1);
9209    const value = langvalue.replace(/^[^']*'/, "");
9210    return textdecode(encoding, value);
9211  }
9212  function rfc2047decode(value) {
9213    if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
9214      return value;
9215    }
9216    return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
9217      if (encoding === "q" || encoding === "Q") {
9218        text = text.replace(/_/g, " ");
9219        text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
9220          return String.fromCharCode(parseInt(hex, 16));
9221        });
9222        return textdecode(charset, text);
9223      }
9224      try {
9225        text = atob(text);
9226      } catch (e) {}
9227      return textdecode(charset, text);
9228    });
9229  }
9230  return "";
9231}
9232
9233/***/ }),
9234/* 24 */
9235/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9236
9237
9238
9239Object.defineProperty(exports, "__esModule", ({
9240  value: true
9241}));
9242exports.PDFNetworkStream = void 0;
9243var _util = __w_pdfjs_require__(1);
9244var _network_utils = __w_pdfjs_require__(22);
9245;
9246const OK_RESPONSE = 200;
9247const PARTIAL_CONTENT_RESPONSE = 206;
9248function getArrayBuffer(xhr) {
9249  const data = xhr.response;
9250  if (typeof data !== "string") {
9251    return data;
9252  }
9253  return (0, _util.stringToBytes)(data).buffer;
9254}
9255class NetworkManager {
9256  constructor(url, args = {}) {
9257    this.url = url;
9258    this.isHttp = /^https?:/i.test(url);
9259    this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
9260    this.withCredentials = args.withCredentials || false;
9261    this.getXhr = args.getXhr || function NetworkManager_getXhr() {
9262      return new XMLHttpRequest();
9263    };
9264    this.currXhrId = 0;
9265    this.pendingRequests = Object.create(null);
9266  }
9267  requestRange(begin, end, listeners) {
9268    const args = {
9269      begin,
9270      end
9271    };
9272    for (const prop in listeners) {
9273      args[prop] = listeners[prop];
9274    }
9275    return this.request(args);
9276  }
9277  requestFull(listeners) {
9278    return this.request(listeners);
9279  }
9280  request(args) {
9281    const xhr = this.getXhr();
9282    const xhrId = this.currXhrId++;
9283    const pendingRequest = this.pendingRequests[xhrId] = {
9284      xhr
9285    };
9286    xhr.open("GET", this.url);
9287    xhr.withCredentials = this.withCredentials;
9288    for (const property in this.httpHeaders) {
9289      const value = this.httpHeaders[property];
9290      if (value === undefined) {
9291        continue;
9292      }
9293      xhr.setRequestHeader(property, value);
9294    }
9295    if (this.isHttp && "begin" in args && "end" in args) {
9296      xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
9297      pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
9298    } else {
9299      pendingRequest.expectedStatus = OK_RESPONSE;
9300    }
9301    xhr.responseType = "arraybuffer";
9302    if (args.onError) {
9303      xhr.onerror = function (evt) {
9304        args.onError(xhr.status);
9305      };
9306    }
9307    xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
9308    xhr.onprogress = this.onProgress.bind(this, xhrId);
9309    pendingRequest.onHeadersReceived = args.onHeadersReceived;
9310    pendingRequest.onDone = args.onDone;
9311    pendingRequest.onError = args.onError;
9312    pendingRequest.onProgress = args.onProgress;
9313    xhr.send(null);
9314    return xhrId;
9315  }
9316  onProgress(xhrId, evt) {
9317    const pendingRequest = this.pendingRequests[xhrId];
9318    if (!pendingRequest) {
9319      return;
9320    }
9321    pendingRequest.onProgress?.(evt);
9322  }
9323  onStateChange(xhrId, evt) {
9324    const pendingRequest = this.pendingRequests[xhrId];
9325    if (!pendingRequest) {
9326      return;
9327    }
9328    const xhr = pendingRequest.xhr;
9329    if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
9330      pendingRequest.onHeadersReceived();
9331      delete pendingRequest.onHeadersReceived;
9332    }
9333    if (xhr.readyState !== 4) {
9334      return;
9335    }
9336    if (!(xhrId in this.pendingRequests)) {
9337      return;
9338    }
9339    delete this.pendingRequests[xhrId];
9340    if (xhr.status === 0 && this.isHttp) {
9341      pendingRequest.onError?.(xhr.status);
9342      return;
9343    }
9344    const xhrStatus = xhr.status || OK_RESPONSE;
9345    const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
9346    if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
9347      pendingRequest.onError?.(xhr.status);
9348      return;
9349    }
9350    const chunk = getArrayBuffer(xhr);
9351    if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
9352      const rangeHeader = xhr.getResponseHeader("Content-Range");
9353      const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
9354      pendingRequest.onDone({
9355        begin: parseInt(matches[1], 10),
9356        chunk
9357      });
9358    } else if (chunk) {
9359      pendingRequest.onDone({
9360        begin: 0,
9361        chunk
9362      });
9363    } else {
9364      pendingRequest.onError?.(xhr.status);
9365    }
9366  }
9367  getRequestXhr(xhrId) {
9368    return this.pendingRequests[xhrId].xhr;
9369  }
9370  isPendingRequest(xhrId) {
9371    return xhrId in this.pendingRequests;
9372  }
9373  abortRequest(xhrId) {
9374    const xhr = this.pendingRequests[xhrId].xhr;
9375    delete this.pendingRequests[xhrId];
9376    xhr.abort();
9377  }
9378}
9379class PDFNetworkStream {
9380  constructor(source) {
9381    this._source = source;
9382    this._manager = new NetworkManager(source.url, {
9383      httpHeaders: source.httpHeaders,
9384      withCredentials: source.withCredentials
9385    });
9386    this._rangeChunkSize = source.rangeChunkSize;
9387    this._fullRequestReader = null;
9388    this._rangeRequestReaders = [];
9389  }
9390  _onRangeRequestReaderClosed(reader) {
9391    const i = this._rangeRequestReaders.indexOf(reader);
9392    if (i >= 0) {
9393      this._rangeRequestReaders.splice(i, 1);
9394    }
9395  }
9396  getFullReader() {
9397    (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
9398    this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
9399    return this._fullRequestReader;
9400  }
9401  getRangeReader(begin, end) {
9402    const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
9403    reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
9404    this._rangeRequestReaders.push(reader);
9405    return reader;
9406  }
9407  cancelAllRequests(reason) {
9408    this._fullRequestReader?.cancel(reason);
9409    for (const reader of this._rangeRequestReaders.slice(0)) {
9410      reader.cancel(reason);
9411    }
9412  }
9413}
9414exports.PDFNetworkStream = PDFNetworkStream;
9415class PDFNetworkStreamFullRequestReader {
9416  constructor(manager, source) {
9417    this._manager = manager;
9418    const args = {
9419      onHeadersReceived: this._onHeadersReceived.bind(this),
9420      onDone: this._onDone.bind(this),
9421      onError: this._onError.bind(this),
9422      onProgress: this._onProgress.bind(this)
9423    };
9424    this._url = source.url;
9425    this._fullRequestId = manager.requestFull(args);
9426    this._headersReceivedCapability = (0, _util.createPromiseCapability)();
9427    this._disableRange = source.disableRange || false;
9428    this._contentLength = source.length;
9429    this._rangeChunkSize = source.rangeChunkSize;
9430    if (!this._rangeChunkSize && !this._disableRange) {
9431      this._disableRange = true;
9432    }
9433    this._isStreamingSupported = false;
9434    this._isRangeSupported = false;
9435    this._cachedChunks = [];
9436    this._requests = [];
9437    this._done = false;
9438    this._storedError = undefined;
9439    this._filename = null;
9440    this.onProgress = null;
9441  }
9442  _onHeadersReceived() {
9443    const fullRequestXhrId = this._fullRequestId;
9444    const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
9445    const getResponseHeader = name => {
9446      return fullRequestXhr.getResponseHeader(name);
9447    };
9448    const {
9449      allowRangeRequests,
9450      suggestedLength
9451    } = (0, _network_utils.validateRangeRequestCapabilities)({
9452      getResponseHeader,
9453      isHttp: this._manager.isHttp,
9454      rangeChunkSize: this._rangeChunkSize,
9455      disableRange: this._disableRange
9456    });
9457    if (allowRangeRequests) {
9458      this._isRangeSupported = true;
9459    }
9460    this._contentLength = suggestedLength || this._contentLength;
9461    this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
9462    if (this._isRangeSupported) {
9463      this._manager.abortRequest(fullRequestXhrId);
9464    }
9465    this._headersReceivedCapability.resolve();
9466  }
9467  _onDone(data) {
9468    if (data) {
9469      if (this._requests.length > 0) {
9470        const requestCapability = this._requests.shift();
9471        requestCapability.resolve({
9472          value: data.chunk,
9473          done: false
9474        });
9475      } else {
9476        this._cachedChunks.push(data.chunk);
9477      }
9478    }
9479    this._done = true;
9480    if (this._cachedChunks.length > 0) {
9481      return;
9482    }
9483    for (const requestCapability of this._requests) {
9484      requestCapability.resolve({
9485        value: undefined,
9486        done: true
9487      });
9488    }
9489    this._requests.length = 0;
9490  }
9491  _onError(status) {
9492    this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
9493    this._headersReceivedCapability.reject(this._storedError);
9494    for (const requestCapability of this._requests) {
9495      requestCapability.reject(this._storedError);
9496    }
9497    this._requests.length = 0;
9498    this._cachedChunks.length = 0;
9499  }
9500  _onProgress(evt) {
9501    this.onProgress?.({
9502      loaded: evt.loaded,
9503      total: evt.lengthComputable ? evt.total : this._contentLength
9504    });
9505  }
9506  get filename() {
9507    return this._filename;
9508  }
9509  get isRangeSupported() {
9510    return this._isRangeSupported;
9511  }
9512  get isStreamingSupported() {
9513    return this._isStreamingSupported;
9514  }
9515  get contentLength() {
9516    return this._contentLength;
9517  }
9518  get headersReady() {
9519    return this._headersReceivedCapability.promise;
9520  }
9521  async read() {
9522    if (this._storedError) {
9523      throw this._storedError;
9524    }
9525    if (this._cachedChunks.length > 0) {
9526      const chunk = this._cachedChunks.shift();
9527      return {
9528        value: chunk,
9529        done: false
9530      };
9531    }
9532    if (this._done) {
9533      return {
9534        value: undefined,
9535        done: true
9536      };
9537    }
9538    const requestCapability = (0, _util.createPromiseCapability)();
9539    this._requests.push(requestCapability);
9540    return requestCapability.promise;
9541  }
9542  cancel(reason) {
9543    this._done = true;
9544    this._headersReceivedCapability.reject(reason);
9545    for (const requestCapability of this._requests) {
9546      requestCapability.resolve({
9547        value: undefined,
9548        done: true
9549      });
9550    }
9551    this._requests.length = 0;
9552    if (this._manager.isPendingRequest(this._fullRequestId)) {
9553      this._manager.abortRequest(this._fullRequestId);
9554    }
9555    this._fullRequestReader = null;
9556  }
9557}
9558class PDFNetworkStreamRangeRequestReader {
9559  constructor(manager, begin, end) {
9560    this._manager = manager;
9561    const args = {
9562      onDone: this._onDone.bind(this),
9563      onError: this._onError.bind(this),
9564      onProgress: this._onProgress.bind(this)
9565    };
9566    this._url = manager.url;
9567    this._requestId = manager.requestRange(begin, end, args);
9568    this._requests = [];
9569    this._queuedChunk = null;
9570    this._done = false;
9571    this._storedError = undefined;
9572    this.onProgress = null;
9573    this.onClosed = null;
9574  }
9575  _close() {
9576    this.onClosed?.(this);
9577  }
9578  _onDone(data) {
9579    const chunk = data.chunk;
9580    if (this._requests.length > 0) {
9581      const requestCapability = this._requests.shift();
9582      requestCapability.resolve({
9583        value: chunk,
9584        done: false
9585      });
9586    } else {
9587      this._queuedChunk = chunk;
9588    }
9589    this._done = true;
9590    for (const requestCapability of this._requests) {
9591      requestCapability.resolve({
9592        value: undefined,
9593        done: true
9594      });
9595    }
9596    this._requests.length = 0;
9597    this._close();
9598  }
9599  _onError(status) {
9600    this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
9601    for (const requestCapability of this._requests) {
9602      requestCapability.reject(this._storedError);
9603    }
9604    this._requests.length = 0;
9605    this._queuedChunk = null;
9606  }
9607  _onProgress(evt) {
9608    if (!this.isStreamingSupported) {
9609      this.onProgress?.({
9610        loaded: evt.loaded
9611      });
9612    }
9613  }
9614  get isStreamingSupported() {
9615    return false;
9616  }
9617  async read() {
9618    if (this._storedError) {
9619      throw this._storedError;
9620    }
9621    if (this._queuedChunk !== null) {
9622      const chunk = this._queuedChunk;
9623      this._queuedChunk = null;
9624      return {
9625        value: chunk,
9626        done: false
9627      };
9628    }
9629    if (this._done) {
9630      return {
9631        value: undefined,
9632        done: true
9633      };
9634    }
9635    const requestCapability = (0, _util.createPromiseCapability)();
9636    this._requests.push(requestCapability);
9637    return requestCapability.promise;
9638  }
9639  cancel(reason) {
9640    this._done = true;
9641    for (const requestCapability of this._requests) {
9642      requestCapability.resolve({
9643        value: undefined,
9644        done: true
9645      });
9646    }
9647    this._requests.length = 0;
9648    if (this._manager.isPendingRequest(this._requestId)) {
9649      this._manager.abortRequest(this._requestId);
9650    }
9651    this._close();
9652  }
9653}
9654
9655/***/ }),
9656/* 25 */
9657/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9658
9659
9660
9661Object.defineProperty(exports, "__esModule", ({
9662  value: true
9663}));
9664exports.PDFFetchStream = void 0;
9665var _util = __w_pdfjs_require__(1);
9666var _network_utils = __w_pdfjs_require__(22);
9667;
9668function createFetchOptions(headers, withCredentials, abortController) {
9669  return {
9670    method: "GET",
9671    headers,
9672    signal: abortController.signal,
9673    mode: "cors",
9674    credentials: withCredentials ? "include" : "same-origin",
9675    redirect: "follow"
9676  };
9677}
9678function createHeaders(httpHeaders) {
9679  const headers = new Headers();
9680  for (const property in httpHeaders) {
9681    const value = httpHeaders[property];
9682    if (value === undefined) {
9683      continue;
9684    }
9685    headers.append(property, value);
9686  }
9687  return headers;
9688}
9689function getArrayBuffer(val) {
9690  if (val instanceof Uint8Array) {
9691    return val.buffer;
9692  }
9693  if (val instanceof ArrayBuffer) {
9694    return val;
9695  }
9696  (0, _util.warn)(`getArrayBuffer - unexpected data format: ${val}`);
9697  return new Uint8Array(val).buffer;
9698}
9699class PDFFetchStream {
9700  constructor(source) {
9701    this.source = source;
9702    this.isHttp = /^https?:/i.test(source.url);
9703    this.httpHeaders = this.isHttp && source.httpHeaders || {};
9704    this._fullRequestReader = null;
9705    this._rangeRequestReaders = [];
9706  }
9707  get _progressiveDataLength() {
9708    return this._fullRequestReader?._loaded ?? 0;
9709  }
9710  getFullReader() {
9711    (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
9712    this._fullRequestReader = new PDFFetchStreamReader(this);
9713    return this._fullRequestReader;
9714  }
9715  getRangeReader(begin, end) {
9716    if (end <= this._progressiveDataLength) {
9717      return null;
9718    }
9719    const reader = new PDFFetchStreamRangeReader(this, begin, end);
9720    this._rangeRequestReaders.push(reader);
9721    return reader;
9722  }
9723  cancelAllRequests(reason) {
9724    this._fullRequestReader?.cancel(reason);
9725    for (const reader of this._rangeRequestReaders.slice(0)) {
9726      reader.cancel(reason);
9727    }
9728  }
9729}
9730exports.PDFFetchStream = PDFFetchStream;
9731class PDFFetchStreamReader {
9732  constructor(stream) {
9733    this._stream = stream;
9734    this._reader = null;
9735    this._loaded = 0;
9736    this._filename = null;
9737    const source = stream.source;
9738    this._withCredentials = source.withCredentials || false;
9739    this._contentLength = source.length;
9740    this._headersCapability = (0, _util.createPromiseCapability)();
9741    this._disableRange = source.disableRange || false;
9742    this._rangeChunkSize = source.rangeChunkSize;
9743    if (!this._rangeChunkSize && !this._disableRange) {
9744      this._disableRange = true;
9745    }
9746    this._abortController = new AbortController();
9747    this._isStreamingSupported = !source.disableStream;
9748    this._isRangeSupported = !source.disableRange;
9749    this._headers = createHeaders(this._stream.httpHeaders);
9750    const url = source.url;
9751    fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
9752      if (!(0, _network_utils.validateResponseStatus)(response.status)) {
9753        throw (0, _network_utils.createResponseStatusError)(response.status, url);
9754      }
9755      this._reader = response.body.getReader();
9756      this._headersCapability.resolve();
9757      const getResponseHeader = name => {
9758        return response.headers.get(name);
9759      };
9760      const {
9761        allowRangeRequests,
9762        suggestedLength
9763      } = (0, _network_utils.validateRangeRequestCapabilities)({
9764        getResponseHeader,
9765        isHttp: this._stream.isHttp,
9766        rangeChunkSize: this._rangeChunkSize,
9767        disableRange: this._disableRange
9768      });
9769      this._isRangeSupported = allowRangeRequests;
9770      this._contentLength = suggestedLength || this._contentLength;
9771      this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
9772      if (!this._isStreamingSupported && this._isRangeSupported) {
9773        this.cancel(new _util.AbortException("Streaming is disabled."));
9774      }
9775    }).catch(this._headersCapability.reject);
9776    this.onProgress = null;
9777  }
9778  get headersReady() {
9779    return this._headersCapability.promise;
9780  }
9781  get filename() {
9782    return this._filename;
9783  }
9784  get contentLength() {
9785    return this._contentLength;
9786  }
9787  get isRangeSupported() {
9788    return this._isRangeSupported;
9789  }
9790  get isStreamingSupported() {
9791    return this._isStreamingSupported;
9792  }
9793  async read() {
9794    await this._headersCapability.promise;
9795    const {
9796      value,
9797      done
9798    } = await this._reader.read();
9799    if (done) {
9800      return {
9801        value,
9802        done
9803      };
9804    }
9805    this._loaded += value.byteLength;
9806    this.onProgress?.({
9807      loaded: this._loaded,
9808      total: this._contentLength
9809    });
9810    return {
9811      value: getArrayBuffer(value),
9812      done: false
9813    };
9814  }
9815  cancel(reason) {
9816    this._reader?.cancel(reason);
9817    this._abortController.abort();
9818  }
9819}
9820class PDFFetchStreamRangeReader {
9821  constructor(stream, begin, end) {
9822    this._stream = stream;
9823    this._reader = null;
9824    this._loaded = 0;
9825    const source = stream.source;
9826    this._withCredentials = source.withCredentials || false;
9827    this._readCapability = (0, _util.createPromiseCapability)();
9828    this._isStreamingSupported = !source.disableStream;
9829    this._abortController = new AbortController();
9830    this._headers = createHeaders(this._stream.httpHeaders);
9831    this._headers.append("Range", `bytes=${begin}-${end - 1}`);
9832    const url = source.url;
9833    fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
9834      if (!(0, _network_utils.validateResponseStatus)(response.status)) {
9835        throw (0, _network_utils.createResponseStatusError)(response.status, url);
9836      }
9837      this._readCapability.resolve();
9838      this._reader = response.body.getReader();
9839    }).catch(this._readCapability.reject);
9840    this.onProgress = null;
9841  }
9842  get isStreamingSupported() {
9843    return this._isStreamingSupported;
9844  }
9845  async read() {
9846    await this._readCapability.promise;
9847    const {
9848      value,
9849      done
9850    } = await this._reader.read();
9851    if (done) {
9852      return {
9853        value,
9854        done
9855      };
9856    }
9857    this._loaded += value.byteLength;
9858    this.onProgress?.({
9859      loaded: this._loaded
9860    });
9861    return {
9862      value: getArrayBuffer(value),
9863      done: false
9864    };
9865  }
9866  cancel(reason) {
9867    this._reader?.cancel(reason);
9868    this._abortController.abort();
9869  }
9870}
9871
9872/***/ }),
9873/* 26 */
9874/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9875
9876
9877
9878Object.defineProperty(exports, "__esModule", ({
9879  value: true
9880}));
9881exports.TextLayerRenderTask = void 0;
9882exports.renderTextLayer = renderTextLayer;
9883exports.updateTextLayer = updateTextLayer;
9884var _util = __w_pdfjs_require__(1);
9885var _display_utils = __w_pdfjs_require__(6);
9886const MAX_TEXT_DIVS_TO_RENDER = 100000;
9887const DEFAULT_FONT_SIZE = 30;
9888const DEFAULT_FONT_ASCENT = 0.8;
9889const ascentCache = new Map();
9890function getCtx(size, isOffscreenCanvasSupported) {
9891  let ctx;
9892  if (isOffscreenCanvasSupported && _util.FeatureTest.isOffscreenCanvasSupported) {
9893    ctx = new OffscreenCanvas(size, size).getContext("2d", {
9894      alpha: false
9895    });
9896  } else {
9897    const canvas = document.createElement("canvas");
9898    canvas.width = canvas.height = size;
9899    ctx = canvas.getContext("2d", {
9900      alpha: false
9901    });
9902  }
9903  return ctx;
9904}
9905function getAscent(fontFamily, isOffscreenCanvasSupported) {
9906  const cachedAscent = ascentCache.get(fontFamily);
9907  if (cachedAscent) {
9908    return cachedAscent;
9909  }
9910  const ctx = getCtx(DEFAULT_FONT_SIZE, isOffscreenCanvasSupported);
9911  ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
9912  const metrics = ctx.measureText("");
9913  let ascent = metrics.fontBoundingBoxAscent;
9914  let descent = Math.abs(metrics.fontBoundingBoxDescent);
9915  if (ascent) {
9916    const ratio = ascent / (ascent + descent);
9917    ascentCache.set(fontFamily, ratio);
9918    ctx.canvas.width = ctx.canvas.height = 0;
9919    return ratio;
9920  }
9921  ctx.strokeStyle = "red";
9922  ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
9923  ctx.strokeText("g", 0, 0);
9924  let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
9925  descent = 0;
9926  for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
9927    if (pixels[i] > 0) {
9928      descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
9929      break;
9930    }
9931  }
9932  ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
9933  ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
9934  pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
9935  ascent = 0;
9936  for (let i = 0, ii = pixels.length; i < ii; i += 4) {
9937    if (pixels[i] > 0) {
9938      ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
9939      break;
9940    }
9941  }
9942  ctx.canvas.width = ctx.canvas.height = 0;
9943  if (ascent) {
9944    const ratio = ascent / (ascent + descent);
9945    ascentCache.set(fontFamily, ratio);
9946    return ratio;
9947  }
9948  ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
9949  return DEFAULT_FONT_ASCENT;
9950}
9951function appendText(task, geom, styles) {
9952  const textDiv = document.createElement("span");
9953  const textDivProperties = {
9954    angle: 0,
9955    canvasWidth: 0,
9956    hasText: geom.str !== "",
9957    hasEOL: geom.hasEOL,
9958    fontSize: 0
9959  };
9960  task._textDivs.push(textDiv);
9961  const tx = _util.Util.transform(task._transform, geom.transform);
9962  let angle = Math.atan2(tx[1], tx[0]);
9963  const style = styles[geom.fontName];
9964  if (style.vertical) {
9965    angle += Math.PI / 2;
9966  }
9967  const fontHeight = Math.hypot(tx[2], tx[3]);
9968  const fontAscent = fontHeight * getAscent(style.fontFamily, task._isOffscreenCanvasSupported);
9969  let left, top;
9970  if (angle === 0) {
9971    left = tx[4];
9972    top = tx[5] - fontAscent;
9973  } else {
9974    left = tx[4] + fontAscent * Math.sin(angle);
9975    top = tx[5] - fontAscent * Math.cos(angle);
9976  }
9977  const scaleFactorStr = "calc(var(--scale-factor)*";
9978  const divStyle = textDiv.style;
9979  if (task._container === task._rootContainer) {
9980    divStyle.left = `${(100 * left / task._pageWidth).toFixed(2)}%`;
9981    divStyle.top = `${(100 * top / task._pageHeight).toFixed(2)}%`;
9982  } else {
9983    divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
9984    divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
9985  }
9986  divStyle.fontSize = `${scaleFactorStr}${fontHeight.toFixed(2)}px)`;
9987  divStyle.fontFamily = style.fontFamily;
9988  textDivProperties.fontSize = fontHeight;
9989  textDiv.setAttribute("role", "presentation");
9990  textDiv.textContent = geom.str;
9991  textDiv.dir = geom.dir;
9992  if (task._fontInspectorEnabled) {
9993    textDiv.dataset.fontName = geom.fontName;
9994  }
9995  if (angle !== 0) {
9996    textDivProperties.angle = angle * (180 / Math.PI);
9997  }
9998  let shouldScaleText = false;
9999  if (geom.str.length > 1) {
10000    shouldScaleText = true;
10001  } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
10002    const absScaleX = Math.abs(geom.transform[0]),
10003      absScaleY = Math.abs(geom.transform[3]);
10004    if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
10005      shouldScaleText = true;
10006    }
10007  }
10008  if (shouldScaleText) {
10009    textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
10010  }
10011  task._textDivProperties.set(textDiv, textDivProperties);
10012  if (task._isReadableStream) {
10013    task._layoutText(textDiv);
10014  }
10015}
10016function layout(params) {
10017  const {
10018    div,
10019    scale,
10020    properties,
10021    ctx,
10022    prevFontSize,
10023    prevFontFamily
10024  } = params;
10025  const {
10026    style
10027  } = div;
10028  let transform = "";
10029  if (properties.canvasWidth !== 0 && properties.hasText) {
10030    const {
10031      fontFamily
10032    } = style;
10033    const {
10034      canvasWidth,
10035      fontSize
10036    } = properties;
10037    if (prevFontSize !== fontSize || prevFontFamily !== fontFamily) {
10038      ctx.font = `${fontSize * scale}px ${fontFamily}`;
10039      params.prevFontSize = fontSize;
10040      params.prevFontFamily = fontFamily;
10041    }
10042    const {
10043      width
10044    } = ctx.measureText(div.textContent);
10045    if (width > 0) {
10046      transform = `scaleX(${canvasWidth * scale / width})`;
10047    }
10048  }
10049  if (properties.angle !== 0) {
10050    transform = `rotate(${properties.angle}deg) ${transform}`;
10051  }
10052  if (transform.length > 0) {
10053    style.transform = transform;
10054  }
10055}
10056function render(task) {
10057  if (task._canceled) {
10058    return;
10059  }
10060  const textDivs = task._textDivs;
10061  const capability = task._capability;
10062  const textDivsLength = textDivs.length;
10063  if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
10064    capability.resolve();
10065    return;
10066  }
10067  if (!task._isReadableStream) {
10068    for (const textDiv of textDivs) {
10069      task._layoutText(textDiv);
10070    }
10071  }
10072  capability.resolve();
10073}
10074class TextLayerRenderTask {
10075  constructor({
10076    textContentSource,
10077    container,
10078    viewport,
10079    textDivs,
10080    textDivProperties,
10081    textContentItemsStr,
10082    isOffscreenCanvasSupported
10083  }) {
10084    this._textContentSource = textContentSource;
10085    this._isReadableStream = textContentSource instanceof ReadableStream;
10086    this._container = this._rootContainer = container;
10087    this._textDivs = textDivs || [];
10088    this._textContentItemsStr = textContentItemsStr || [];
10089    this._isOffscreenCanvasSupported = isOffscreenCanvasSupported;
10090    this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
10091    this._reader = null;
10092    this._textDivProperties = textDivProperties || new WeakMap();
10093    this._canceled = false;
10094    this._capability = (0, _util.createPromiseCapability)();
10095    this._layoutTextParams = {
10096      prevFontSize: null,
10097      prevFontFamily: null,
10098      div: null,
10099      scale: viewport.scale * (globalThis.devicePixelRatio || 1),
10100      properties: null,
10101      ctx: getCtx(0, isOffscreenCanvasSupported)
10102    };
10103    const {
10104      pageWidth,
10105      pageHeight,
10106      pageX,
10107      pageY
10108    } = viewport.rawDims;
10109    this._transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
10110    this._pageWidth = pageWidth;
10111    this._pageHeight = pageHeight;
10112    (0, _display_utils.setLayerDimensions)(container, viewport);
10113    this._capability.promise.finally(() => {
10114      this._layoutTextParams = null;
10115    }).catch(() => {});
10116  }
10117  get promise() {
10118    return this._capability.promise;
10119  }
10120  cancel() {
10121    this._canceled = true;
10122    if (this._reader) {
10123      this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
10124      this._reader = null;
10125    }
10126    this._capability.reject(new _util.AbortException("TextLayer task cancelled."));
10127  }
10128  _processItems(items, styleCache) {
10129    for (const item of items) {
10130      if (item.str === undefined) {
10131        if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
10132          const parent = this._container;
10133          this._container = document.createElement("span");
10134          this._container.classList.add("markedContent");
10135          if (item.id !== null) {
10136            this._container.setAttribute("id", `${item.id}`);
10137          }
10138          parent.append(this._container);
10139        } else if (item.type === "endMarkedContent") {
10140          this._container = this._container.parentNode;
10141        }
10142        continue;
10143      }
10144      this._textContentItemsStr.push(item.str);
10145      appendText(this, item, styleCache);
10146    }
10147  }
10148  _layoutText(textDiv) {
10149    const textDivProperties = this._layoutTextParams.properties = this._textDivProperties.get(textDiv);
10150    this._layoutTextParams.div = textDiv;
10151    layout(this._layoutTextParams);
10152    if (textDivProperties.hasText) {
10153      this._container.append(textDiv);
10154    }
10155    if (textDivProperties.hasEOL) {
10156      const br = document.createElement("br");
10157      br.setAttribute("role", "presentation");
10158      this._container.append(br);
10159    }
10160  }
10161  _render() {
10162    const capability = (0, _util.createPromiseCapability)();
10163    let styleCache = Object.create(null);
10164    if (this._isReadableStream) {
10165      const pump = () => {
10166        this._reader.read().then(({
10167          value,
10168          done
10169        }) => {
10170          if (done) {
10171            capability.resolve();
10172            return;
10173          }
10174          Object.assign(styleCache, value.styles);
10175          this._processItems(value.items, styleCache);
10176          pump();
10177        }, capability.reject);
10178      };
10179      this._reader = this._textContentSource.getReader();
10180      pump();
10181    } else if (this._textContentSource) {
10182      const {
10183        items,
10184        styles
10185      } = this._textContentSource;
10186      this._processItems(items, styles);
10187      capability.resolve();
10188    } else {
10189      throw new Error('No "textContentSource" parameter specified.');
10190    }
10191    capability.promise.then(() => {
10192      styleCache = null;
10193      render(this);
10194    }, this._capability.reject);
10195  }
10196}
10197exports.TextLayerRenderTask = TextLayerRenderTask;
10198function renderTextLayer(params) {
10199  if (!params.textContentSource && (params.textContent || params.textContentStream)) {
10200    (0, _display_utils.deprecated)("The TextLayerRender `textContent`/`textContentStream` parameters " + "will be removed in the future, please use `textContentSource` instead.");
10201    params.textContentSource = params.textContent || params.textContentStream;
10202  }
10203  const task = new TextLayerRenderTask(params);
10204  task._render();
10205  return task;
10206}
10207function updateTextLayer({
10208  container,
10209  viewport,
10210  textDivs,
10211  textDivProperties,
10212  isOffscreenCanvasSupported,
10213  mustRotate = true,
10214  mustRescale = true
10215}) {
10216  if (mustRotate) {
10217    (0, _display_utils.setLayerDimensions)(container, {
10218      rotation: viewport.rotation
10219    });
10220  }
10221  if (mustRescale) {
10222    const ctx = getCtx(0, isOffscreenCanvasSupported);
10223    const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
10224    const params = {
10225      prevFontSize: null,
10226      prevFontFamily: null,
10227      div: null,
10228      scale,
10229      properties: null,
10230      ctx
10231    };
10232    for (const div of textDivs) {
10233      params.properties = textDivProperties.get(div);
10234      params.div = div;
10235      layout(params);
10236    }
10237  }
10238}
10239
10240/***/ }),
10241/* 27 */
10242/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
10243
10244
10245
10246Object.defineProperty(exports, "__esModule", ({
10247  value: true
10248}));
10249exports.AnnotationEditorLayer = void 0;
10250var _util = __w_pdfjs_require__(1);
10251var _tools = __w_pdfjs_require__(5);
10252var _freetext = __w_pdfjs_require__(28);
10253var _ink = __w_pdfjs_require__(29);
10254var _display_utils = __w_pdfjs_require__(6);
10255class AnnotationEditorLayer {
10256  #accessibilityManager;
10257  #allowClick = false;
10258  #boundPointerup = this.pointerup.bind(this);
10259  #boundPointerdown = this.pointerdown.bind(this);
10260  #editors = new Map();
10261  #hadPointerDown = false;
10262  #isCleaningUp = false;
10263  #uiManager;
10264  static _initialized = false;
10265  constructor(options) {
10266    if (!AnnotationEditorLayer._initialized) {
10267      AnnotationEditorLayer._initialized = true;
10268      _freetext.FreeTextEditor.initialize(options.l10n);
10269      _ink.InkEditor.initialize(options.l10n);
10270    }
10271    options.uiManager.registerEditorTypes([_freetext.FreeTextEditor, _ink.InkEditor]);
10272    this.#uiManager = options.uiManager;
10273    this.pageIndex = options.pageIndex;
10274    this.div = options.div;
10275    this.#accessibilityManager = options.accessibilityManager;
10276    this.#uiManager.addLayer(this);
10277  }
10278  get isEmpty() {
10279    return this.#editors.size === 0;
10280  }
10281  updateToolbar(mode) {
10282    this.#uiManager.updateToolbar(mode);
10283  }
10284  updateMode(mode = this.#uiManager.getMode()) {
10285    this.#cleanup();
10286    if (mode === _util.AnnotationEditorType.INK) {
10287      this.addInkEditorIfNeeded(false);
10288      this.disableClick();
10289    } else {
10290      this.enableClick();
10291    }
10292    this.#uiManager.unselectAll();
10293    if (mode !== _util.AnnotationEditorType.NONE) {
10294      this.div.classList.toggle("freeTextEditing", mode === _util.AnnotationEditorType.FREETEXT);
10295      this.div.classList.toggle("inkEditing", mode === _util.AnnotationEditorType.INK);
10296      this.div.hidden = false;
10297    }
10298  }
10299  addInkEditorIfNeeded(isCommitting) {
10300    if (!isCommitting && this.#uiManager.getMode() !== _util.AnnotationEditorType.INK) {
10301      return;
10302    }
10303    if (!isCommitting) {
10304      for (const editor of this.#editors.values()) {
10305        if (editor.isEmpty()) {
10306          editor.setInBackground();
10307          return;
10308        }
10309      }
10310    }
10311    const editor = this.#createAndAddNewEditor({
10312      offsetX: 0,
10313      offsetY: 0
10314    });
10315    editor.setInBackground();
10316  }
10317  setEditingState(isEditing) {
10318    this.#uiManager.setEditingState(isEditing);
10319  }
10320  addCommands(params) {
10321    this.#uiManager.addCommands(params);
10322  }
10323  enable() {
10324    this.div.style.pointerEvents = "auto";
10325    for (const editor of this.#editors.values()) {
10326      editor.enableEditing();
10327    }
10328  }
10329  disable() {
10330    this.div.style.pointerEvents = "none";
10331    for (const editor of this.#editors.values()) {
10332      editor.disableEditing();
10333    }
10334    this.#cleanup();
10335    if (this.isEmpty) {
10336      this.div.hidden = true;
10337    }
10338  }
10339  setActiveEditor(editor) {
10340    const currentActive = this.#uiManager.getActive();
10341    if (currentActive === editor) {
10342      return;
10343    }
10344    this.#uiManager.setActiveEditor(editor);
10345  }
10346  enableClick() {
10347    this.div.addEventListener("pointerdown", this.#boundPointerdown);
10348    this.div.addEventListener("pointerup", this.#boundPointerup);
10349  }
10350  disableClick() {
10351    this.div.removeEventListener("pointerdown", this.#boundPointerdown);
10352    this.div.removeEventListener("pointerup", this.#boundPointerup);
10353  }
10354  attach(editor) {
10355    this.#editors.set(editor.id, editor);
10356  }
10357  detach(editor) {
10358    this.#editors.delete(editor.id);
10359    this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
10360  }
10361  remove(editor) {
10362    this.#uiManager.removeEditor(editor);
10363    this.detach(editor);
10364    editor.div.style.display = "none";
10365    setTimeout(() => {
10366      editor.div.style.display = "";
10367      editor.div.remove();
10368      editor.isAttachedToDOM = false;
10369      if (document.activeElement === document.body) {
10370        this.#uiManager.focusMainContainer();
10371      }
10372    }, 0);
10373    if (!this.#isCleaningUp) {
10374      this.addInkEditorIfNeeded(false);
10375    }
10376  }
10377  #changeParent(editor) {
10378    if (editor.parent === this) {
10379      return;
10380    }
10381    this.attach(editor);
10382    editor.parent?.detach(editor);
10383    editor.setParent(this);
10384    if (editor.div && editor.isAttachedToDOM) {
10385      editor.div.remove();
10386      this.div.append(editor.div);
10387    }
10388  }
10389  add(editor) {
10390    this.#changeParent(editor);
10391    this.#uiManager.addEditor(editor);
10392    this.attach(editor);
10393    if (!editor.isAttachedToDOM) {
10394      const div = editor.render();
10395      this.div.append(div);
10396      editor.isAttachedToDOM = true;
10397    }
10398    this.moveEditorInDOM(editor);
10399    editor.onceAdded();
10400    this.#uiManager.addToAnnotationStorage(editor);
10401  }
10402  moveEditorInDOM(editor) {
10403    this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
10404  }
10405  addOrRebuild(editor) {
10406    if (editor.needsToBeRebuilt()) {
10407      editor.rebuild();
10408    } else {
10409      this.add(editor);
10410    }
10411  }
10412  addANewEditor(editor) {
10413    const cmd = () => {
10414      this.addOrRebuild(editor);
10415    };
10416    const undo = () => {
10417      editor.remove();
10418    };
10419    this.addCommands({
10420      cmd,
10421      undo,
10422      mustExec: true
10423    });
10424  }
10425  addUndoableEditor(editor) {
10426    const cmd = () => {
10427      this.addOrRebuild(editor);
10428    };
10429    const undo = () => {
10430      editor.remove();
10431    };
10432    this.addCommands({
10433      cmd,
10434      undo,
10435      mustExec: false
10436    });
10437  }
10438  getNextId() {
10439    return this.#uiManager.getId();
10440  }
10441  #createNewEditor(params) {
10442    switch (this.#uiManager.getMode()) {
10443      case _util.AnnotationEditorType.FREETEXT:
10444        return new _freetext.FreeTextEditor(params);
10445      case _util.AnnotationEditorType.INK:
10446        return new _ink.InkEditor(params);
10447    }
10448    return null;
10449  }
10450  deserialize(data) {
10451    switch (data.annotationType) {
10452      case _util.AnnotationEditorType.FREETEXT:
10453        return _freetext.FreeTextEditor.deserialize(data, this, this.#uiManager);
10454      case _util.AnnotationEditorType.INK:
10455        return _ink.InkEditor.deserialize(data, this, this.#uiManager);
10456    }
10457    return null;
10458  }
10459  #createAndAddNewEditor(event) {
10460    const id = this.getNextId();
10461    const editor = this.#createNewEditor({
10462      parent: this,
10463      id,
10464      x: event.offsetX,
10465      y: event.offsetY,
10466      uiManager: this.#uiManager
10467    });
10468    if (editor) {
10469      this.add(editor);
10470    }
10471    return editor;
10472  }
10473  setSelected(editor) {
10474    this.#uiManager.setSelected(editor);
10475  }
10476  toggleSelected(editor) {
10477    this.#uiManager.toggleSelected(editor);
10478  }
10479  isSelected(editor) {
10480    return this.#uiManager.isSelected(editor);
10481  }
10482  unselect(editor) {
10483    this.#uiManager.unselect(editor);
10484  }
10485  pointerup(event) {
10486    const {
10487      isMac
10488    } = _util.FeatureTest.platform;
10489    if (event.button !== 0 || event.ctrlKey && isMac) {
10490      return;
10491    }
10492    if (event.target !== this.div) {
10493      return;
10494    }
10495    if (!this.#hadPointerDown) {
10496      return;
10497    }
10498    this.#hadPointerDown = false;
10499    if (!this.#allowClick) {
10500      this.#allowClick = true;
10501      return;
10502    }
10503    this.#createAndAddNewEditor(event);
10504  }
10505  pointerdown(event) {
10506    const {
10507      isMac
10508    } = _util.FeatureTest.platform;
10509    if (event.button !== 0 || event.ctrlKey && isMac) {
10510      return;
10511    }
10512    if (event.target !== this.div) {
10513      return;
10514    }
10515    this.#hadPointerDown = true;
10516    const editor = this.#uiManager.getActive();
10517    this.#allowClick = !editor || editor.isEmpty();
10518  }
10519  drop(event) {
10520    const id = event.dataTransfer.getData("text/plain");
10521    const editor = this.#uiManager.getEditor(id);
10522    if (!editor) {
10523      return;
10524    }
10525    event.preventDefault();
10526    event.dataTransfer.dropEffect = "move";
10527    this.#changeParent(editor);
10528    const rect = this.div.getBoundingClientRect();
10529    const endX = event.clientX - rect.x;
10530    const endY = event.clientY - rect.y;
10531    editor.translate(endX - editor.startX, endY - editor.startY);
10532    this.moveEditorInDOM(editor);
10533    editor.div.focus();
10534  }
10535  dragover(event) {
10536    event.preventDefault();
10537  }
10538  destroy() {
10539    if (this.#uiManager.getActive()?.parent === this) {
10540      this.#uiManager.setActiveEditor(null);
10541    }
10542    for (const editor of this.#editors.values()) {
10543      this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
10544      editor.setParent(null);
10545      editor.isAttachedToDOM = false;
10546      editor.div.remove();
10547    }
10548    this.div = null;
10549    this.#editors.clear();
10550    this.#uiManager.removeLayer(this);
10551  }
10552  #cleanup() {
10553    this.#isCleaningUp = true;
10554    for (const editor of this.#editors.values()) {
10555      if (editor.isEmpty()) {
10556        editor.remove();
10557      }
10558    }
10559    this.#isCleaningUp = false;
10560  }
10561  render({
10562    viewport
10563  }) {
10564    this.viewport = viewport;
10565    (0, _display_utils.setLayerDimensions)(this.div, viewport);
10566    (0, _tools.bindEvents)(this, this.div, ["dragover", "drop"]);
10567    for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
10568      this.add(editor);
10569    }
10570    this.updateMode();
10571  }
10572  update({
10573    viewport
10574  }) {
10575    this.#uiManager.commitOrRemove();
10576    this.viewport = viewport;
10577    (0, _display_utils.setLayerDimensions)(this.div, {
10578      rotation: viewport.rotation
10579    });
10580    this.updateMode();
10581  }
10582  get pageDimensions() {
10583    const {
10584      pageWidth,
10585      pageHeight
10586    } = this.viewport.rawDims;
10587    return [pageWidth, pageHeight];
10588  }
10589}
10590exports.AnnotationEditorLayer = AnnotationEditorLayer;
10591
10592/***/ }),
10593/* 28 */
10594/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
10595
10596
10597
10598Object.defineProperty(exports, "__esModule", ({
10599  value: true
10600}));
10601exports.FreeTextEditor = void 0;
10602var _util = __w_pdfjs_require__(1);
10603var _tools = __w_pdfjs_require__(5);
10604var _editor = __w_pdfjs_require__(4);
10605class FreeTextEditor extends _editor.AnnotationEditor {
10606  #boundEditorDivBlur = this.editorDivBlur.bind(this);
10607  #boundEditorDivFocus = this.editorDivFocus.bind(this);
10608  #boundEditorDivInput = this.editorDivInput.bind(this);
10609  #boundEditorDivKeydown = this.editorDivKeydown.bind(this);
10610  #color;
10611  #content = "";
10612  #editorDivId = `${this.id}-editor`;
10613  #hasAlreadyBeenCommitted = false;
10614  #fontSize;
10615  static _freeTextDefaultContent = "";
10616  static _l10nPromise;
10617  static _internalPadding = 0;
10618  static _defaultColor = null;
10619  static _defaultFontSize = 10;
10620  static _keyboardManager = new _tools.KeyboardManager([[["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], FreeTextEditor.prototype.commitOrRemove]]);
10621  static _type = "freetext";
10622  constructor(params) {
10623    super({
10624      ...params,
10625      name: "freeTextEditor"
10626    });
10627    this.#color = params.color || FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
10628    this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
10629  }
10630  static initialize(l10n) {
10631    this._l10nPromise = new Map(["free_text2_default_content", "editor_free_text2_aria_label"].map(str => [str, l10n.get(str)]));
10632    const style = getComputedStyle(document.documentElement);
10633    this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
10634  }
10635  static updateDefaultParams(type, value) {
10636    switch (type) {
10637      case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
10638        FreeTextEditor._defaultFontSize = value;
10639        break;
10640      case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
10641        FreeTextEditor._defaultColor = value;
10642        break;
10643    }
10644  }
10645  updateParams(type, value) {
10646    switch (type) {
10647      case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
10648        this.#updateFontSize(value);
10649        break;
10650      case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
10651        this.#updateColor(value);
10652        break;
10653    }
10654  }
10655  static get defaultPropertiesToUpdate() {
10656    return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor]];
10657  }
10658  get propertiesToUpdate() {
10659    return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
10660  }
10661  #updateFontSize(fontSize) {
10662    const setFontsize = size => {
10663      this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
10664      this.translate(0, -(size - this.#fontSize) * this.parentScale);
10665      this.#fontSize = size;
10666      this.#setEditorDimensions();
10667    };
10668    const savedFontsize = this.#fontSize;
10669    this.addCommands({
10670      cmd: () => {
10671        setFontsize(fontSize);
10672      },
10673      undo: () => {
10674        setFontsize(savedFontsize);
10675      },
10676      mustExec: true,
10677      type: _util.AnnotationEditorParamsType.FREETEXT_SIZE,
10678      overwriteIfSameType: true,
10679      keepUndo: true
10680    });
10681  }
10682  #updateColor(color) {
10683    const savedColor = this.#color;
10684    this.addCommands({
10685      cmd: () => {
10686        this.#color = this.editorDiv.style.color = color;
10687      },
10688      undo: () => {
10689        this.#color = this.editorDiv.style.color = savedColor;
10690      },
10691      mustExec: true,
10692      type: _util.AnnotationEditorParamsType.FREETEXT_COLOR,
10693      overwriteIfSameType: true,
10694      keepUndo: true
10695    });
10696  }
10697  getInitialTranslation() {
10698    const scale = this.parentScale;
10699    return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
10700  }
10701  rebuild() {
10702    super.rebuild();
10703    if (this.div === null) {
10704      return;
10705    }
10706    if (!this.isAttachedToDOM) {
10707      this.parent.add(this);
10708    }
10709  }
10710  enableEditMode() {
10711    if (this.isInEditMode()) {
10712      return;
10713    }
10714    this.parent.setEditingState(false);
10715    this.parent.updateToolbar(_util.AnnotationEditorType.FREETEXT);
10716    super.enableEditMode();
10717    this.overlayDiv.classList.remove("enabled");
10718    this.editorDiv.contentEditable = true;
10719    this.div.draggable = false;
10720    this.div.removeAttribute("aria-activedescendant");
10721    this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown);
10722    this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus);
10723    this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur);
10724    this.editorDiv.addEventListener("input", this.#boundEditorDivInput);
10725  }
10726  disableEditMode() {
10727    if (!this.isInEditMode()) {
10728      return;
10729    }
10730    this.parent.setEditingState(true);
10731    super.disableEditMode();
10732    this.overlayDiv.classList.add("enabled");
10733    this.editorDiv.contentEditable = false;
10734    this.div.setAttribute("aria-activedescendant", this.#editorDivId);
10735    this.div.draggable = true;
10736    this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown);
10737    this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus);
10738    this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur);
10739    this.editorDiv.removeEventListener("input", this.#boundEditorDivInput);
10740    this.div.focus({
10741      preventScroll: true
10742    });
10743    this.isEditing = false;
10744    this.parent.div.classList.add("freeTextEditing");
10745  }
10746  focusin(event) {
10747    super.focusin(event);
10748    if (event.target !== this.editorDiv) {
10749      this.editorDiv.focus();
10750    }
10751  }
10752  onceAdded() {
10753    if (this.width) {
10754      return;
10755    }
10756    this.enableEditMode();
10757    this.editorDiv.focus();
10758  }
10759  isEmpty() {
10760    return !this.editorDiv || this.editorDiv.innerText.trim() === "";
10761  }
10762  remove() {
10763    this.isEditing = false;
10764    this.parent.setEditingState(true);
10765    this.parent.div.classList.add("freeTextEditing");
10766    super.remove();
10767  }
10768  #extractText() {
10769    const divs = this.editorDiv.getElementsByTagName("div");
10770    if (divs.length === 0) {
10771      return this.editorDiv.innerText;
10772    }
10773    const buffer = [];
10774    for (const div of divs) {
10775      buffer.push(div.innerText.replace(/\r\n?|\n/, ""));
10776    }
10777    return buffer.join("\n");
10778  }
10779  #setEditorDimensions() {
10780    const [parentWidth, parentHeight] = this.parentDimensions;
10781    let rect;
10782    if (this.isAttachedToDOM) {
10783      rect = this.div.getBoundingClientRect();
10784    } else {
10785      const {
10786        currentLayer,
10787        div
10788      } = this;
10789      const savedDisplay = div.style.display;
10790      div.style.display = "hidden";
10791      currentLayer.div.append(this.div);
10792      rect = div.getBoundingClientRect();
10793      div.remove();
10794      div.style.display = savedDisplay;
10795    }
10796    this.width = rect.width / parentWidth;
10797    this.height = rect.height / parentHeight;
10798  }
10799  commit() {
10800    if (!this.isInEditMode()) {
10801      return;
10802    }
10803    super.commit();
10804    if (!this.#hasAlreadyBeenCommitted) {
10805      this.#hasAlreadyBeenCommitted = true;
10806      this.parent.addUndoableEditor(this);
10807    }
10808    this.disableEditMode();
10809    this.#content = this.#extractText().trimEnd();
10810    this.#setEditorDimensions();
10811  }
10812  shouldGetKeyboardEvents() {
10813    return this.isInEditMode();
10814  }
10815  dblclick(event) {
10816    this.enableEditMode();
10817    this.editorDiv.focus();
10818  }
10819  keydown(event) {
10820    if (event.target === this.div && event.key === "Enter") {
10821      this.enableEditMode();
10822      this.editorDiv.focus();
10823    }
10824  }
10825  editorDivKeydown(event) {
10826    FreeTextEditor._keyboardManager.exec(this, event);
10827  }
10828  editorDivFocus(event) {
10829    this.isEditing = true;
10830  }
10831  editorDivBlur(event) {
10832    this.isEditing = false;
10833  }
10834  editorDivInput(event) {
10835    this.parent.div.classList.toggle("freeTextEditing", this.isEmpty());
10836  }
10837  disableEditing() {
10838    this.editorDiv.setAttribute("role", "comment");
10839    this.editorDiv.removeAttribute("aria-multiline");
10840  }
10841  enableEditing() {
10842    this.editorDiv.setAttribute("role", "textbox");
10843    this.editorDiv.setAttribute("aria-multiline", true);
10844  }
10845  render() {
10846    if (this.div) {
10847      return this.div;
10848    }
10849    let baseX, baseY;
10850    if (this.width) {
10851      baseX = this.x;
10852      baseY = this.y;
10853    }
10854    super.render();
10855    this.editorDiv = document.createElement("div");
10856    this.editorDiv.className = "internal";
10857    this.editorDiv.setAttribute("id", this.#editorDivId);
10858    this.enableEditing();
10859    FreeTextEditor._l10nPromise.get("editor_free_text2_aria_label").then(msg => this.editorDiv?.setAttribute("aria-label", msg));
10860    FreeTextEditor._l10nPromise.get("free_text2_default_content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
10861    this.editorDiv.contentEditable = true;
10862    const {
10863      style
10864    } = this.editorDiv;
10865    style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
10866    style.color = this.#color;
10867    this.div.append(this.editorDiv);
10868    this.overlayDiv = document.createElement("div");
10869    this.overlayDiv.classList.add("overlay", "enabled");
10870    this.div.append(this.overlayDiv);
10871    (0, _tools.bindEvents)(this, this.div, ["dblclick", "keydown"]);
10872    if (this.width) {
10873      const [parentWidth, parentHeight] = this.parentDimensions;
10874      this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
10875      for (const line of this.#content.split("\n")) {
10876        const div = document.createElement("div");
10877        div.append(line ? document.createTextNode(line) : document.createElement("br"));
10878        this.editorDiv.append(div);
10879      }
10880      this.div.draggable = true;
10881      this.editorDiv.contentEditable = false;
10882    } else {
10883      this.div.draggable = false;
10884      this.editorDiv.contentEditable = true;
10885    }
10886    return this.div;
10887  }
10888  get contentDiv() {
10889    return this.editorDiv;
10890  }
10891  static deserialize(data, parent, uiManager) {
10892    const editor = super.deserialize(data, parent, uiManager);
10893    editor.#fontSize = data.fontSize;
10894    editor.#color = _util.Util.makeHexColor(...data.color);
10895    editor.#content = data.value;
10896    return editor;
10897  }
10898  serialize() {
10899    if (this.isEmpty()) {
10900      return null;
10901    }
10902    const padding = FreeTextEditor._internalPadding * this.parentScale;
10903    const rect = this.getRect(padding, padding);
10904    const color = _editor.AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
10905    return {
10906      annotationType: _util.AnnotationEditorType.FREETEXT,
10907      color,
10908      fontSize: this.#fontSize,
10909      value: this.#content,
10910      pageIndex: this.pageIndex,
10911      rect,
10912      rotation: this.rotation
10913    };
10914  }
10915}
10916exports.FreeTextEditor = FreeTextEditor;
10917
10918/***/ }),
10919/* 29 */
10920/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
10921
10922
10923
10924Object.defineProperty(exports, "__esModule", ({
10925  value: true
10926}));
10927exports.InkEditor = void 0;
10928Object.defineProperty(exports, "fitCurve", ({
10929  enumerable: true,
10930  get: function () {
10931    return _pdfjsFitCurve.fitCurve;
10932  }
10933}));
10934var _util = __w_pdfjs_require__(1);
10935var _editor = __w_pdfjs_require__(4);
10936var _pdfjsFitCurve = __w_pdfjs_require__(30);
10937var _tools = __w_pdfjs_require__(5);
10938const RESIZER_SIZE = 16;
10939const TIME_TO_WAIT_BEFORE_FIXING_DIMS = 100;
10940class InkEditor extends _editor.AnnotationEditor {
10941  #aspectRatio = 0;
10942  #baseHeight = 0;
10943  #baseWidth = 0;
10944  #boundCanvasPointermove = this.canvasPointermove.bind(this);
10945  #boundCanvasPointerleave = this.canvasPointerleave.bind(this);
10946  #boundCanvasPointerup = this.canvasPointerup.bind(this);
10947  #boundCanvasPointerdown = this.canvasPointerdown.bind(this);
10948  #disableEditing = false;
10949  #isCanvasInitialized = false;
10950  #lastPoint = null;
10951  #observer = null;
10952  #realWidth = 0;
10953  #realHeight = 0;
10954  #requestFrameCallback = null;
10955  static _defaultColor = null;
10956  static _defaultOpacity = 1;
10957  static _defaultThickness = 1;
10958  static _l10nPromise;
10959  static _type = "ink";
10960  constructor(params) {
10961    super({
10962      ...params,
10963      name: "inkEditor"
10964    });
10965    this.color = params.color || null;
10966    this.thickness = params.thickness || null;
10967    this.opacity = params.opacity || null;
10968    this.paths = [];
10969    this.bezierPath2D = [];
10970    this.currentPath = [];
10971    this.scaleFactor = 1;
10972    this.translationX = this.translationY = 0;
10973    this.x = 0;
10974    this.y = 0;
10975  }
10976  static initialize(l10n) {
10977    this._l10nPromise = new Map(["editor_ink_canvas_aria_label", "editor_ink2_aria_label"].map(str => [str, l10n.get(str)]));
10978  }
10979  static updateDefaultParams(type, value) {
10980    switch (type) {
10981      case _util.AnnotationEditorParamsType.INK_THICKNESS:
10982        InkEditor._defaultThickness = value;
10983        break;
10984      case _util.AnnotationEditorParamsType.INK_COLOR:
10985        InkEditor._defaultColor = value;
10986        break;
10987      case _util.AnnotationEditorParamsType.INK_OPACITY:
10988        InkEditor._defaultOpacity = value / 100;
10989        break;
10990    }
10991  }
10992  updateParams(type, value) {
10993    switch (type) {
10994      case _util.AnnotationEditorParamsType.INK_THICKNESS:
10995        this.#updateThickness(value);
10996        break;
10997      case _util.AnnotationEditorParamsType.INK_COLOR:
10998        this.#updateColor(value);
10999        break;
11000      case _util.AnnotationEditorParamsType.INK_OPACITY:
11001        this.#updateOpacity(value);
11002        break;
11003    }
11004  }
11005  static get defaultPropertiesToUpdate() {
11006    return [[_util.AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [_util.AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor], [_util.AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]];
11007  }
11008  get propertiesToUpdate() {
11009    return [[_util.AnnotationEditorParamsType.INK_THICKNESS, this.thickness || InkEditor._defaultThickness], [_util.AnnotationEditorParamsType.INK_COLOR, this.color || InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor], [_util.AnnotationEditorParamsType.INK_OPACITY, Math.round(100 * (this.opacity ?? InkEditor._defaultOpacity))]];
11010  }
11011  #updateThickness(thickness) {
11012    const savedThickness = this.thickness;
11013    this.addCommands({
11014      cmd: () => {
11015        this.thickness = thickness;
11016        this.#fitToContent();
11017      },
11018      undo: () => {
11019        this.thickness = savedThickness;
11020        this.#fitToContent();
11021      },
11022      mustExec: true,
11023      type: _util.AnnotationEditorParamsType.INK_THICKNESS,
11024      overwriteIfSameType: true,
11025      keepUndo: true
11026    });
11027  }
11028  #updateColor(color) {
11029    const savedColor = this.color;
11030    this.addCommands({
11031      cmd: () => {
11032        this.color = color;
11033        this.#redraw();
11034      },
11035      undo: () => {
11036        this.color = savedColor;
11037        this.#redraw();
11038      },
11039      mustExec: true,
11040      type: _util.AnnotationEditorParamsType.INK_COLOR,
11041      overwriteIfSameType: true,
11042      keepUndo: true
11043    });
11044  }
11045  #updateOpacity(opacity) {
11046    opacity /= 100;
11047    const savedOpacity = this.opacity;
11048    this.addCommands({
11049      cmd: () => {
11050        this.opacity = opacity;
11051        this.#redraw();
11052      },
11053      undo: () => {
11054        this.opacity = savedOpacity;
11055        this.#redraw();
11056      },
11057      mustExec: true,
11058      type: _util.AnnotationEditorParamsType.INK_OPACITY,
11059      overwriteIfSameType: true,
11060      keepUndo: true
11061    });
11062  }
11063  rebuild() {
11064    super.rebuild();
11065    if (this.div === null) {
11066      return;
11067    }
11068    if (!this.canvas) {
11069      this.#createCanvas();
11070      this.#createObserver();
11071    }
11072    if (!this.isAttachedToDOM) {
11073      this.parent.add(this);
11074      this.#setCanvasDims();
11075    }
11076    this.#fitToContent();
11077  }
11078  remove() {
11079    if (this.canvas === null) {
11080      return;
11081    }
11082    if (!this.isEmpty()) {
11083      this.commit();
11084    }
11085    this.canvas.width = this.canvas.height = 0;
11086    this.canvas.remove();
11087    this.canvas = null;
11088    this.#observer.disconnect();
11089    this.#observer = null;
11090    super.remove();
11091  }
11092  setParent(parent) {
11093    if (!this.parent && parent) {
11094      this._uiManager.removeShouldRescale(this);
11095    } else if (this.parent && parent === null) {
11096      this._uiManager.addShouldRescale(this);
11097    }
11098    super.setParent(parent);
11099  }
11100  onScaleChanging() {
11101    const [parentWidth, parentHeight] = this.parentDimensions;
11102    const width = this.width * parentWidth;
11103    const height = this.height * parentHeight;
11104    this.setDimensions(width, height);
11105  }
11106  enableEditMode() {
11107    if (this.#disableEditing || this.canvas === null) {
11108      return;
11109    }
11110    super.enableEditMode();
11111    this.div.draggable = false;
11112    this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
11113    this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup);
11114  }
11115  disableEditMode() {
11116    if (!this.isInEditMode() || this.canvas === null) {
11117      return;
11118    }
11119    super.disableEditMode();
11120    this.div.draggable = !this.isEmpty();
11121    this.div.classList.remove("editing");
11122    this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
11123    this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup);
11124  }
11125  onceAdded() {
11126    this.div.draggable = !this.isEmpty();
11127  }
11128  isEmpty() {
11129    return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
11130  }
11131  #getInitialBBox() {
11132    const {
11133      parentRotation,
11134      parentDimensions: [width, height]
11135    } = this;
11136    switch (parentRotation) {
11137      case 90:
11138        return [0, height, height, width];
11139      case 180:
11140        return [width, height, width, height];
11141      case 270:
11142        return [width, 0, height, width];
11143      default:
11144        return [0, 0, width, height];
11145    }
11146  }
11147  #setStroke() {
11148    const {
11149      ctx,
11150      color,
11151      opacity,
11152      thickness,
11153      parentScale,
11154      scaleFactor
11155    } = this;
11156    ctx.lineWidth = thickness * parentScale / scaleFactor;
11157    ctx.lineCap = "round";
11158    ctx.lineJoin = "round";
11159    ctx.miterLimit = 10;
11160    ctx.strokeStyle = `${color}${(0, _tools.opacityToHex)(opacity)}`;
11161  }
11162  #startDrawing(x, y) {
11163    this.isEditing = true;
11164    if (!this.#isCanvasInitialized) {
11165      this.#isCanvasInitialized = true;
11166      this.#setCanvasDims();
11167      this.thickness ||= InkEditor._defaultThickness;
11168      this.color ||= InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
11169      this.opacity ??= InkEditor._defaultOpacity;
11170    }
11171    this.currentPath.push([x, y]);
11172    this.#lastPoint = null;
11173    this.#setStroke();
11174    this.ctx.beginPath();
11175    this.ctx.moveTo(x, y);
11176    this.#requestFrameCallback = () => {
11177      if (!this.#requestFrameCallback) {
11178        return;
11179      }
11180      if (this.#lastPoint) {
11181        if (this.isEmpty()) {
11182          this.ctx.setTransform(1, 0, 0, 1, 0, 0);
11183          this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
11184        } else {
11185          this.#redraw();
11186        }
11187        this.ctx.lineTo(...this.#lastPoint);
11188        this.#lastPoint = null;
11189        this.ctx.stroke();
11190      }
11191      window.requestAnimationFrame(this.#requestFrameCallback);
11192    };
11193    window.requestAnimationFrame(this.#requestFrameCallback);
11194  }
11195  #draw(x, y) {
11196    const [lastX, lastY] = this.currentPath.at(-1);
11197    if (x === lastX && y === lastY) {
11198      return;
11199    }
11200    this.currentPath.push([x, y]);
11201    this.#lastPoint = [x, y];
11202  }
11203  #stopDrawing(x, y) {
11204    this.ctx.closePath();
11205    this.#requestFrameCallback = null;
11206    x = Math.min(Math.max(x, 0), this.canvas.width);
11207    y = Math.min(Math.max(y, 0), this.canvas.height);
11208    const [lastX, lastY] = this.currentPath.at(-1);
11209    if (x !== lastX || y !== lastY) {
11210      this.currentPath.push([x, y]);
11211    }
11212    let bezier;
11213    if (this.currentPath.length !== 1) {
11214      bezier = (0, _pdfjsFitCurve.fitCurve)(this.currentPath, 30, null);
11215    } else {
11216      const xy = [x, y];
11217      bezier = [[xy, xy.slice(), xy.slice(), xy]];
11218    }
11219    const path2D = InkEditor.#buildPath2D(bezier);
11220    this.currentPath.length = 0;
11221    const cmd = () => {
11222      this.paths.push(bezier);
11223      this.bezierPath2D.push(path2D);
11224      this.rebuild();
11225    };
11226    const undo = () => {
11227      this.paths.pop();
11228      this.bezierPath2D.pop();
11229      if (this.paths.length === 0) {
11230        this.remove();
11231      } else {
11232        if (!this.canvas) {
11233          this.#createCanvas();
11234          this.#createObserver();
11235        }
11236        this.#fitToContent();
11237      }
11238    };
11239    this.addCommands({
11240      cmd,
11241      undo,
11242      mustExec: true
11243    });
11244  }
11245  #redraw() {
11246    if (this.isEmpty()) {
11247      this.#updateTransform();
11248      return;
11249    }
11250    this.#setStroke();
11251    const {
11252      canvas,
11253      ctx
11254    } = this;
11255    ctx.setTransform(1, 0, 0, 1, 0, 0);
11256    ctx.clearRect(0, 0, canvas.width, canvas.height);
11257    this.#updateTransform();
11258    for (const path of this.bezierPath2D) {
11259      ctx.stroke(path);
11260    }
11261  }
11262  commit() {
11263    if (this.#disableEditing) {
11264      return;
11265    }
11266    super.commit();
11267    this.isEditing = false;
11268    this.disableEditMode();
11269    this.setInForeground();
11270    this.#disableEditing = true;
11271    this.div.classList.add("disabled");
11272    this.#fitToContent(true);
11273    this.parent.addInkEditorIfNeeded(true);
11274    this.parent.moveEditorInDOM(this);
11275    this.div.focus({
11276      preventScroll: true
11277    });
11278  }
11279  focusin(event) {
11280    super.focusin(event);
11281    this.enableEditMode();
11282  }
11283  canvasPointerdown(event) {
11284    if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
11285      return;
11286    }
11287    this.setInForeground();
11288    if (event.type !== "mouse") {
11289      this.div.focus();
11290    }
11291    event.stopPropagation();
11292    this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave);
11293    this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove);
11294    this.#startDrawing(event.offsetX, event.offsetY);
11295  }
11296  canvasPointermove(event) {
11297    event.stopPropagation();
11298    this.#draw(event.offsetX, event.offsetY);
11299  }
11300  canvasPointerup(event) {
11301    if (event.button !== 0) {
11302      return;
11303    }
11304    if (this.isInEditMode() && this.currentPath.length !== 0) {
11305      event.stopPropagation();
11306      this.#endDrawing(event);
11307      this.setInBackground();
11308    }
11309  }
11310  canvasPointerleave(event) {
11311    this.#endDrawing(event);
11312    this.setInBackground();
11313  }
11314  #endDrawing(event) {
11315    this.#stopDrawing(event.offsetX, event.offsetY);
11316    this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave);
11317    this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove);
11318    this.addToAnnotationStorage();
11319  }
11320  #createCanvas() {
11321    this.canvas = document.createElement("canvas");
11322    this.canvas.width = this.canvas.height = 0;
11323    this.canvas.className = "inkEditorCanvas";
11324    InkEditor._l10nPromise.get("editor_ink_canvas_aria_label").then(msg => this.canvas?.setAttribute("aria-label", msg));
11325    this.div.append(this.canvas);
11326    this.ctx = this.canvas.getContext("2d");
11327  }
11328  #createObserver() {
11329    let timeoutId = null;
11330    this.#observer = new ResizeObserver(entries => {
11331      const rect = entries[0].contentRect;
11332      if (rect.width && rect.height) {
11333        if (timeoutId !== null) {
11334          clearTimeout(timeoutId);
11335        }
11336        timeoutId = setTimeout(() => {
11337          this.fixDims();
11338          timeoutId = null;
11339        }, TIME_TO_WAIT_BEFORE_FIXING_DIMS);
11340        this.setDimensions(rect.width, rect.height);
11341      }
11342    });
11343    this.#observer.observe(this.div);
11344  }
11345  render() {
11346    if (this.div) {
11347      return this.div;
11348    }
11349    let baseX, baseY;
11350    if (this.width) {
11351      baseX = this.x;
11352      baseY = this.y;
11353    }
11354    super.render();
11355    InkEditor._l10nPromise.get("editor_ink2_aria_label").then(msg => this.div?.setAttribute("aria-label", msg));
11356    const [x, y, w, h] = this.#getInitialBBox();
11357    this.setAt(x, y, 0, 0);
11358    this.setDims(w, h);
11359    this.#createCanvas();
11360    if (this.width) {
11361      const [parentWidth, parentHeight] = this.parentDimensions;
11362      this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
11363      this.#isCanvasInitialized = true;
11364      this.#setCanvasDims();
11365      this.setDims(this.width * parentWidth, this.height * parentHeight);
11366      this.#redraw();
11367      this.#setMinDims();
11368      this.div.classList.add("disabled");
11369    } else {
11370      this.div.classList.add("editing");
11371      this.enableEditMode();
11372    }
11373    this.#createObserver();
11374    return this.div;
11375  }
11376  #setCanvasDims() {
11377    if (!this.#isCanvasInitialized) {
11378      return;
11379    }
11380    const [parentWidth, parentHeight] = this.parentDimensions;
11381    this.canvas.width = Math.ceil(this.width * parentWidth);
11382    this.canvas.height = Math.ceil(this.height * parentHeight);
11383    this.#updateTransform();
11384  }
11385  setDimensions(width, height) {
11386    const roundedWidth = Math.round(width);
11387    const roundedHeight = Math.round(height);
11388    if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
11389      return;
11390    }
11391    this.#realWidth = roundedWidth;
11392    this.#realHeight = roundedHeight;
11393    this.canvas.style.visibility = "hidden";
11394    if (this.#aspectRatio && Math.abs(this.#aspectRatio - width / height) > 1e-2) {
11395      height = Math.ceil(width / this.#aspectRatio);
11396      this.setDims(width, height);
11397    }
11398    const [parentWidth, parentHeight] = this.parentDimensions;
11399    this.width = width / parentWidth;
11400    this.height = height / parentHeight;
11401    if (this.#disableEditing) {
11402      this.#setScaleFactor(width, height);
11403    }
11404    this.#setCanvasDims();
11405    this.#redraw();
11406    this.canvas.style.visibility = "visible";
11407  }
11408  #setScaleFactor(width, height) {
11409    const padding = this.#getPadding();
11410    const scaleFactorW = (width - padding) / this.#baseWidth;
11411    const scaleFactorH = (height - padding) / this.#baseHeight;
11412    this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
11413  }
11414  #updateTransform() {
11415    const padding = this.#getPadding() / 2;
11416    this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
11417  }
11418  static #buildPath2D(bezier) {
11419    const path2D = new Path2D();
11420    for (let i = 0, ii = bezier.length; i < ii; i++) {
11421      const [first, control1, control2, second] = bezier[i];
11422      if (i === 0) {
11423        path2D.moveTo(...first);
11424      }
11425      path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
11426    }
11427    return path2D;
11428  }
11429  #serializePaths(s, tx, ty, h) {
11430    const NUMBER_OF_POINTS_ON_BEZIER_CURVE = 4;
11431    const paths = [];
11432    const padding = this.thickness / 2;
11433    let buffer, points;
11434    for (const bezier of this.paths) {
11435      buffer = [];
11436      points = [];
11437      for (let i = 0, ii = bezier.length; i < ii; i++) {
11438        const [first, control1, control2, second] = bezier[i];
11439        const p10 = s * (first[0] + tx) + padding;
11440        const p11 = h - s * (first[1] + ty) - padding;
11441        const p20 = s * (control1[0] + tx) + padding;
11442        const p21 = h - s * (control1[1] + ty) - padding;
11443        const p30 = s * (control2[0] + tx) + padding;
11444        const p31 = h - s * (control2[1] + ty) - padding;
11445        const p40 = s * (second[0] + tx) + padding;
11446        const p41 = h - s * (second[1] + ty) - padding;
11447        if (i === 0) {
11448          buffer.push(p10, p11);
11449          points.push(p10, p11);
11450        }
11451        buffer.push(p20, p21, p30, p31, p40, p41);
11452        this.#extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, NUMBER_OF_POINTS_ON_BEZIER_CURVE, points);
11453      }
11454      paths.push({
11455        bezier: buffer,
11456        points
11457      });
11458    }
11459    return paths;
11460  }
11461  #extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, n, points) {
11462    if (this.#isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41)) {
11463      points.push(p40, p41);
11464      return;
11465    }
11466    for (let i = 1; i < n - 1; i++) {
11467      const t = i / n;
11468      const mt = 1 - t;
11469      let q10 = t * p10 + mt * p20;
11470      let q11 = t * p11 + mt * p21;
11471      let q20 = t * p20 + mt * p30;
11472      let q21 = t * p21 + mt * p31;
11473      const q30 = t * p30 + mt * p40;
11474      const q31 = t * p31 + mt * p41;
11475      q10 = t * q10 + mt * q20;
11476      q11 = t * q11 + mt * q21;
11477      q20 = t * q20 + mt * q30;
11478      q21 = t * q21 + mt * q31;
11479      q10 = t * q10 + mt * q20;
11480      q11 = t * q11 + mt * q21;
11481      points.push(q10, q11);
11482    }
11483    points.push(p40, p41);
11484  }
11485  #isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41) {
11486    const tol = 10;
11487    const ax = (3 * p20 - 2 * p10 - p40) ** 2;
11488    const ay = (3 * p21 - 2 * p11 - p41) ** 2;
11489    const bx = (3 * p30 - p10 - 2 * p40) ** 2;
11490    const by = (3 * p31 - p11 - 2 * p41) ** 2;
11491    return Math.max(ax, bx) + Math.max(ay, by) <= tol;
11492  }
11493  #getBbox() {
11494    let xMin = Infinity;
11495    let xMax = -Infinity;
11496    let yMin = Infinity;
11497    let yMax = -Infinity;
11498    for (const path of this.paths) {
11499      for (const [first, control1, control2, second] of path) {
11500        const bbox = _util.Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
11501        xMin = Math.min(xMin, bbox[0]);
11502        yMin = Math.min(yMin, bbox[1]);
11503        xMax = Math.max(xMax, bbox[2]);
11504        yMax = Math.max(yMax, bbox[3]);
11505      }
11506    }
11507    return [xMin, yMin, xMax, yMax];
11508  }
11509  #getPadding() {
11510    return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0;
11511  }
11512  #fitToContent(firstTime = false) {
11513    if (this.isEmpty()) {
11514      return;
11515    }
11516    if (!this.#disableEditing) {
11517      this.#redraw();
11518      return;
11519    }
11520    const bbox = this.#getBbox();
11521    const padding = this.#getPadding();
11522    this.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
11523    this.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
11524    const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
11525    const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
11526    const [parentWidth, parentHeight] = this.parentDimensions;
11527    this.width = width / parentWidth;
11528    this.height = height / parentHeight;
11529    this.#aspectRatio = width / height;
11530    this.#setMinDims();
11531    const prevTranslationX = this.translationX;
11532    const prevTranslationY = this.translationY;
11533    this.translationX = -bbox[0];
11534    this.translationY = -bbox[1];
11535    this.#setCanvasDims();
11536    this.#redraw();
11537    this.#realWidth = width;
11538    this.#realHeight = height;
11539    this.setDims(width, height);
11540    const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
11541    this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
11542  }
11543  #setMinDims() {
11544    const {
11545      style
11546    } = this.div;
11547    if (this.#aspectRatio >= 1) {
11548      style.minHeight = `${RESIZER_SIZE}px`;
11549      style.minWidth = `${Math.round(this.#aspectRatio * RESIZER_SIZE)}px`;
11550    } else {
11551      style.minWidth = `${RESIZER_SIZE}px`;
11552      style.minHeight = `${Math.round(RESIZER_SIZE / this.#aspectRatio)}px`;
11553    }
11554  }
11555  static deserialize(data, parent, uiManager) {
11556    const editor = super.deserialize(data, parent, uiManager);
11557    editor.thickness = data.thickness;
11558    editor.color = _util.Util.makeHexColor(...data.color);
11559    editor.opacity = data.opacity;
11560    const [pageWidth, pageHeight] = editor.pageDimensions;
11561    const width = editor.width * pageWidth;
11562    const height = editor.height * pageHeight;
11563    const scaleFactor = editor.parentScale;
11564    const padding = data.thickness / 2;
11565    editor.#aspectRatio = width / height;
11566    editor.#disableEditing = true;
11567    editor.#realWidth = Math.round(width);
11568    editor.#realHeight = Math.round(height);
11569    for (const {
11570      bezier
11571    } of data.paths) {
11572      const path = [];
11573      editor.paths.push(path);
11574      let p0 = scaleFactor * (bezier[0] - padding);
11575      let p1 = scaleFactor * (height - bezier[1] - padding);
11576      for (let i = 2, ii = bezier.length; i < ii; i += 6) {
11577        const p10 = scaleFactor * (bezier[i] - padding);
11578        const p11 = scaleFactor * (height - bezier[i + 1] - padding);
11579        const p20 = scaleFactor * (bezier[i + 2] - padding);
11580        const p21 = scaleFactor * (height - bezier[i + 3] - padding);
11581        const p30 = scaleFactor * (bezier[i + 4] - padding);
11582        const p31 = scaleFactor * (height - bezier[i + 5] - padding);
11583        path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
11584        p0 = p30;
11585        p1 = p31;
11586      }
11587      const path2D = this.#buildPath2D(path);
11588      editor.bezierPath2D.push(path2D);
11589    }
11590    const bbox = editor.#getBbox();
11591    editor.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
11592    editor.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
11593    editor.#setScaleFactor(width, height);
11594    return editor;
11595  }
11596  serialize() {
11597    if (this.isEmpty()) {
11598      return null;
11599    }
11600    const rect = this.getRect(0, 0);
11601    const height = this.rotation % 180 === 0 ? rect[3] - rect[1] : rect[2] - rect[0];
11602    const color = _editor.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
11603    return {
11604      annotationType: _util.AnnotationEditorType.INK,
11605      color,
11606      thickness: this.thickness,
11607      opacity: this.opacity,
11608      paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, height),
11609      pageIndex: this.pageIndex,
11610      rect,
11611      rotation: this.rotation
11612    };
11613  }
11614}
11615exports.InkEditor = InkEditor;
11616
11617/***/ }),
11618/* 30 */
11619/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
11620
11621
11622
11623Object.defineProperty(exports, "__esModule", ({
11624  value: true
11625}));
11626exports.fitCurve = void 0;
11627const fitCurve = __w_pdfjs_require__(31);
11628exports.fitCurve = fitCurve;
11629
11630/***/ }),
11631/* 31 */
11632/***/ ((module) => {
11633
11634
11635
11636function fitCurve(points, maxError, progressCallback) {
11637  if (!Array.isArray(points)) {
11638    throw new TypeError("First argument should be an array");
11639  }
11640  points.forEach(point => {
11641    if (!Array.isArray(point) || point.some(item => typeof item !== 'number') || point.length !== points[0].length) {
11642      throw Error("Each point should be an array of numbers. Each point should have the same amount of numbers.");
11643    }
11644  });
11645  points = points.filter((point, i) => i === 0 || !point.every((val, j) => val === points[i - 1][j]));
11646  if (points.length < 2) {
11647    return [];
11648  }
11649  const len = points.length;
11650  const leftTangent = createTangent(points[1], points[0]);
11651  const rightTangent = createTangent(points[len - 2], points[len - 1]);
11652  return fitCubic(points, leftTangent, rightTangent, maxError, progressCallback);
11653}
11654function fitCubic(points, leftTangent, rightTangent, error, progressCallback) {
11655  const MaxIterations = 20;
11656  var bezCurve, u, uPrime, maxError, prevErr, splitPoint, prevSplit, centerVector, toCenterTangent, fromCenterTangent, beziers, dist, i;
11657  if (points.length === 2) {
11658    dist = maths.vectorLen(maths.subtract(points[0], points[1])) / 3.0;
11659    bezCurve = [points[0], maths.addArrays(points[0], maths.mulItems(leftTangent, dist)), maths.addArrays(points[1], maths.mulItems(rightTangent, dist)), points[1]];
11660    return [bezCurve];
11661  }
11662  u = chordLengthParameterize(points);
11663  [bezCurve, maxError, splitPoint] = generateAndReport(points, u, u, leftTangent, rightTangent, progressCallback);
11664  if (maxError === 0 || maxError < error) {
11665    return [bezCurve];
11666  }
11667  if (maxError < error * error) {
11668    uPrime = u;
11669    prevErr = maxError;
11670    prevSplit = splitPoint;
11671    for (i = 0; i < MaxIterations; i++) {
11672      uPrime = reparameterize(bezCurve, points, uPrime);
11673      [bezCurve, maxError, splitPoint] = generateAndReport(points, u, uPrime, leftTangent, rightTangent, progressCallback);
11674      if (maxError < error) {
11675        return [bezCurve];
11676      } else if (splitPoint === prevSplit) {
11677        let errChange = maxError / prevErr;
11678        if (errChange > .9999 && errChange < 1.0001) {
11679          break;
11680        }
11681      }
11682      prevErr = maxError;
11683      prevSplit = splitPoint;
11684    }
11685  }
11686  beziers = [];
11687  centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint + 1]);
11688  if (centerVector.every(val => val === 0)) {
11689    centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint]);
11690    [centerVector[0], centerVector[1]] = [-centerVector[1], centerVector[0]];
11691  }
11692  toCenterTangent = maths.normalize(centerVector);
11693  fromCenterTangent = maths.mulItems(toCenterTangent, -1);
11694  beziers = beziers.concat(fitCubic(points.slice(0, splitPoint + 1), leftTangent, toCenterTangent, error, progressCallback));
11695  beziers = beziers.concat(fitCubic(points.slice(splitPoint), fromCenterTangent, rightTangent, error, progressCallback));
11696  return beziers;
11697}
11698;
11699function generateAndReport(points, paramsOrig, paramsPrime, leftTangent, rightTangent, progressCallback) {
11700  var bezCurve, maxError, splitPoint;
11701  bezCurve = generateBezier(points, paramsPrime, leftTangent, rightTangent, progressCallback);
11702  [maxError, splitPoint] = computeMaxError(points, bezCurve, paramsOrig);
11703  if (progressCallback) {
11704    progressCallback({
11705      bez: bezCurve,
11706      points: points,
11707      params: paramsOrig,
11708      maxErr: maxError,
11709      maxPoint: splitPoint
11710    });
11711  }
11712  return [bezCurve, maxError, splitPoint];
11713}
11714function generateBezier(points, parameters, leftTangent, rightTangent) {
11715  var bezCurve,
11716    A,
11717    a,
11718    C,
11719    X,
11720    det_C0_C1,
11721    det_C0_X,
11722    det_X_C1,
11723    alpha_l,
11724    alpha_r,
11725    epsilon,
11726    segLength,
11727    i,
11728    len,
11729    tmp,
11730    u,
11731    ux,
11732    firstPoint = points[0],
11733    lastPoint = points[points.length - 1];
11734  bezCurve = [firstPoint, null, null, lastPoint];
11735  A = maths.zeros_Xx2x2(parameters.length);
11736  for (i = 0, len = parameters.length; i < len; i++) {
11737    u = parameters[i];
11738    ux = 1 - u;
11739    a = A[i];
11740    a[0] = maths.mulItems(leftTangent, 3 * u * (ux * ux));
11741    a[1] = maths.mulItems(rightTangent, 3 * ux * (u * u));
11742  }
11743  C = [[0, 0], [0, 0]];
11744  X = [0, 0];
11745  for (i = 0, len = points.length; i < len; i++) {
11746    u = parameters[i];
11747    a = A[i];
11748    C[0][0] += maths.dot(a[0], a[0]);
11749    C[0][1] += maths.dot(a[0], a[1]);
11750    C[1][0] += maths.dot(a[0], a[1]);
11751    C[1][1] += maths.dot(a[1], a[1]);
11752    tmp = maths.subtract(points[i], bezier.q([firstPoint, firstPoint, lastPoint, lastPoint], u));
11753    X[0] += maths.dot(a[0], tmp);
11754    X[1] += maths.dot(a[1], tmp);
11755  }
11756  det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
11757  det_C0_X = C[0][0] * X[1] - C[1][0] * X[0];
11758  det_X_C1 = X[0] * C[1][1] - X[1] * C[0][1];
11759  alpha_l = det_C0_C1 === 0 ? 0 : det_X_C1 / det_C0_C1;
11760  alpha_r = det_C0_C1 === 0 ? 0 : det_C0_X / det_C0_C1;
11761  segLength = maths.vectorLen(maths.subtract(firstPoint, lastPoint));
11762  epsilon = 1.0e-6 * segLength;
11763  if (alpha_l < epsilon || alpha_r < epsilon) {
11764    bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, segLength / 3.0));
11765    bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, segLength / 3.0));
11766  } else {
11767    bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, alpha_l));
11768    bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, alpha_r));
11769  }
11770  return bezCurve;
11771}
11772;
11773function reparameterize(bezier, points, parameters) {
11774  return parameters.map((p, i) => newtonRaphsonRootFind(bezier, points[i], p));
11775}
11776;
11777function newtonRaphsonRootFind(bez, point, u) {
11778  var d = maths.subtract(bezier.q(bez, u), point),
11779    qprime = bezier.qprime(bez, u),
11780    numerator = maths.mulMatrix(d, qprime),
11781    denominator = maths.sum(maths.squareItems(qprime)) + 2 * maths.mulMatrix(d, bezier.qprimeprime(bez, u));
11782  if (denominator === 0) {
11783    return u;
11784  } else {
11785    return u - numerator / denominator;
11786  }
11787}
11788;
11789function chordLengthParameterize(points) {
11790  var u = [],
11791    currU,
11792    prevU,
11793    prevP;
11794  points.forEach((p, i) => {
11795    currU = i ? prevU + maths.vectorLen(maths.subtract(p, prevP)) : 0;
11796    u.push(currU);
11797    prevU = currU;
11798    prevP = p;
11799  });
11800  u = u.map(x => x / prevU);
11801  return u;
11802}
11803;
11804function computeMaxError(points, bez, parameters) {
11805  var dist, maxDist, splitPoint, v, i, count, point, t;
11806  maxDist = 0;
11807  splitPoint = Math.floor(points.length / 2);
11808  const t_distMap = mapTtoRelativeDistances(bez, 10);
11809  for (i = 0, count = points.length; i < count; i++) {
11810    point = points[i];
11811    t = find_t(bez, parameters[i], t_distMap, 10);
11812    v = maths.subtract(bezier.q(bez, t), point);
11813    dist = v[0] * v[0] + v[1] * v[1];
11814    if (dist > maxDist) {
11815      maxDist = dist;
11816      splitPoint = i;
11817    }
11818  }
11819  return [maxDist, splitPoint];
11820}
11821;
11822var mapTtoRelativeDistances = function (bez, B_parts) {
11823  var B_t_curr;
11824  var B_t_dist = [0];
11825  var B_t_prev = bez[0];
11826  var sumLen = 0;
11827  for (var i = 1; i <= B_parts; i++) {
11828    B_t_curr = bezier.q(bez, i / B_parts);
11829    sumLen += maths.vectorLen(maths.subtract(B_t_curr, B_t_prev));
11830    B_t_dist.push(sumLen);
11831    B_t_prev = B_t_curr;
11832  }
11833  B_t_dist = B_t_dist.map(x => x / sumLen);
11834  return B_t_dist;
11835};
11836function find_t(bez, param, t_distMap, B_parts) {
11837  if (param < 0) {
11838    return 0;
11839  }
11840  if (param > 1) {
11841    return 1;
11842  }
11843  var lenMax, lenMin, tMax, tMin, t;
11844  for (var i = 1; i <= B_parts; i++) {
11845    if (param <= t_distMap[i]) {
11846      tMin = (i - 1) / B_parts;
11847      tMax = i / B_parts;
11848      lenMin = t_distMap[i - 1];
11849      lenMax = t_distMap[i];
11850      t = (param - lenMin) / (lenMax - lenMin) * (tMax - tMin) + tMin;
11851      break;
11852    }
11853  }
11854  return t;
11855}
11856function createTangent(pointA, pointB) {
11857  return maths.normalize(maths.subtract(pointA, pointB));
11858}
11859class maths {
11860  static zeros_Xx2x2(x) {
11861    var zs = [];
11862    while (x--) {
11863      zs.push([0, 0]);
11864    }
11865    return zs;
11866  }
11867  static mulItems(items, multiplier) {
11868    return items.map(x => x * multiplier);
11869  }
11870  static mulMatrix(m1, m2) {
11871    return m1.reduce((sum, x1, i) => sum + x1 * m2[i], 0);
11872  }
11873  static subtract(arr1, arr2) {
11874    return arr1.map((x1, i) => x1 - arr2[i]);
11875  }
11876  static addArrays(arr1, arr2) {
11877    return arr1.map((x1, i) => x1 + arr2[i]);
11878  }
11879  static addItems(items, addition) {
11880    return items.map(x => x + addition);
11881  }
11882  static sum(items) {
11883    return items.reduce((sum, x) => sum + x);
11884  }
11885  static dot(m1, m2) {
11886    return maths.mulMatrix(m1, m2);
11887  }
11888  static vectorLen(v) {
11889    return Math.hypot(...v);
11890  }
11891  static divItems(items, divisor) {
11892    return items.map(x => x / divisor);
11893  }
11894  static squareItems(items) {
11895    return items.map(x => x * x);
11896  }
11897  static normalize(v) {
11898    return this.divItems(v, this.vectorLen(v));
11899  }
11900}
11901class bezier {
11902  static q(ctrlPoly, t) {
11903    var tx = 1.0 - t;
11904    var pA = maths.mulItems(ctrlPoly[0], tx * tx * tx),
11905      pB = maths.mulItems(ctrlPoly[1], 3 * tx * tx * t),
11906      pC = maths.mulItems(ctrlPoly[2], 3 * tx * t * t),
11907      pD = maths.mulItems(ctrlPoly[3], t * t * t);
11908    return maths.addArrays(maths.addArrays(pA, pB), maths.addArrays(pC, pD));
11909  }
11910  static qprime(ctrlPoly, t) {
11911    var tx = 1.0 - t;
11912    var pA = maths.mulItems(maths.subtract(ctrlPoly[1], ctrlPoly[0]), 3 * tx * tx),
11913      pB = maths.mulItems(maths.subtract(ctrlPoly[2], ctrlPoly[1]), 6 * tx * t),
11914      pC = maths.mulItems(maths.subtract(ctrlPoly[3], ctrlPoly[2]), 3 * t * t);
11915    return maths.addArrays(maths.addArrays(pA, pB), pC);
11916  }
11917  static qprimeprime(ctrlPoly, t) {
11918    return maths.addArrays(maths.mulItems(maths.addArrays(maths.subtract(ctrlPoly[2], maths.mulItems(ctrlPoly[1], 2)), ctrlPoly[0]), 6 * (1.0 - t)), maths.mulItems(maths.addArrays(maths.subtract(ctrlPoly[3], maths.mulItems(ctrlPoly[2], 2)), ctrlPoly[1]), 6 * t));
11919  }
11920}
11921module.exports = fitCurve;
11922module.exports.fitCubic = fitCubic;
11923module.exports.createTangent = createTangent;
11924
11925/***/ }),
11926/* 32 */
11927/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
11928
11929
11930
11931Object.defineProperty(exports, "__esModule", ({
11932  value: true
11933}));
11934exports.AnnotationLayer = void 0;
11935var _util = __w_pdfjs_require__(1);
11936var _display_utils = __w_pdfjs_require__(6);
11937var _annotation_storage = __w_pdfjs_require__(3);
11938var _scripting_utils = __w_pdfjs_require__(33);
11939var _xfa_layer = __w_pdfjs_require__(34);
11940const DEFAULT_TAB_INDEX = 1000;
11941const DEFAULT_FONT_SIZE = 9;
11942const GetElementsByNameSet = new WeakSet();
11943function getRectDims(rect) {
11944  return {
11945    width: rect[2] - rect[0],
11946    height: rect[3] - rect[1]
11947  };
11948}
11949class AnnotationElementFactory {
11950  static create(parameters) {
11951    const subtype = parameters.data.annotationType;
11952    switch (subtype) {
11953      case _util.AnnotationType.LINK:
11954        return new LinkAnnotationElement(parameters);
11955      case _util.AnnotationType.TEXT:
11956        return new TextAnnotationElement(parameters);
11957      case _util.AnnotationType.WIDGET:
11958        const fieldType = parameters.data.fieldType;
11959        switch (fieldType) {
11960          case "Tx":
11961            return new TextWidgetAnnotationElement(parameters);
11962          case "Btn":
11963            if (parameters.data.radioButton) {
11964              return new RadioButtonWidgetAnnotationElement(parameters);
11965            } else if (parameters.data.checkBox) {
11966              return new CheckboxWidgetAnnotationElement(parameters);
11967            }
11968            return new PushButtonWidgetAnnotationElement(parameters);
11969          case "Ch":
11970            return new ChoiceWidgetAnnotationElement(parameters);
11971        }
11972        return new WidgetAnnotationElement(parameters);
11973      case _util.AnnotationType.POPUP:
11974        return new PopupAnnotationElement(parameters);
11975      case _util.AnnotationType.FREETEXT:
11976        return new FreeTextAnnotationElement(parameters);
11977      case _util.AnnotationType.LINE:
11978        return new LineAnnotationElement(parameters);
11979      case _util.AnnotationType.SQUARE:
11980        return new SquareAnnotationElement(parameters);
11981      case _util.AnnotationType.CIRCLE:
11982        return new CircleAnnotationElement(parameters);
11983      case _util.AnnotationType.POLYLINE:
11984        return new PolylineAnnotationElement(parameters);
11985      case _util.AnnotationType.CARET:
11986        return new CaretAnnotationElement(parameters);
11987      case _util.AnnotationType.INK:
11988        return new InkAnnotationElement(parameters);
11989      case _util.AnnotationType.POLYGON:
11990        return new PolygonAnnotationElement(parameters);
11991      case _util.AnnotationType.HIGHLIGHT:
11992        return new HighlightAnnotationElement(parameters);
11993      case _util.AnnotationType.UNDERLINE:
11994        return new UnderlineAnnotationElement(parameters);
11995      case _util.AnnotationType.SQUIGGLY:
11996        return new SquigglyAnnotationElement(parameters);
11997      case _util.AnnotationType.STRIKEOUT:
11998        return new StrikeOutAnnotationElement(parameters);
11999      case _util.AnnotationType.STAMP:
12000        return new StampAnnotationElement(parameters);
12001      case _util.AnnotationType.FILEATTACHMENT:
12002        return new FileAttachmentAnnotationElement(parameters);
12003      default:
12004        return new AnnotationElement(parameters);
12005    }
12006  }
12007}
12008class AnnotationElement {
12009  constructor(parameters, {
12010    isRenderable = false,
12011    ignoreBorder = false,
12012    createQuadrilaterals = false
12013  }
12013 = {}) {
12014    this.isRenderable = isRenderable;
12015    this.data = parameters.data;
12016    this.layer = parameters.layer;
12017    this.page = parameters.page;
12018    this.viewport = parameters.viewport;
12019    this.linkService = parameters.linkService;
12020    this.downloadManager = parameters.downloadManager;
12021    this.imageResourcesPath = parameters.imageResourcesPath;
12022    this.renderForms = parameters.renderForms;
12023    this.svgFactory = parameters.svgFactory;
12024    this.annotationStorage = parameters.annotationStorage;
12025    this.enableScripting = parameters.enableScripting;
12026    this.hasJSActions = parameters.hasJSActions;
12027    this._fieldObjects = parameters.fieldObjects;
12028    if (isRenderable) {
12029      this.container = this._createContainer(ignoreBorder);
12030    }
12031    if (createQuadrilaterals) {
12032      this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
12033    }
12034  }
12035  _createContainer(ignoreBorder = false) {
12036    const {
12037      data,
12038      page,
12039      viewport
12040    } = this;
12041    const container = document.createElement("section");
12042    container.setAttribute("data-annotation-id", data.id);
12043    const {
12044      pageWidth,
12045      pageHeight,
12046      pageX,
12047      pageY
12048    } = viewport.rawDims;
12049    const {
12050      width,
12051      height
12052    } = getRectDims(data.rect);
12053    const rect = _util.Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
12054    if (!ignoreBorder && data.borderStyle.width > 0) {
12055      container.style.borderWidth = `${data.borderStyle.width}px`;
12056      const horizontalRadius = data.borderStyle.horizontalCornerRadius;
12057      const verticalRadius = data.borderStyle.verticalCornerRadius;
12058      if (horizontalRadius > 0 || verticalRadius > 0) {
12059        const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
12060        container.style.borderRadius = radius;
12061      } else if (this instanceof RadioButtonWidgetAnnotationElement) {
12062        const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
12063        container.style.borderRadius = radius;
12064      }
12065      switch (data.borderStyle.style) {
12066        case _util.AnnotationBorderStyleType.SOLID:
12067          container.style.borderStyle = "solid";
12068          break;
12069        case _util.AnnotationBorderStyleType.DASHED:
12070          container.style.borderStyle = "dashed";
12071          break;
12072        case _util.AnnotationBorderStyleType.BEVELED:
12073          (0, _util.warn)("Unimplemented border style: beveled");
12074          break;
12075        case _util.AnnotationBorderStyleType.INSET:
12076          (0, _util.warn)("Unimplemented border style: inset");
12077          break;
12078        case _util.AnnotationBorderStyleType.UNDERLINE:
12079          container.style.borderBottomStyle = "solid";
12080          break;
12081        default:
12082          break;
12083      }
12084      const borderColor = data.borderColor || null;
12085      if (borderColor) {
12086        container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
12087      } else {
12088        container.style.borderWidth = 0;
12089      }
12090    }
12091    container.style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
12092    container.style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
12093    const {
12094      rotation
12095    } = data;
12096    if (data.hasOwnCanvas || rotation === 0) {
12097      container.style.width = `${100 * width / pageWidth}%`;
12098      container.style.height = `${100 * height / pageHeight}%`;
12099    } else {
12100      this.setRotation(rotation, container);
12101    }
12102    return container;
12103  }
12104  setRotation(angle, container = this.container) {
12105    const {
12106      pageWidth,
12107      pageHeight
12108    } = this.viewport.rawDims;
12109    const {
12110      width,
12111      height
12112    } = getRectDims(this.data.rect);
12113    let elementWidth, elementHeight;
12114    if (angle % 180 === 0) {
12115      elementWidth = 100 * width / pageWidth;
12116      elementHeight = 100 * height / pageHeight;
12117    } else {
12118      elementWidth = 100 * height / pageWidth;
12119      elementHeight = 100 * width / pageHeight;
12120    }
12121    container.style.width = `${elementWidth}%`;
12122    container.style.height = `${elementHeight}%`;
12123    container.setAttribute("data-main-rotation", (360 - angle) % 360);
12124  }
12125  get _commonActions() {
12126    const setColor = (jsName, styleName, event) => {
12127      const color = event.detail[jsName];
12128      event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
12129    };
12130    return (0, _util.shadow)(this, "_commonActions", {
12131      display: event => {
12132        const hidden = event.detail.display % 2 === 1;
12133        this.container.style.visibility = hidden ? "hidden" : "visible";
12134        this.annotationStorage.setValue(this.data.id, {
12135          hidden,
12136          print: event.detail.display === 0 || event.detail.display === 3
12137        });
12138      },
12139      print: event => {
12140        this.annotationStorage.setValue(this.data.id, {
12141          print: event.detail.print
12142        });
12143      },
12144      hidden: event => {
12145        this.container.style.visibility = event.detail.hidden ? "hidden" : "visible";
12146        this.annotationStorage.setValue(this.data.id, {
12147          hidden: event.detail.hidden
12148        });
12149      },
12150      focus: event => {
12151        setTimeout(() =>
12151 event.target.focus({
12152          preventScroll: false
12153        }), 0);
12154      },
12155      userName: event => {
12156        event.target.title = event.detail.userName;
12157      },
12158      readonly: event => {
12159        if (event.detail.readonly) {
12160          event.target.setAttribute("readonly", "");
12161        } else {
12162          event.target.removeAttribute("readonly");
12163        }
12164      },
12165      required: event => {
12166        this._setRequired(event.target, event.detail.required);
12167      },
12168      bgColor: event => {
12169        setColor("bgColor", "backgroundColor", event);
12170      },
12171      fillColor: event => {
12172        setColor("fillColor", "backgroundColor", event);
12173      },
12174      fgColor: event => {
12175        setColor("fgColor", "color", event);
12176      },
12177      textColor: event => {
12178        setColor("textColor", "color", event);
12179      },
12180      borderColor: event => {
12181        setColor("borderColor", "borderColor", event);
12182      },
12183      strokeColor: event => {
12184        setColor("strokeColor", "borderColor", event);
12185      },
12186      rotation: event => {
12187        const angle = event.detail.rotation;
12188        this.setRotation(angle);
12189        this.annotationStorage.setValue(this.data.id, {
12190          rotation: angle
12191        });
12192      }
12193    });
12194  }
12195  _dispatchEventFromSandbox(actions, jsEvent) {
12196    const commonActions = this._commonActions;
12197    for (const name of Object.keys(jsEvent.detail)) {
12198      const action = actions[name] || commonActions[name];
12199      action?.(jsEvent);
12200    }
12201  }
12202  _setDefaultPropertiesFromJS(element) {
12203    if (!this.enableScripting) {
12204      return;
12205    }
12206    const storedData = this.annotationStorage.getRawValue(this.data.id);
12207    if (!storedData) {
12208      return;
12209    }
12210    const commonActions = this._commonActions;
12211    for (const [actionName, detail] of Object.entries(storedData)) {
12212      const action = commonActions[actionName];
12213      if (action) {
12214        const eventProxy = {
12215          detail: {
12216            [actionName]: detail
12217          },
12218          target: element
12219        };
12220        action(eventProxy);
12221        delete storedData[actionName];
12222      }
12223    }
12224  }
12225  _createQuadrilaterals(ignoreBorder = false) {
12226    if (!this.data.quadPoints) {
12227      return null;
12228    }
12229    const quadrilaterals = [];
12230    const savedRect = this.data.rect;
12231    for (const quadPoint of this.data.quadPoints) {
12232      this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
12233      quadrilaterals.push(this._createContainer(ignoreBorder));
12234    }
12235    this.data.rect = savedRect;
12236    return quadrilaterals;
12237  }
12238  _createPopup(trigger, data) {
12239    let container = this.container;
12240    if (this.quadrilaterals) {
12241      trigger = trigger || this.quadrilaterals;
12242      container = this.quadrilaterals[0];
12243    }
12244    if (!trigger) {
12245      trigger = document.createElement("div");
12246      trigger.className = "popupTriggerArea";
12247      container.append(trigger);
12248    }
12249    const popupElement = new PopupElement({
12250      container,
12251      trigger,
12252      color: data.color,
12253      titleObj: data.titleObj,
12254      modificationDate: data.modificationDate,
12255      contentsObj: data.contentsObj,
12256      richText: data.richText,
12257      hideWrapper: true
12258    });
12259    const popup = popupElement.render();
12260    popup.style.left = "100%";
12261    container.append(popup);
12262  }
12263  _renderQuadrilaterals(className) {
12264    for (const quadrilateral of this.quadrilaterals) {
12265      quadrilateral.className = className;
12266    }
12267    return this.quadrilaterals;
12268  }
12269  render() {
12270    (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
12271  }
12272  _getElementsByName(name, skipId = null) {
12273    const fields = [];
12274    if (this._fieldObjects) {
12275      const fieldObj = this._fieldObjects[name];
12276      if (fieldObj) {
12277        for (const {
12278          page,
12279          id,
12280          exportValues
12281        } of fieldObj) {
12282          if (page === -1) {
12283            continue;
12284          }
12285          if (id === skipId) {
12286            continue;
12287          }
12288          const exportValue = typeof exportValues === "string" ? exportValues : null;
12289          const domElement = document.querySelector(`[data-element-id="${id}"]`);
12290          if (domElement && !GetElementsByNameSet.has(domElement)) {
12291            (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
12292            continue;
12293          }
12294          fields.push({
12295            id,
12296            exportValue,
12297            domElement
12298          });
12299        }
12300      }
12301      return fields;
12302    }
12303    for (const domElement of document.getElementsByName(name)) {
12304      const {
12305        exportValue
12306      } = domElement;
12307      const id = domElement.getAttribute("data-element-id");
12308      if (id === skipId) {
12309        continue;
12310      }
12311      if (!GetElementsByNameSet.has(domElement)) {
12312        continue;
12313      }
12314      fields.push({
12315        id,
12316        exportValue,
12317        domElement
12318      });
12319    }
12320    return fields;
12321  }
12322}
12323class LinkAnnotationElement extends AnnotationElement {
12324  constructor(parameters, options = null) {
12325    super(parameters, {
12326      isRenderable: true,
12327      ignoreBorder: !!options?.ignoreBorder,
12328      createQuadrilaterals: true
12329    });
12330    this.isTooltipOnly = parameters.data.isTooltipOnly;
12331  }
12332  render() {
12333    const {
12334      data,
12335      linkService
12336    } = this;
12337    const link = document.createElement("a");
12338    link.setAttribute("data-element-id", data.id);
12339    let isBound = false;
12340    if (data.url) {
12341      linkService.addLinkAttributes(link, data.url, data.newWindow);
12342      isBound = true;
12343    } else if (data.action) {
12344      this._bindNamedAction(link, data.action);
12345      isBound = true;
12346    } else if (data.attachment) {
12347      this._bindAttachment(link, data.attachment);
12348      isBound = true;
12349    } else if (data.setOCGState) {
12350      this.#bindSetOCGState(link, data.setOCGState);
12351      isBound = true;
12352    } else if (data.dest) {
12353      this._bindLink(link, data.dest);
12354      isBound = true;
12355    } else {
12356      if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
12357        this._bindJSAction(link, data);
12358        isBound = true;
12359      }
12360      if (data.resetForm) {
12361        this._bindResetFormAction(link, data.resetForm);
12362        isBound = true;
12363      } else if (this.isTooltipOnly && !isBound) {
12364        this._bindLink(link, "");
12365        isBound = true;
12366      }
12367    }
12368    if (this.quadrilaterals) {
12369      return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
12370        const linkElement = index === 0 ? link : link.cloneNode();
12371        quadrilateral.append(linkElement);
12372        return quadrilateral;
12373      });
12374    }
12375    this.container.className = "linkAnnotation";
12376    if (isBound) {
12377      this.container.append(link);
12378    }
12379    return this.container;
12380  }
12381  #setInternalLink() {
12382    this.container.setAttribute("data-internal-link", "");
12383  }
12384  _bindLink(link, destination) {
12385    link.href = this.linkService.getDestinationHash(destination);
12386    link.onclick = () => {
12387      if (destination) {
12388        this.linkService.goToDestination(destination);
12389      }
12390      return false;
vendor: 4,473 bytes, lines 12391-12543
12391    };
12392    if (destination || destination === "") {
12393      this.#setInternalLink();
12394    }
12395  }
12396  _bindNamedAction(link, action) {
12397    link.href = this.linkService.getAnchorUrl("");
12398    link.onclick = () => {
12399      this.linkService.executeNamedAction(action);
12400      return false;
12401    };
12402    this.#setInternalLink();
12403  }
12404  _bindAttachment(link, attachment) {
12405    link.href = this.linkService.getAnchorUrl("");
12406    link.onclick = () => {
12407      this.downloadManager?.openOrDownloadData(this.container, attachment.content, attachment.filename);
12408      return false;
12409    };
12410    this.#setInternalLink();
12411  }
12412  #bindSetOCGState(link, action) {
12413    link.href = this.linkService.getAnchorUrl("");
12414    link.onclick = () => {
12415      this.linkService.executeSetOCGState(action);
12416      return false;
12417    };
12418    this.#setInternalLink();
12419  }
12420  _bindJSAction(link, data) {
12421    link.href = this.linkService.getAnchorUrl("");
12422    const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
12423    for (const name of Object.keys(data.actions)) {
12424      const jsName = map.get(name);
12425      if (!jsName) {
12426        continue;
12427      }
12428      link[jsName] = () => {
12429        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12430          source: this,
12431          detail: {
12432            id: data.id,
12433            name
12434          }
12435        });
12436        return false;
12437      };
12438    }
12439    if (!link.onclick) {
12440      link.onclick = () => false;
12441    }
12442    this.#setInternalLink();
12443  }
12444  _bindResetFormAction(link, resetForm) {
12445    const otherClickAction = link.onclick;
12446    if (!otherClickAction) {
12447      link.href = this.linkService.getAnchorUrl("");
12448    }
12449    this.#setInternalLink();
12450    if (!this._fieldObjects) {
12451      (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
12452      if (!otherClickAction) {
12453        link.onclick = () => false;
12454      }
12455      return;
12456    }
12457    link.onclick = () => {
12458      otherClickAction?.();
12459      const {
12460        fields: resetFormFields,
12461        refs: resetFormRefs,
12462        include
12463      } = resetForm;
12464      const allFields = [];
12465      if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
12466        const fieldIds = new Set(resetFormRefs);
12467        for (const fieldName of resetFormFields) {
12468          const fields = this._fieldObjects[fieldName] || [];
12469          for (const {
12470            id
12471          } of fields) {
12472            fieldIds.add(id);
12473          }
12474        }
12475        for (const fields of Object.values(this._fieldObjects)) {
12476          for (const field of fields) {
12477            if (fieldIds.has(field.id) === include) {
12478              allFields.push(field);
12479            }
12480          }
12481        }
12482      } else {
12483        for (const fields of Object.values(this._fieldObjects)) {
12484          allFields.push(...fields);
12485        }
12486      }
12487      const storage = this.annotationStorage;
12488      const allIds = [];
12489      for (const field of allFields) {
12490        const {
12491          id
12492        } = field;
12493        allIds.push(id);
12494        switch (field.type) {
12495          case "text":
12496            {
12497              const value = field.defaultValue || "";
12498              storage.setValue(id, {
12499                value
12500              });
12501              break;
12502            }
12503          case "checkbox":
12504          case "radiobutton":
12505            {
12506              const value = field.defaultValue === field.exportValues;
12507              storage.setValue(id, {
12508                value
12509              });
12510              break;
12511            }
12512          case "combobox":
12513          case "listbox":
12514            {
12515              const value = field.defaultValue || "";
12516              storage.setValue(id, {
12517                value
12518              });
12519              break;
12520            }
12521          default:
12522            continue;
12523        }
12524        const domElement = document.querySelector(`[data-element-id="${id}"]`);
12525        if (!domElement) {
12526          continue;
12527        } else if (!GetElementsByNameSet.has(domElement)) {
12528          (0, _util.warn)(`_bindResetFormAction - element not allowed: ${id}`);
12529          continue;
12530        }
12531        domElement.dispatchEvent(new Event("resetform"));
12532      }
12533      if (this.enableScripting) {
12534        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12535          source: this,
12536          detail: {
12537            id: "app",
12538            ids: allIds,
12539            name: "ResetForm"
12540          }
12541        });
12542      }
12543      return false;
12544    };
12545  }
12546}
12547class TextAnnotationElement extends AnnotationElement {
12548  constructor(parameters) {
12549    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
12550    super(parameters, {
12551      isRenderable
12552    });
12553  }
12554  render() {
12555    this.container.className = "textAnnotation";
12556    const image = document.createElement("img");
12557    image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
12558    image.alt = "[{{type}} Annotation]";
12559    image.dataset.l10nId = "text_annotation_type";
12560    image.dataset.l10nArgs = JSON.stringify({
12561      type: this.data.name
12562    });
12563    if (!this.data.hasPopup) {
12564      this._createPopup(image, this.data);
12565    }
12566    this.container.append(image);
12567    return this.container;
12568  }
12569}
12570class WidgetAnnotationElement extends AnnotationElement {
12571  render() {
12572    if (this.data.alternativeText) {
12573      this.container.title = this.data.alternativeText;
12574    }
12575    return this.container;
12576  }
12577  _getKeyModifier(event) {
12578    const {
12579      isWin,
12580      isMac
12581    } = _util.FeatureTest.platform;
12582    return isWin && event.ctrlKey || isMac && event.metaKey;
12583  }
12584  _setEventListener(element, baseName, eventName, valueGetter) {
12585    if (baseName.includes("mouse")) {
12586      element.addEventListener(baseName, event => {
12587        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12588          source: this,
12589          detail: {
12590            id: this.data.id,
12591            name: eventName,
12592            value: valueGetter(event),
12593            shift: event.shiftKey,
12594            modifier: this._getKeyModifier(event)
12595          }
12596        });
12597      });
12598    } else {
12599      element.addEventListener(baseName, event => {
12600        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12601          source: this,
12602          detail: {
12603            id: this.data.id,
12604            name: eventName,
12605            value: valueGetter(event)
12606          }
12607        });
12608      });
12609    }
12610  }
12611  _setEventListeners(element, names, getter) {
12612    for (const [baseName, eventName] of names) {
12613      if (eventName === "Action" || this.data.actions?.[eventName]) {
12614        this._setEventListener(element, baseName, eventName, getter);
12615      }
12616    }
12617  }
12618  _setBackgroundColor(element) {
12619    const color = this.data.backgroundColor || null;
12620    element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
12621  }
12622  _setTextStyle(element) {
12623    const TEXT_ALIGNMENT = ["left", "center", "right"];
12624    const {
12625      fontColor
12626    } = this.data.defaultAppearanceData;
12627    const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE;
12628    const style = element.style;
12629    let computedFontSize;
12630    const BORDER_SIZE = 2;
12631    const roundToOneDecimal = x => Math.round(10 * x) / 10;
12632    if (this.data.multiLine) {
12633      const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
12634      const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1;
12635      const lineHeight = height / numberOfLines;
12636      computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / _util.LINE_FACTOR));
12637    } else {
12638      const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
12639      computedFontSize = Math.min(fontSize, roundToOneDecimal(height / _util.LINE_FACTOR));
12640    }
12641    style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
12642    style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
12643    if (this.data.textAlignment !== null) {
12644      style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
12645    }
12646  }
12647  _setRequired(element, isRequired) {
12648    if (isRequired) {
12649      element.setAttribute("required", true);
12650    } else {
12651      element.removeAttribute("required");
12652    }
12653    element.setAttribute("aria-required", isRequired);
12654  }
12655}
12656class TextWidgetAnnotationElement extends WidgetAnnotationElement {
12657  constructor(parameters) {
12658    const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
12659    super(parameters, {
12660      isRenderable
12661    });
12662  }
12663  setPropertyOnSiblings(base, key, value, keyInStorage) {
12664    const storage = this.annotationStorage;
12665    for (const element of this._getElementsByName(base.name, base.id)) {
12666      if (element.domElement) {
12667        element.domElement[key] = value;
12668      }
12669      storage.setValue(element.id, {
12670        [keyInStorage]: value
12671      });
12672    }
12673  }
12674  render() {
12675    const storage = this.annotationStorage;
12676    const id = this.data.id;
12677    this.container.className = "textWidgetAnnotation";
12678    let element = null;
12679    if (this.renderForms) {
12680      const storedData = storage.getValue(id, {
12681        value: this.data.fieldValue
12682      });
12683      let textContent = storedData.formattedValue || storedData.value || "";
12684      const maxLen = storage.getValue(id, {
12685        charLimit: this.data.maxLen
12686      }).charLimit;
12687      if (maxLen && textContent.length > maxLen) {
12688        textContent = textContent.slice(0, maxLen);
12689      }
12690      const elementData = {
12691        userValue: textContent,
12692        formattedValue: null,
12693        lastCommittedValue: null,
12694        commitKey: 1
12695      };
12696      if (this.data.multiLine) {
12697        element = document.createElement("textarea");
12698        element.textContent = textContent;
12699        if (this.data.doNotScroll) {
12700          element.style.overflowY = "hidden";
12701        }
12702      } else {
12703        element = document.createElement("input");
12704        element.type = "text";
12705        element.setAttribute("value", textContent);
12706        if (this.data.doNotScroll) {
12707          element.style.overflowX = "hidden";
12708        }
12709      }
12710      GetElementsByNameSet.add(element);
12711      element.setAttribute("data-element-id", id);
12712      element.disabled = this.data.readOnly;
12713      element.name = this.data.fieldName;
12714      element.tabIndex = DEFAULT_TAB_INDEX;
12715      this._setRequired(element, this.data.required);
12716      if (maxLen) {
12717        element.maxLength = maxLen;
12718      }
12719      element.addEventListener("input", event => {
12720        storage.setValue(id, {
12721          value: event.target.value
12722        });
12723        this.setPropertyOnSiblings(element, "value", event.target.value, "value");
12724      });
12725      element.addEventListener("resetform", event => {
12726        const defaultValue = this.data.defaultFieldValue ?? "";
12727        element.value = elementData.userValue = defaultValue;
12728        elementData.formattedValue = null;
12729      });
12730      let blurListener = event => {
12731        const {
12732          formattedValue
12733        } = elementData;
12734        if (formattedValue !== null && formattedValue !== undefined) {
12735          event.target.value = formattedValue;
12736        }
12737        event.target.scrollLeft = 0;
12738      };
12739      if (this.enableScripting && this.hasJSActions) {
12740        element.addEventListener("focus", event => {
12741          const {
12742            target
12743          } = event;
12744          if (elementData.userValue) {
12745            target.value = elementData.userValue;
12746          }
12747          elementData.lastCommittedValue = target.value;
12748          elementData.commitKey = 1;
12749        });
12750        element.addEventListener("updatefromsandbox", jsEvent => {
12751          const actions = {
12752            value(event) {
12753              elementData.userValue = event.detail.value ?? "";
12754              storage.setValue(id, {
12755                value: elementData.userValue.toString()
12756              });
12757              event.target.value = elementData.userValue;
12758            },
12759            formattedValue(event) {
12760              const {
12761                formattedValue
12762              } = event.detail;
12763              elementData.formattedValue = formattedValue;
12764              if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
12765                event.target.value = formattedValue;
12766              }
12767              storage.setValue(id, {
12768                formattedValue
12769              });
12770            },
12771            selRange(event) {
12772              event.target.setSelectionRange(...event.detail.selRange);
12773            },
12774            charLimit: event => {
12775              const {
12776                charLimit
12777              } = event.detail;
12778              const {
12779                target
12780              } = event;
12781              if (charLimit === 0) {
12782                target.removeAttribute("maxLength");
12783                return;
12784              }
12785              target.setAttribute("maxLength", charLimit);
12786              let value = elementData.userValue;
12787              if (!value || value.length <= charLimit) {
12788                return;
12789              }
12790              value = value.slice(0, charLimit);
12791              target.value = elementData.userValue = value;
12792              storage.setValue(id, {
12793                value
12794              });
12795              this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12796                source: this,
12797                detail: {
12798                  id,
12799                  name: "Keystroke",
12800                  value,
12801                  willCommit: true,
12802                  commitKey: 1,
12803                  selStart: target.selectionStart,
12804                  selEnd: target.selectionEnd
12805                }
12806              });
12807            }
12808          };
12809          this._dispatchEventFromSandbox(actions, jsEvent);
12810        });
12811        element.addEventListener("keydown", event => {
12812          elementData.commitKey = 1;
12813          let commitKey = -1;
12814          if (event.key === "Escape") {
12815            commitKey = 0;
12816          } else if (event.key === "Enter" && !this.data.multiLine) {
12817            commitKey = 2;
12818          } else if (event.key === "Tab") {
12819            elementData.commitKey = 3;
12820          }
12821          if (commitKey === -1) {
12822            return;
12823          }
12824          const {
12825            value
12826          } = event.target;
12827          if (elementData.lastCommittedValue === value) {
12828            return;
12829          }
12830          elementData.lastCommittedValue = value;
12831          elementData.userValue = value;
12832          this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12833            source: this,
12834            detail: {
12835              id,
12836              name: "Keystroke",
12837              value,
12838              willCommit: true,
12839              commitKey,
12840              selStart: event.target.selectionStart,
12841              selEnd: event.target.selectionEnd
12842            }
12843          });
12844        });
12845        const _blurListener = blurListener;
12846        blurListener = null;
12847        element.addEventListener("blur", event => {
12848          if (!event.relatedTarget) {
12849            return;
12850          }
12851          const {
12852            value
12853          } = event.target;
12854          elementData.userValue = value;
12855          if (elementData.lastCommittedValue !== value) {
12856            this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12857              source: this,
12858              detail: {
12859                id,
12860                name: "Keystroke",
12861                value,
12862                willCommit: true,
12863                commitKey: elementData.commitKey,
12864                selStart: event.target.selectionStart,
12865                selEnd: event.target.selectionEnd
12866              }
12867            });
12868          }
12869          _blurListener(event);
12870        });
12871        if (this.data.actions?.Keystroke) {
12872          element.addEventListener("beforeinput", event => {
12873            elementData.lastCommittedValue = null;
12874            const {
12875              data,
12876              target
12877            } = event;
12878            const {
12879              value,
12880              selectionStart,
12881              selectionEnd
12882            } = target;
12883            let selStart = selectionStart,
12884              selEnd = selectionEnd;
12885            switch (event.inputType) {
12886              case "deleteWordBackward":
12887                {
12888                  const match = value.substring(0, selectionStart).match(/\w*[^\
vendor: 16,077 bytes, lines 12888-13339
12888w]*$/);
12889                  if (match) {
12890                    selStart -= match[0].length;
12891                  }
12892                  break;
12893                }
12894              case "deleteWordForward":
12895                {
12896                  const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
12897                  if (match) {
12898                    selEnd += match[0].length;
12899                  }
12900                  break;
12901                }
12902              case "deleteContentBackward":
12903                if (selectionStart === selectionEnd) {
12904                  selStart -= 1;
12905                }
12906                break;
12907              case "deleteContentForward":
12908                if (selectionStart === selectionEnd) {
12909                  selEnd += 1;
12910                }
12911                break;
12912            }
12913            event.preventDefault();
12914            this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
12915              source: this,
12916              detail: {
12917                id,
12918                name: "Keystroke",
12919                value,
12920                change: data || "",
12921                willCommit: false,
12922                selStart,
12923                selEnd
12924              }
12925            });
12926          });
12927        }
12928        this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
12929      }
12930      if (blurListener) {
12931        element.addEventListener("blur", blurListener);
12932      }
12933      if (this.data.comb) {
12934        const fieldWidth = this.data.rect[2] - this.data.rect[0];
12935        const combWidth = fieldWidth / maxLen;
12936        element.classList.add("comb");
12937        element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
12938      }
12939    } else {
12940      element = document.createElement("div");
12941      element.textContent = this.data.fieldValue;
12942      element.style.verticalAlign = "middle";
12943      element.style.display = "table-cell";
12944    }
12945    this._setTextStyle(element);
12946    this._setBackgroundColor(element);
12947    this._setDefaultPropertiesFromJS(element);
12948    this.container.append(element);
12949    return this.container;
12950  }
12951}
12952class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
12953  constructor(parameters) {
12954    super(parameters, {
12955      isRenderable: parameters.renderForms
12956    });
12957  }
12958  render() {
12959    const storage = this.annotationStorage;
12960    const data = this.data;
12961    const id = data.id;
12962    let value = storage.getValue(id, {
12963      value: data.exportValue === data.fieldValue
12964    }).value;
12965    if (typeof value === "string") {
12966      value = value !== "Off";
12967      storage.setValue(id, {
12968        value
12969      });
12970    }
12971    this.container.className = "buttonWidgetAnnotation checkBox";
12972    const element = document.createElement("input");
12973    GetElementsByNameSet.add(element);
12974    element.setAttribute("data-element-id", id);
12975    element.disabled = data.readOnly;
12976    this._setRequired(element, this.data.required);
12977    element.type = "checkbox";
12978    element.name = data.fieldName;
12979    if (value) {
12980      element.setAttribute("checked", true);
12981    }
12982    element.setAttribute("exportValue", data.exportValue);
12983    element.tabIndex = DEFAULT_TAB_INDEX;
12984    element.addEventListener("change", event => {
12985      const {
12986        name,
12987        checked
12988      } = event.target;
12989      for (const checkbox of this._getElementsByName(name, id)) {
12990        const curChecked = checked && checkbox.exportValue === data.exportValue;
12991        if (checkbox.domElement) {
12992          checkbox.domElement.checked = curChecked;
12993        }
12994        storage.setValue(checkbox.id, {
12995          value: curChecked
12996        });
12997      }
12998      storage.setValue(id, {
12999        value: checked
13000      });
13001    });
13002    element.addEventListener("resetform", event => {
13003      const defaultValue = data.defaultFieldValue || "Off";
13004      event.target.checked = defaultValue === data.exportValue;
13005    });
13006    if (this.enableScripting && this.hasJSActions) {
13007      element.addEventListener("updatefromsandbox", jsEvent => {
13008        const actions = {
13009          value(event) {
13010            event.target.checked = event.detail.value !== "Off";
13011            storage.setValue(id, {
13012              value: event.target.checked
13013            });
13014          }
13015        };
13016        this._dispatchEventFromSandbox(actions, jsEvent);
13017      });
13018      this._setEventListeners(element, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
13019    }
13020    this._setBackgroundColor(element);
13021    this._setDefaultPropertiesFromJS(element);
13022    this.container.append(element);
13023    return this.container;
13024  }
13025}
13026class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
13027  constructor(parameters) {
13028    super(parameters, {
13029      isRenderable: parameters.renderForms
13030    });
13031  }
13032  render() {
13033    this.container.className = "buttonWidgetAnnotation radioButton";
13034    const storage = this.annotationStorage;
13035    const data = this.data;
13036    const id = data.id;
13037    let value = storage.getValue(id, {
13038      value: data.fieldValue === data.buttonValue
13039    }).value;
13040    if (typeof value === "string") {
13041      value = value !== data.buttonValue;
13042      storage.setValue(id, {
13043        value
13044      });
13045    }
13046    const element = document.createElement("input");
13047    GetElementsByNameSet.add(element);
13048    element.setAttribute("data-element-id", id);
13049    element.disabled = data.readOnly;
13050    this._setRequired(element, this.data.required);
13051    element.type = "radio";
13052    element.name = data.fieldName;
13053    if (value) {
13054      element.setAttribute("checked", true);
13055    }
13056    element.tabIndex = DEFAULT_TAB_INDEX;
13057    element.addEventListener("change", event => {
13058      const {
13059        name,
13060        checked
13061      } = event.target;
13062      for (const radio of this._getElementsByName(name, id)) {
13063        storage.setValue(radio.id, {
13064          value: false
13065        });
13066      }
13067      storage.setValue(id, {
13068        value: checked
13069      });
13070    });
13071    element.addEventListener("resetform", event => {
13072      const defaultValue = data.defaultFieldValue;
13073      event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
13074    });
13075    if (this.enableScripting && this.hasJSActions) {
13076      const pdfButtonValue = data.buttonValue;
13077      element.addEventListener("updatefromsandbox", jsEvent => {
13078        const actions = {
13079          value: event => {
13080            const checked = pdfButtonValue === event.detail.value;
13081            for (const radio of this._getElementsByName(event.target.name)) {
13082              const curChecked = checked && radio.id === id;
13083              if (radio.domElement) {
13084                radio.domElement.checked = curChecked;
13085              }
13086              storage.setValue(radio.id, {
13087                value: curChecked
13088              });
13089            }
13090          }
13091        };
13092        this._dispatchEventFromSandbox(actions, jsEvent);
13093      });
13094      this._setEventListeners(element, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
13095    }
13096    this._setBackgroundColor(element);
13097    this._setDefaultPropertiesFromJS(element);
13098    this.container.append(element);
13099    return this.container;
13100  }
13101}
13102class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
13103  constructor(parameters) {
13104    super(parameters, {
13105      ignoreBorder: parameters.data.hasAppearance
13106    });
13107  }
13108  render() {
13109    const container = super.render();
13110    container.className = "buttonWidgetAnnotation pushButton";
13111    if (this.data.alternativeText) {
13112      container.title = this.data.alternativeText;
13113    }
13114    const linkElement = container.lastChild;
13115    if (this.enableScripting && this.hasJSActions && linkElement) {
13116      this._setDefaultPropertiesFromJS(linkElement);
13117      linkElement.addEventListener("updatefromsandbox", jsEvent => {
13118        this._dispatchEventFromSandbox({}, jsEvent);
13119      });
13120    }
13121    return container;
13122  }
13123}
13124class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
13125  constructor(parameters) {
13126    super(parameters, {
13127      isRenderable: parameters.renderForms
13128    });
13129  }
13130  render() {
13131    this.container.className = "choiceWidgetAnnotation";
13132    const storage = this.annotationStorage;
13133    const id = this.data.id;
13134    const storedData = storage.getValue(id, {
13135      value: this.data.fieldValue
13136    });
13137    const selectElement = document.createElement("select");
13138    GetElementsByNameSet.add(selectElement);
13139    selectElement.setAttribute("data-element-id", id);
13140    selectElement.disabled = this.data.readOnly;
13141    this._setRequired(selectElement, this.data.required);
13142    selectElement.name = this.data.fieldName;
13143    selectElement.tabIndex = DEFAULT_TAB_INDEX;
13144    let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
13145    if (!this.data.combo) {
13146      selectElement.size = this.data.options.length;
13147      if (this.data.multiSelect) {
13148        selectElement.multiple = true;
13149      }
13150    }
13151    selectElement.addEventListener("resetform", event => {
13152      const defaultValue = this.data.defaultFieldValue;
13153      for (const option of selectElement.options) {
13154        option.selected = option.value === defaultValue;
13155      }
13156    });
13157    for (const option of this.data.options) {
13158      const optionElement = document.createElement("option");
13159      optionElement.textContent = option.displayValue;
13160      optionElement.value = option.exportValue;
13161      if (storedData.value.includes(option.exportValue)) {
13162        optionElement.setAttribute("selected", true);
13163        addAnEmptyEntry = false;
13164      }
13165      selectElement.append(optionElement);
13166    }
13167    let removeEmptyEntry = null;
13168    if (addAnEmptyEntry) {
13169      const noneOptionElement = document.createElement("option");
13170      noneOptionElement.value = " ";
13171      noneOptionElement.setAttribute("hidden", true);
13172      noneOptionElement.setAttribute("selected", true);
13173      selectElement.prepend(noneOptionElement);
13174      removeEmptyEntry = () => {
13175        noneOptionElement.remove();
13176        selectElement.removeEventListener("input", removeEmptyEntry);
13177        removeEmptyEntry = null;
13178      };
13179      selectElement.addEventListener("input", removeEmptyEntry);
13180    }
13181    const getValue = isExport => {
13182      const name = isExport ? "value" : "textContent";
13183      const {
13184        options,
13185        multiple
13186      } = selectElement;
13187      if (!multiple) {
13188        return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
13189      }
13190      return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
13191    };
13192    let selectedValues = getValue(false);
13193    const getItems = event => {
13194      const options = event.target.options;
13195      return Array.prototype.map.call(options, option => {
13196        return {
13197          displayValue: option.textContent,
13198          exportValue: option.value
13199        };
13200      });
13201    };
13202    if (this.enableScripting && this.hasJSActions) {
13203      selectElement.addEventListener("updatefromsandbox", jsEvent => {
13204        const actions = {
13205          value(event) {
13206            removeEmptyEntry?.();
13207            const value = event.detail.value;
13208            const values = new Set(Array.isArray(value) ? value : [value]);
13209            for (const option of selectElement.options) {
13210              option.selected = values.has(option.value);
13211            }
13212            storage.setValue(id, {
13213              value: getValue(true)
13214            });
13215            selectedValues = getValue(false);
13216          },
13217          multipleSelection(event) {
13218            selectElement.multiple = true;
13219          },
13220          remove(event) {
13221            const options = selectElement.options;
13222            const index = event.detail.remove;
13223            options[index].selected = false;
13224            selectElement.remove(index);
13225            if (options.length > 0) {
13226              const i = Array.prototype.findIndex.call(options, option => option.selected);
13227              if (i === -1) {
13228                options[0].selected = true;
13229              }
13230            }
13231            storage.setValue(id, {
13232              value: getValue(true),
13233              items: getItems(event)
13234            });
13235            selectedValues = getValue(false);
13236          },
13237          clear(event) {
13238            while (selectElement.length !== 0) {
13239              selectElement.remove(0);
13240            }
13241            storage.setValue(id, {
13242              value: null,
13243              items: []
13244            });
13245            selectedValues = getValue(false);
13246          },
13247          insert(event) {
13248            const {
13249              index,
13250              displayValue,
13251              exportValue
13252            } = event.detail.insert;
13253            const selectChild = selectElement.children[index];
13254            const optionElement = document.createElement("option");
13255            optionElement.textContent = displayValue;
13256            optionElement.value = exportValue;
13257            if (selectChild) {
13258              selectChild.before(optionElement);
13259            } else {
13260              selectElement.append(optionElement);
13261            }
13262            storage.setValue(id, {
13263              value: getValue(true),
13264              items: getItems(event)
13265            });
13266            selectedValues = getValue(false);
13267          },
13268          items(event) {
13269            const {
13270              items
13271            } = event.detail;
13272            while (selectElement.length !== 0) {
13273              selectElement.remove(0);
13274            }
13275            for (const item of items) {
13276              const {
13277                displayValue,
13278                exportValue
13279              } = item;
13280              const optionElement = document.createElement("option");
13281              optionElement.textContent = displayValue;
13282              optionElement.value = exportValue;
13283              selectElement.append(optionElement);
13284            }
13285            if (selectElement.options.length > 0) {
13286              selectElement.options[0].selected = true;
13287            }
13288            storage.setValue(id, {
13289              value: getValue(true),
13290              items: getItems(event)
13291            });
13292            selectedValues = getValue(false);
13293          },
13294          indices(event) {
13295            const indices = new Set(event.detail.indices);
13296            for (const option of event.target.options) {
13297              option.selected = indices.has(option.index);
13298            }
13299            storage.setValue(id, {
13300              value: getValue(true)
13301            });
13302            selectedValues = getValue(false);
13303          },
13304          editable(event) {
13305            event.target.disabled = !event.detail.editable;
13306          }
13307        };
13308        this._dispatchEventFromSandbox(actions, jsEvent);
13309      });
13310      selectElement.addEventListener("input", event => {
13311        const exportValue = getValue(true);
13312        storage.setValue(id, {
13313          value: exportValue
13314        });
13315        event.preventDefault();
13316        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
13317          source: this,
13318          detail: {
13319            id,
13320            name: "Keystroke",
13321            value: selectedValues,
13322            changeEx: exportValue,
13323            willCommit: false,
13324            commitKey: 1,
13325            keyDown: false
13326          }
13327        });
13328      });
13329      this._setEventListeners(selectElement, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value);
13330    } else {
13331      selectElement.addEventListener("input", function (event) {
13332        storage.setValue(id, {
13333          value: getValue(true)
13334        });
13335      });
13336    }
13337    if (this.data.combo) {
13338      this._setTextStyle(selectElement);
13339    } else {}
13340    this._setBackgroundColor(selectElement);
13341    this._setDefaultPropertiesFromJS(selectElement);
13342    this.container.append(selectElement);
13343    return this.container;
13344  }
13345}
13346class PopupAnnotationElement extends AnnotationElement {
13347  static IGNORE_TYPES = new Set(["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"]);
13348  constructor(parameters) {
13349    const {
13350      data
13351    } = parameters;
13352    const isRenderable = !PopupAnnotationElement.IGNORE_TYPES.has(data.parentType) && !!(data.titleObj?.str || data.contentsObj?.str || data.richText?.str);
13353    super(parameters, {
13354      isRenderable
13355    });
13356  }
13357  render() {
13358    this.container.className = "popupAnnotation";
13359    const parentElements = this.layer.querySelectorAll(`[data-annotation-id="${this.data.parentId}"]`);
13360    if (parentElements.length === 0) {
13361      return this.container;
13362    }
13363    const popup = new PopupElement({
13364      container: this.container,
13365      trigger: Array.from(parentElements),
13366      color: this.data.color,
13367      titleObj: this.data.titleObj,
13368      modificationDate: this.data.modificationDate,
13369      contentsObj: this.data.contentsObj,
13370      richText: this.data.richText
13371    });
13372    const page = this.page;
13373    const rect = _util.Util.normalizeRect([this.data.parentRect[0], page.view[3] - this.data.parentRect[1] + page.view[1], this.data.parentRect[2], page.view[3] - this.data.parentRect[3] + page.view[1]]);
13374    const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
13375    const popupTop = rect[1];
13376    const {
13377      pageWidth,
13378      pageHeight,
13379      pageX,
13380      pageY
13381    } = this.viewport.rawDims;
13382    this.container.style.left = `${100 * (popupLeft - pageX) / pageWidth}%`;
13383    this.container.style.top = `${100 * (popupTop - pageY) / pageHeight}%`;
13384    this.container.append(popup.render());
13385    return this.container;
13386  }
13387}
13388class PopupElement {
13389  constructor(parameters) {
13390    this.container = parameters.container;
13391    this.trigger = parameters.trigger;
13392    this.color = parameters.color;
13393    this.titleObj = parameters.titleObj;
13394    this.modificationDate = parameters.modificationDate;
13395    this.contentsObj = parameters.contentsObj;
13396    this.richText = parameters.richText;
13397    this.hideWrapper = parameters.hideWrapper || false;
13398    this.pinned = false;
13399  }
13400  render() {
13401    const BACKGROUND_ENLIGHT = 0.7;
13402    const wrapper = document.createElement("div");
13403    wrapper.className = "popupWrapper";
13404    this.hideElement = this.hideWrapper ? wrapper : this.container;
13405    this.hideElement.hidden = true;
13406    const popup = document.createElement("div");
13407    popup.className = "popup";
13408    const color = this.color;
13409    if (color) {
13410      const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
13411      const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
13412      const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
13413      popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
13414    }
13415    const title = document.createElement("h1");
13416    title.dir = this.titleObj.dir;
13417    title.textContent = this.titleObj.str;
13418    popup.append(title);
13419    const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
13420    if (dateObject) {
13421      const modificationDate = document.createElement("span");
13422      modificationDate.className = "popupDate";
13423      modificationDate.textContent = "{{date}}, {{time}}";
13424      modificationDate.dataset.l10nId = "annotation_date_string";
13425      modificationDate.dataset.l10nArgs = JSON.stringify({
13426        date: dateObject.toLocaleDateString(),
13427        time: dateObject.toLocaleTimeString()
13428      });
13429      popup.append(modificationDate);
13430    }
13431    if (this.richText?.str && (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)) {
13432      _xfa_layer.XfaLayer.render({
13433        xfaHtml: this.richText.html,
13434        intent: "richText",
13435        div: popup
13436      });
13437      popup.lastChild.className = "richText popupContent";
13438    } else {
13439      const contents = this._formatContents(this.contentsObj);
13440      popup.append(contents);
13441    }
13442    if (!Array.isArray(this.trigger)) {
13443      this.trigger = [this.trigger];
13444    }
13445    for (const element of this.trigger) {
13446      element.addEventListener("click", this._toggle.bind(this));
13447      element.addEventListener("mouseover", this._show.bind(this, false));
13448      element.addEventListener("mouseout", this._hide.bind(this, false));
13449    }
13450    popup.addEventListener("click", this._hide.bind(this, true));
13451    wrapper.append(popup);
13452    return wrapper;
13453  }
13454  _formatContents({
13455    str,
13456    dir
13457  }) {
13458    const p = document.createElement("p");
13459    p.className = "popupContent";
13460    p.dir = dir;
13461    const lines = str.split(/(?:\r\n?|\n)/);
13462    for (let i = 0, ii = lines.length; i < ii; ++i) {
13463      const line = lines[i];
13464      p.append(document.createTextNode(line));
13465      if (i < ii - 1) {
13466        p.append(document.createElement("br"));
13467      }
13468    }
13469    return p;
13470  }
13471  _toggle() {
13472    if (this.pinned) {
13473      this._hide(true);
13474    } else {
13475      this._show(true);
13476    }
13477  }
13478  _show(pin = false) {
13479    if (pin) {
13480      this.pinned = true;
13481    }
13482    if (this.hideElement.hidden) {
13483      this.hideElement.hidden = false;
13484      this.container.style.zIndex = parseInt(this.container.style.zIndex) + 1000;
13485    }
13486  }
13487  _hide(unpin = true) {
13488    if (unpin) {
13489      this.pinned = false;
13490    }
13491    if (!this.hideElement.hidden && !this.pinned) {
13492      this.hideElement.hidden = true;
13493      this.container.style.zIndex = parseInt(this.container.style.zIndex) - 1000;
13494    }
13495  }
13496}
13497class FreeTextAnnotationElement extends AnnotationElement {
13498  constructor(parameters) {
13499    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13500    super(parameters, {
13501      isRenderable,
13502      ignoreBorder: true
13503    });
13504    this.textContent = parameters.data.textContent;
13505  }
13506  render() {
13507    this.container.className = "freeTextAnnotation";
13508    if (this.textContent) {
13509      const content = document.createElement("div");
13510      content.className = "annotationTextContent";
13511      content.setAttribute("role", "comment");
13512      for (const line of this.textContent) {
13513        const lineSpan = document.createElement("span");
13514        lineSpan.textContent = line;
13515        content.append(lineSpan);
13516      }
13517      this.container.append(content);
13518    }
13519    if (!this.data.hasPopup) {
13520      this._createPopup(null, this.data);
13521    }
13522    return this.container;
13523  }
13524}
13525class LineAnnotationElement extends AnnotationElement {
13526  constructor(parameters) {
13527    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13528    super(parameters, {
13529      isRenderable,
13530      ignoreBorder: true
13531    });
13532  }
13533  render() {
13534    this.container.className = "lineAnnotation";
13535    const data = this.data;
13536    const {
13537      width,
13538      height
13539    } = getRectDims(data.rect);
13540    const svg = this.svgFactory.create(width, height, true);
13541    const line = this.svgFactory.createElement("svg:line");
13542    line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
13543    line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
13544    line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
13545    line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
13546    line.setAttribute("stroke-width", data.borderStyle.width || 1);
13547    line.setAttribute("stroke", "transparent");
13548    line.setAttribute("fill", "transparent");
13549    svg.append(line);
13550    this.container.append(svg);
13551    this._createPopup(line, data);
13552    return this.container;
13553  }
13554}
13555class SquareAnnotationElement extends AnnotationElement {
13556  constructor(parameters) {
13557    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13558    super(parameters, {
13559      isRenderable,
13560      ignoreBorder: true
13561    });
13562  }
13563  render() {
13564    this.container.className = "squareAnnotation";
13565    const data = this.data;
13566    const {
13567      width,
13568      height
13569    } = getRectDims(data.rect);
13570    const svg = this.svgFactory.create(width, height, true);
13571    const borderWidth = data.borderStyle.width;
13572    const square = this.svgFactory.createElement("svg:rect");
13573    square.setAttribute("x", borderWidth / 2);
13574    square.setAttribute("y", borderWidth / 2);
13575    square.setAttribute("width", width - borderWidth);
13576    square.setAttribute("height", height - borderWidth);
13577    square.setAttribute("stroke-width", borderWidth || 1);
13578    square.setAttribute("stroke", "transparent");
13579    square.setAttribute("fill", "transparent");
13580    svg.append(square);
13581    this.container.append(svg);
13582    this._createPopup(square, data);
13583    return this.container;
13584  }
13585}
13586class CircleAnnotationElement extends AnnotationElement {
13587  constructor(parameters) {
13588    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13589    super(parameters, {
13590      isRenderable,
13591      ignoreBorder: true
13592    });
13593  }
13594  render() {
13595    this.container.className = "circleAnnotation";
13596    const data = this.data;
13597    const {
13598      width,
13599      height
13600    } = getRectDims(data.rect);
13601    const svg = this.svgFactory.create(width, height, true);
13602    const borderWidth = data.borderStyle.width;
13603    const circle = this.svgFactory.createElement("svg:ellipse");
13604    circle.setAttribute("cx", width / 2);
13605    circle.setAttribute("cy", height / 2);
13606    circle.setAttribute("rx", width / 2 - borderWidth / 2);
13607    circle.setAttribute("ry", height / 2 - borderWidth / 2);
13608    circle.setAttribute("stroke-width", borderWidth || 1);
13609    circle.setAttribute("stroke", "transparent");
13610    circle.setAttribute("fill", "transparent");
13611    svg.append(circle);
13612    this.container.append(svg);
13613    this._createPopup(circle, data);
13614    return this.container;
13615  }
13616}
13617class PolylineAnnotationElement extends AnnotationElement {
13618  constructor(parameters) {
13619    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13620    super(parameters, {
13621      isRenderable,
13622      ignoreBorder: true
13623    });
13624    this.containerClassName = "polylineAnnotation";
13625    this.svgElementName = "svg:polyline";
13626  }
13627  render() {
13628    this.container.className = this.containerClassName;
13629    const data = this.data;
13630    const {
13631      width,
13632      height
13633    } = getRectDims(data.rect);
13634    const svg = this.svgFactory.create(width, height, true);
13635    let points = [];
13636    for (const coordinate of data.vertices) {
13637      const x = coordinate.x - data.rect[0];
13638      const y = data.rect[3] - coordinate.y;
13639      points.push(x + "," + y);
13640    }
13641    points = points.join(" ");
13642    const polyline = this.svgFactory.createElement(this.svgElementName);
13643    polyline.setAttribute("points", points);
13644    polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
13645    polyline.setAttribute("stroke", "transparent");
13646    polyline.setAttribute("fill", "transparent");
13647    svg.append(polyline);
13648    this.container.append(svg);
13649    this._createPopup(polyline, data);
13650    return this.container;
13651  }
13652}
13653class PolygonAnnotationElement extends PolylineAnnotationElement {
13654  constructor(parameters) {
13655    super(parameters);
13656    this.containerClassName = "polygonAnnotation";
13657    this.svgElementName = "svg:polygon";
13658  }
13659}
13660class CaretAnnotationElement extends AnnotationElement {
13661  constructor(parameters) {
13662    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13663    super(parameters, {
13664      isRenderable,
13665      ignoreBorder: true
13666    });
13667  }
13668  render() {
13669    this.container.className = "caretAnnotation";
13670    if (!this.data.hasPopup) {
13671      this._createPopup(null, this.data);
13672    }
13673    return this.container;
13674  }
13675}
13676class InkAnnotationElement extends AnnotationElement {
13677  constructor(parameters) {
13678    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13679    super(parameters, {
13680      isRenderable,
13681      ignoreBorder: true
13682    });
13683    this.containerClassName = "inkAnnotation";
13684    this.svgElementName = "svg:polyline";
13685  }
13686  render() {
13687    this.container.className = this.containerClassName;
13688    const data = this.data;
13689    const {
13690      width,
13691      height
13692    } = getRectDims(data.rect);
13693    const svg = this.svgFactory.create(width, height, true);
13694    for (const inkList of data.inkLists) {
13695      let points = [];
13696      for (const coordinate of inkList) {
13697        const x = coordinate.x - data.rect[0];
13698        const y = data.rect[3] - coordinate.y;
13699        points.push(`${x},${y}`);
13700      }
13701      points = points.join(" ");
13702      const polyline = this.svgFactory.createElement(this.svgElementName);
13703      polyline.setAttribute("points", points);
13704      polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
13705      polyline.setAttribute("stroke", "transparent");
13706      polyline.setAttribute("fill", "transparent");
13707      this._createPopup(polyline, data);
13708      svg.append(polyline);
13709    }
13710    this.container.append(svg);
13711    return this.container;
13712  }
13713}
13714class HighlightAnnotationElement extends AnnotationElement {
13715  constructor(parameters) {
13716    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13717    super(parameters, {
13718      isRenderable,
13719      ignoreBorder: true,
13720      createQuadrilaterals: true
13721    });
13722  }
13723  render() {
13724    if (!this.data.hasPopup) {
13725      this._createPopup(null, this.data);
13726    }
13727    if (this.quadrilaterals) {
13728      return this._renderQuadrilaterals("highlightAnnotation");
13729    }
13730    this.container.className = "highlightAnnotation";
13731    return this.container;
13732  }
13733}
13734class UnderlineAnnotationElement extends AnnotationElement {
13735  constructor(parameters) {
13736    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13737    super(parameters, {
13738      isRenderable,
13739      ignoreBorder: true,
13740      createQuadrilaterals: true
13741    });
13742  }
13743  render() {
13744    if (!this.data.hasPopup) {
13745      this._createPopup(null, this.data);
13746    }
13747    if (this.quadrilaterals) {
13748      return this._renderQuadrilaterals("underlineAnnotation");
13749    }
13750    this.container.className = "underlineAnnotation";
13751    return this.container;
13752  }
13753}
13754class SquigglyAnnotationElement extends AnnotationElement {
13755  constructor(parameters) {
13756    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13757    super(parameters, {
13758      isRenderable,
13759      ignoreBorder: true,
13760      createQuadrilaterals: true
13761    });
13762  }
13763  render() {
13764    if (!this.data.hasPopup) {
13765      this._createPopup(null, this.data);
13766    }
13767    if (this.quadrilaterals) {
13768      return this._renderQuadrilaterals("squigglyAnnotation");
13769    }
13770    this.container.className = "squigglyAnnotation";
13771    return this.container;
13772  }
13773}
13774class StrikeOutAnnotationElement extends AnnotationElement {
13775  constructor(parameters) {
13776    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13777    super(parameters, {
13778      isRenderable,
13779      ignoreBorder: true,
13780      createQuadrilaterals: true
13781    });
13782  }
13783  render() {
13784    if (!this.data.hasPopup) {
13785      this._createPopup(null, this.data);
13786    }
13787    if (this.quadrilaterals) {
13788      return this._renderQuadrilaterals("strikeoutAnnotation");
13789    }
13790    this.container.className = "strikeoutAnnotation";
13791    return this.container;
13792  }
13793}
13794class StampAnnotationElement extends AnnotationElement {
13795  constructor(parameters) {
13796    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
13797    super(parameters, {
13798      isRenderable,
13799      ignoreBorder: true
13800    });
13801  }
13802  render() {
13803    this.container.className = "stampAnnotation";
13804    if (!this.data.hasPopup) {
13805      this._createPopup(null, this.data);
13806    }
13807    return this.container;
13808  }
13809}
13810class FileAttachmentAnnotationElement extends AnnotationElement {
13811  constructor(parameters) {
13812    super(parameters, {
13813      isRenderable: true
13814    });
13815    const {
13816      filename,
13817      content
13818    } = this.data.file;
13819    this.filename = (0, _display_utils.getFilenameFromUrl)(filename, true);
13820    this.content = content;
13821    this.linkService.eventBus?.dispatch("fileattachmentannotation", {
13822      source: this,
13823      filename,
13824      content
13825    });
13826  }
13827  render() {
13828    this.container.className = "fileAttachmentAnnotation";
13829    let trigger;
13830    if (this.data.hasAppearance) {
13831      trigger = document.createElement("div");
13832    } else {
13833      trigger = document.createElement("img");
13834      trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(this.data.name) ? "paperclip" : "pushpin"}.svg`;
13835    }
13836    trigger.className = "popupTriggerArea";
13837    trigger.addEventListener("dblclick", this._download.bind(this));
13838    if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str || this.data.richText)) {
13839      this._createPopup(trigger, this.data);
13840    }
13841    this.container.append(trigger);
13842    return this.container;
13843  }
13844  _download() {
13845    this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
13846  }
13847}
13848class AnnotationLayer {
13849  static #appendElement(element, id, div, accessibilityManager) {
13850    const contentElement = element.firstChild || element;
13851    contentElement.id = `${_display_utils.AnnotationPrefix}${id}`;
13852    div.append(element);
13853    accessibilityManager?.moveElementInDOM(div, element, contentElement, false);
13854  }
13855  static render(params) {
13856    const {
13857      annotations,
13858      div,
13859      viewport,
13860      accessibilityManager
13861    } = params;
13862    (0, _display_utils.setLayerDimensions)(div, viewport);
13863    const elementParams = {
13864      data: null,
13865      layer: div,
13866      page: params.page,
13867      viewport,
13868      linkService: params.linkService,
13869      downloadManager: params.downloadManager,
13870      imageResourcesPath: params.imageResourcesPath || "",
13871      renderForms: params.renderForms !== false,
13872      svgFactory: new _display_utils.DOMSVGFactory(),
13873      annotationStorage: params.annotationStorage || new _annotation_storage.AnnotationStorage(),
13874      enableScripting: params.enableScripting === true,
13875      hasJSActions: params.hasJSActions,
13876      fieldObjects: params.fieldObjects
13877    };
13878    let zIndex = 0;
13879    for (const data of annotations) {
13880      if (data.annotationType !== _util.AnnotationType.POPUP) {
13881        const {
13882          width,
13883          height
13884        } = getRectDims(data.rect);
13885        if (width <= 0 || height <= 0) {
13886          continue;
13887        }
13888      }
13889      elementParams.data = data;
13890      const element = AnnotationElementFactory.create(elementParams);
13891      if (!element.isRenderable) {
13892        continue;
13893      }
13894      const rendered = element.render();
13895      if (data.hidden) {
13896        rendered.style.visibility = "hidden";
13897      }
13898      if (Array.isArray(rendered)) {
13899        for (const renderedElement of rendered) {
13900          renderedElement.style.zIndex = zIndex++;
13901          AnnotationLayer.#appendElement(renderedElement, data.id, div, accessibilityManager);
13902        }
13903      } else {
13904        rendered.style.zIndex = zIndex++;
13905        if (element instanceof PopupAnnotationElement) {
13906          div.prepend(rendered);
13907        } else {
13908          AnnotationLayer.#appendElement(rendered, data.id, div, accessibilityManager);
13909        }
13910      }
13911    }
13912    this.#setAnnotationCanvasMap(div, params.annotationCanvasMap);
13913  }
13914  static update(params) {
13915    const {
13916      annotationCanvasMap,
13917      div,
13918      viewport
13919    } = params;
13920    (0, _display_utils.setLayerDimensions)(div, {
13921      rotation: viewport.rotation
13922    });
13923    this.#setAnnotationCanvasMap(div, annotationCanvasMap);
13924    div.hidden = false;
13925  }
13926  static #setAnnotationCanvasMap(div, annotationCanvasMap) {
13927    if (!annotationCanvasMap) {
13928      return;
13929    }
13930    for (const [id, canvas] of annotationCanvasMap) {
13931      const element = div.querySelector(`[data-annotation-id="${id}"]`);
13932      if (!element) {
13933        continue;
13934      }
13935      const {
13936        firstChild
13937      } = element;
13938      if (!firstChild) {
13939        element.append(canvas);
13940      } else if (firstChild.nodeName === "CANVAS") {
13941        firstChild.replaceWith(canvas);
13942      } else {
13943        firstChild.before(canvas);
13944      }
13945    }
13946    annotationCanvasMap.clear();
13947  }
13948}
13949exports.AnnotationLayer = AnnotationLayer;
13950
13951/***/ }),
13952/* 33 */
13953/***/ ((__unused_webpack_module, exports) => {
13954
13955
13956
13957Object.defineProperty(exports, "__esModule", ({
13958  value: true
13959}));
13960exports.ColorConverters = void 0;
13961function makeColorComp(n) {
13962  return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
13963}
13964class ColorConverters {
13965  static CMYK_G([c, y, m, k]) {
13966    return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
13967  }
13968  static G_CMYK([g]) {
13969    return ["CMYK", 0, 0, 0, 1 - g];
13970  }
13971  static G_RGB([g]) {
13972    return ["RGB", g, g, g];
13973  }
13974  static G_HTML([g]) {
13975    const G = makeColorComp(g);
13976    return `#${G}${G}${G}`;
13977  }
13978  static RGB_G([r, g, b]) {
13979    return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
13980  }
13981  static RGB_HTML([r, g, b]) {
13982    const R = makeColorComp(r);
13983    const G = makeColorComp(g);
13984    const B = makeColorComp(b);
13985    return `#${R}${G}${B}`;
13986  }
13987  static T_HTML() {
13988    return "#00000000";
13989  }
13990  static CMYK_RGB([c, y, m, k]) {
13991    return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
13992  }
13993  static CMYK_HTML(components) {
13994    const rgb = this.CMYK_RGB(components).slice(1);
13995    return this.RGB_HTML(rgb);
13996  }
13997  static RGB_CMYK([r, g, b]) {
13998    const c = 1 - r;
13999    const m = 1 - g;
14000    const y = 1 - b;
14001    const k = Math.min(c, m, y);
14002    return ["CMYK", c, m, y, k];
14003  }
14004}
14005exports.ColorConverters = ColorConverters;
14006
14007/***/ }),
14008/* 34 */
14009/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
14010
14011
14012
14013Object.defineProperty(exports, "__esModule", ({
14014  value: true
14015}));
14016exports.XfaLayer = void 0;
14017var _xfa_text = __w_pdfjs_require__(19);
14018class XfaLayer {
14019  static setupStorage(html, id, element, storage, intent) {
14020    const storedData = storage.getValue(id, {
14021      value: null
14022    });
14023    switch (element.name) {
14024      case "textarea":
14025        if (storedData.value !== null) {
14026          html.textContent = storedData.value;
14027        }
14028        if (intent === "print") {
14029          break;
14030        }
14031        html.addEventListener("input", event => {
14032          storage.setValue(id, {
14033            value: event.target.value
14034          });
14035        });
14036        break;
14037      case "input":
14038        if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
14039          if (storedData.value === element.attributes.xfaOn) {
14040            html.setAttribute("checked", true);
14041          } else if (storedData.value === element.attributes.xfaOff) {
14042            html.removeAttribute("checked");
14043          }
14044          if (intent === "print") {
14045            break;
14046          }
14047          html.addEventListener("change", event => {
14048            storage.setValue(id, {
14049              value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
14050            });
14051          });
14052        } else {
14053          if (storedData.value !== null) {
14054            html.setAttribute("value", storedData.value);
14055          }
14056          if (intent === "print") {
14057            break;
14058          }
14059          html.addEventListener("input", event => {
14060            storage.setValue(id, {
14061              value: event.target.value
14062            });
14063          });
14064        }
14065        break;
14066      case "select":
14067        if (storedData.value !== null) {
14068          for (const option of element.children) {
14069            if (option.attributes.value === storedData.value) {
14070              option.attributes.selected = true;
14071            }
14072          }
14073        }
14074        html.addEventListener("input", event => {
14075          const options = event.target.options;
14076          const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
14077          storage.setValue(id, {
14078            value
14079          });
14080        });
14081        break;
14082    }
14083  }
14084  static setAttributes({
14085    html,
14086    element,
14087    storage = null,
14088    intent,
14089    linkService
14090  }) {
14091    const {
14092      attributes
14093    } = element;
14094    const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
14095    if (attributes.type === "radio") {
14096      attributes.name = `${attributes.name}-${intent}`;
14097    }
14098    for (const [key, value] of Object.entries(attributes)) {
14099      if (value === null || value === undefined) {
14100        continue;
14101      }
14102      switch (key) {
14103        case "class":
14104          if (value.length) {
14105            html.setAttribute(key, value.join(" "));
14106          }
14107          break;
14108        case "dataId":
14109          break;
14110        case "id":
14111          html.setAttribute("data-element-id", value);
14112          break;
14113        case "style":
14114          Object.assign(html.style, value);
14115          break;
14116        case "textContent":
14117          html.textContent = value;
14118          break;
14119        default:
14120          if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
14121            html.setAttribute(key, value);
14122          }
14123      }
14124    }
14125    if (isHTMLAnchorElement) {
14126      linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
14127    }
14128    if (storage && attributes.dataId) {
14129      this.setupStorage(html, attributes.dataId, element, storage);
14130    }
14131  }
14132  static render(parameters) {
14133    const storage = parameters.annotationStorage;
14134    const linkService = parameters.linkService;
14135    const root = parameters.xfaHtml;
14136    const intent = parameters.intent || "display";
14137    const rootHtml = document.createElement(root.name);
14138    if (root.attributes) {
14139      this.setAttributes({
14140        html: rootHtml,
14141        element: root,
14142        intent,
14143        linkService
14144      });
14145    }
14146    const stack = [[root, -1, rootHtml]];
14147    const rootDiv = parameters.div;
14148    rootDiv.append(rootHtml);
14149    if (parameters.viewport) {
14150      const transform = `matrix(${parameters.viewport.transform.join(",")})`;
14151      rootDiv.style.transform = transform;
14152    }
14153    if (intent !== "richText") {
14154      rootDiv.setAttribute("class", "xfaLayer xfaFont");
14155    }
14156    const textDivs = [];
14157    while (stack.length > 0) {
14158      const [parent, i, html] = stack.at(-1);
14159      if (i + 1 === parent.children.length) {
14160        stack.pop();
14161        continue;
14162      }
14163      const child = parent.children[++stack.at(-1)[1]];
14164      if (child === null) {
14165        continue;
14166      }
14167      const {
14168        name
14169      } = child;
14170      if (name === "#text") {
14171        const node = document.createTextNode(child.value);
14172        textDivs.push(node);
14173        html.append(node);
14174        continue;
14175      }
14176      let childHtml;
14177      if (child?.attributes?.xmlns) {
14178        childHtml = document.createElementNS(child.attributes.xmlns, name);
14179      } else {
14180        childHtml = document.createElement(name);
14181      }
14182      html.append(childHtml);
14183      if (child.attributes) {
14184        this.setAttributes({
14185          html: childHtml,
14186          element: child,
14187          storage,
14188          intent,
14189          linkService
14190        });
14191      }
14192      if (child.children && child.children.length > 0) {
14193        stack.push([child, -1, childHtml]);
14194      } else if (child.value) {
14195        const node = document.createTextNode(child.value);
14196        if (_xfa_text.XfaText.shouldBuildText(name)) {
14197          textDivs.push(node);
14198        }
14199        childHtml.append(node);
14200      }
14201    }
14202    for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
14203      el.setAttribute("readOnly", true);
14204    }
14205    return {
14206      textDivs
14207    };
14208  }
14209  static update(parameters) {
14210    const transform = `matrix(${parameters.viewport.transform.join(",")})`;
14211    parameters.div.style.transform = transform;
14212    parameters.div.hidden = false;
14213  }
14214}
14215exports.XfaLayer = XfaLayer;
14216
14217/***/ }),
14218/* 35 */
14219/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
14220
14221
14222
14223Object.defineProperty(exports, "__esModule", ({
14224  value: true
14225}));
14226exports.SVGGraphics = void 0;
14227var _display_utils = __w_pdfjs_require__(6);
14228var _util = __w_pdfjs_require__(1);
14229var _is_node = __w_pdfjs_require__(10);
14230let SVGGraphics = class {
14231  constructor() {
14232    (0, _util.unreachable)("Not implemented: SVGGraphics");
14233  }
14234};
14235exports.SVGGraphics = SVGGraphics;
14236{
14237  const SVG_DEFAULTS = {
14238    fontStyle: "normal",
14239    fontWeight: "normal",
14240    fillColor: "#000000"
14241  };
14242  const XML_NS = "http://www.w3.org/XML/1998/namespace";
14243  const XLINK_NS = "http://www.w3.org/1999/xlink";
14244  const LINE_CAP_STYLES = ["butt", "round", "square"];
14245  const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
14246  const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
14247    if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
14248      return URL.createObjectURL(new Blob([data], {
14249        type: contentType
14250      }));
14251    }
14252    const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
14253    let buffer = `data:${contentType};base64,`;
14254    for (let i = 0, ii = data.length; i < ii; i += 3) {
14255      const b1 = data[i] & 0xff;
14256      const b2 = data[i + 1] & 0xff;
14257      const b3 = data[i + 2] & 0xff;
14258      const d1 = b1 >> 2,
14259        d2 = (b1 & 3) << 4 | b2 >> 4;
14260      const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
14261      const d4 = i + 2 < ii ? b3 & 0x3f : 64;
14262      buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
14263    }
14264    return buffer;
14265  };
14266  const convertImgDataToPng = function () {
14267    const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
14268    const CHUNK_WRAPPER_SIZE = 12;
14269    const crcTable = new Int32Array(256);
14270    for (let i = 0; i < 256; i++) {
14271      let c = i;
14272      for (let h = 0; h < 8; h++) {
14273        if (c & 1) {
14274          c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
14275        } else {
14276          c = c >> 1 & 0x7fffffff;
14277        }
14278      }
14279      crcTable[i] = c;
14280    }
14281    function crc32(data, start, end) {
14282      let crc = -1;
14283      for (let i = start; i < end; i++) {
14284        const a = (crc ^ data[i]) & 0xff;
14285        const b = crcTable[a];
14286        crc = crc >>> 8 ^ b;
14287      }
14288      return crc ^ -1;
14289    }
14290    function writePngChunk(type, body, data, offset) {
14291      let p = offset;
14292      const len = body.length;
14293      data[p] = len >> 24 & 0xff;
14294      data[p + 1] = len >> 16 & 0xff;
14295      data[p + 2] = len >> 8 & 0xff;
14296      data[p + 3] = len & 0xff;
14297      p += 4;
14298      data[p] = type.charCodeAt(0) & 0xff;
14299      data[p + 1] = type.charCodeAt(1) & 0xff;
14300      data[p + 2] = type.charCodeAt(2) & 0xff;
14301      data[p + 3] = type.charCodeAt(3) & 0xff;
14302      p += 4;
14303      data.set(body, p);
14304      p += body.length;
14305      const crc = crc32(data, offset + 4, p);
14306      data[p] = crc >> 24 & 0xff;
14307      data[p + 1] = crc >> 16 & 0xff;
14308      data[p + 2] = crc >> 8 & 0xff;
14309      data[p + 3] = crc & 0xff;
14310    }
14311    function adler32(data, start, end) {
14312      let a = 1;
14313      let b = 0;
14314      for (let i = start; i < end; ++i) {
14315        a = (a + (data[i] & 0xff)) % 65521;
14316        b = (b + a) % 65521;
14317      }
14318      return b << 16 | a;
14319    }
14320    function deflateSync(literals) {
14321      if (!_is_node.isNodeJS) {
14322        return deflateSyncUncompressed(literals);
14323      }
14324      try {
14325        let input;
14326        if (parseInt(process.versions.node) >= 8) {
14327          input = literals;
14328        } else {
14329          input = Buffer.from(literals);
14330        }
14331        const output = require("zlib").deflateSync(input, {
14332          level: 9
14333        });
14334        return output instanceof Uint8Array ? output : new Uint8Array(output);
14335      } catch (e) {
14336        (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
14337      }
14338      return deflateSyncUncompressed(literals);
14339    }
14340    function deflateSyncUncompressed(literals) {
14341      let len = literals.length;
14342      const maxBlockLength = 0xffff;
14343      const deflateBlocks = Math.ceil(len / maxBlockLength);
14344      const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
14345      let pi = 0;
14346      idat[pi++] = 0x78;
14347      idat[pi++] = 0x9c;
14348      let pos = 0;
14349      while (len > maxBlockLength) {
14350        idat[pi++] = 0x00;
14351        idat[pi++] = 0xff;
14352        idat[pi++] = 0xff;
14353        idat[pi++] = 0x00;
14354        idat[pi++] = 0x00;
14355        idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
14356        pi += maxBlockLength;
14357        pos += maxBlockLength;
14358        len -= maxBlockLength;
14359      }
14360      idat[pi++] = 0x01;
14361      idat[pi++] = len & 0xff;
14362      idat[pi++] = len >> 8 & 0xff;
14363      idat[pi++] = ~len & 0xffff & 0xff;
14364      idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
14365      idat.set(literals.subarray(pos), pi);
14366      pi += literals.length - pos;
14367      const adler = adler32(literals, 0, literals.length);
14368      idat[pi++] = adler >> 24 & 0xff;
14369      idat[pi++] = adler >> 16 & 0xff;
14370      idat[pi++] = adler >> 8 & 0xff;
14371      idat[pi++] = adler & 0xff;
14372      return idat;
14373    }
14374    function encode(imgData, kind, forceDataSchema, isMask) {
14375      const width = imgData.width;
14376      const height = imgData.height;
14377      let bitDepth, colorType, lineSize;
14378      const bytes = imgData.data;
14379      switch (kind) {
14380        case _util.ImageKind.GRAYSCALE_1BPP:
14381          colorType = 0;
14382          bitDepth = 1;
14383          lineSize = width + 7 >> 3;
14384          break;
14385        case _util.ImageKind.RGB_24BPP:
14386          colorType = 2;
14387          bitDepth = 8;
14388          lineSize = width * 3;
14389          break;
14390        case _util.ImageKind.RGBA_32BPP:
14391          colorType = 6;
14392          bitDepth = 8;
14393          lineSize = width * 4;
14394          break;
14395        default:
14396          throw new Error("invalid format");
14397      }
14398      const literals = new Uint8Array((1 + lineSize) * height);
14399      let offsetLiterals = 0,
14400        offsetBytes = 0;
14401      for (let y = 0; y < height; ++y) {
14402        literals[offsetLiterals++] = 0;
14403        literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
14404        offsetBytes += lineSize;
14405        offsetLiterals += lineSize;
14406      }
14407      if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
14408        offsetLiterals = 0;
14409        for (let y = 0; y < height; y++) {
14410          offsetLiterals++;
14411          for (let i = 0; i < lineSize; i++) {
14412            literals[offsetLiterals++] ^= 0xff;
14413          }
14414        }
14415      }
14416      const ihdr = new Uint8Array([width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, colorType, 0x00, 0x00, 0x00]);
14417      const idat = deflateSync(literals);
14418      const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
14419      const data = new Uint8Array(pngLength);
14420      let offset = 0;
14421      data.set(PNG_HEADER, offset);
14422      offset += PNG_HEADER.length;
14423      writePngChunk("IHDR", ihdr, data, offset);
14424      offset += CHUNK_WRAPPER_SIZE + ihdr.length;
14425      writePngChunk("IDATA", idat, data, offset);
14426      offset += CHUNK_WRAPPER_SIZE + idat.length;
14427      writePngChunk("IEND", new Uint8Array(0), data, offset);
14428      return createObjectURL(data, "image/png", forceDataSchema);
14429    }
14430    return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
14431      const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
14432      return encode(imgData, kind, forceDataSchema, isMask);
14433    };
14434  }();
14435  class SVGExtraState {
14436    constructor() {
14437      this.fontSizeScale = 1;
14438      this.fontWeight = SVG_DEFAULTS.fontWeight;
14439      this.fontSize = 0;
14440      this.textMatrix = _util.IDENTITY_MATRIX;
14441      this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
14442      this.leading = 0;
14443      this.textRenderingMode = _util.TextRenderingMode.FILL;
14444      this.textMatrixScale = 1;
14445      this.x = 0;
14446      this.y = 0;
14447      this.lineX = 0;
14448      this.lineY = 0;
14449      this.charSpacing = 0;
14450      this.wordSpacing = 0;
14451      this.textHScale = 1;
14452      this.textRise = 0;
14453      this.fillColor = SVG_DEFAULTS.fillColor;
14454      this.strokeColor = "#000000";
14455      this.fillAlpha = 1;
14456      this.strokeAlpha = 1;
14457      this.lineWidth = 1;
14458      this.lineJoin = "";
14459      this.lineCap = "";
14460      this.miterLimit = 0;
14461      this.dashArray = [];
14462      this.dashPhase = 0;
14463      this.dependencies = [];
14464      this.activeClipUrl = null;
14465      this.clipGroup = null;
14466      this.maskId = "";
14467    }
14468    clone() {
14469      return Object.create(this);
14470    }
14471    setCurrentPoint(x, y) {
14472      this.x = x;
14473      this.y = y;
14474    }
14475  }
14476  function opListToTree(opList) {
14477    let opTree = [];
14478    const tmp = [];
14479    for (const opListElement of opList) {
14480      if (opListElement.fn === "save") {
14481        opTree.push({
14482          fnId: 92,
14483          fn: "group",
14484          items: []
14485        });
14486        tmp.push(opTree);
14487        opTree = opTree.at(-1).items;
14488        continue;
14489      }
14490      if (opListElement.fn === "restore") {
14491        opTree = tmp.pop();
14492      } else {
14493        opTree.push(opListElement);
14494      }
14495    }
14496    return opTree;
14497  }
14498  function pf(value) {
14499    if (Number.isInteger(value)) {
14500      return value.toString();
14501    }
14502    const s = value.toFixed(10);
14503    let i = s.length - 1;
14504    if (s[i] !== "0") {
14505      return s;
14506    }
14507    do {
14508      i--;
14509    } while (s[i] === "0");
14510    return s.substring(0, s[i] === "." ? i : i + 1);
14511  }
14512  function pm(m) {
14513    if (m[4] === 0 && m[5] === 0) {
14514      if (m[1] === 0 && m[2] === 0) {
14515        if (m[0] === 1 && m[3] === 1) {
14516          return "";
14517        }
14518        return `scale(${pf(m[0])} ${pf(m[3])})`;
14519      }
14520      if (m[0] === m[3] && m[1] === -m[2]) {
14521        const a = Math.acos(m[0]) * 180 / Math.PI;
14522        return `rotate(${pf(a)})`;
14523      }
14524    } else {
14525      if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
14526        return `translate(${pf(m[4])} ${pf(m[5])})`;
14527      }
14528    }
14529    return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
14530  }
14531  let clipCount = 0;
14532  let maskCount = 0;
14533  let shadingCount = 0;
14534  exports.SVGGraphics = SVGGraphics = class {
14535    constructor(commonObjs, objs, forceDataSchema = false) {
14536      (0, _display_utils.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future.");
14537      this.svgFactory = new _display_utils.DOMSVGFactory();
14538      this.current = new SVGExtraState();
14539      this.transformMatrix = _util.IDENTITY_MATRIX;
14540      this.transformStack = [];
14541      this.extraStack = [];
14542      this.commonObjs = commonObjs;
14543      this.objs = objs;
14544      this.pendingClip = null;
14545      this.pendingEOFill = false;
14546      this.embedFonts = false;
14547      this.embeddedFonts = Object.create(null);
14548      this.cssStyle = null;
14549      this.forceDataSchema = !!forceDataSchema;
14550      this._operatorIdMapping = [];
14551      for (const op in _util.OPS) {
14552        this._operatorIdMapping[_util.OPS[op]] = op;
14553      }
14554    }
14555    getObject(data, fallback = null) {
14556      if (typeof data === "string") {
14557        return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
14558      }
14559      return fallback;
14560    }
14561    save() {
14562      this.transformStack.push(this.transformMatrix);
14563      const old = this.current;
14564      this.extraStack.push(old);
14565      this.current = old.clone();
14566    }
14567    restore() {
14568      this.transformMatrix = this.transformStack.pop();
14569      this.current = this.extraStack.pop();
14570      this.pendingClip = null;
14571      this.tgrp = null;
14572    }
14573    group(items) {
14574      this.save();
14575      this.executeOpTree(items);
14576      this.restore();
14577    }
14578    loadDependencies(operatorList) {
14579      const fnArray = operatorList.fnArray;
14580      const argsArray = operatorList.argsArray;
14581      for (let i = 0, ii = fnArray.length; i < ii; i++) {
14582        if (fnArray[i] !== _util.OPS.dependency) {
14583          continue;
14584        }
14585        for (const obj of argsArray[i]) {
14586          const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
14587          const promise = new Promise(resolve => {
14588            objsPool.get(obj, resolve);
14589          });
14590          this.current.dependencies.push(promise);
14591        }
14592      }
14593      return Promise.all(this.current.dependencies);
14594    }
14595    transform(a, b, c, d, e, f) {
14596      const transformMatrix = [a, b, c, d, e, f];
14597      this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
14598      this.tgrp = null;
14599    }
14600    getSVG(operatorList, viewport) {
14601      this.viewport = viewport;
14602      const svgElement = this._initialize(viewport);
14603      return this.loadDependencies(operatorList).then(() => {
14604        this.transformMatrix = _util.IDENTITY_MATRIX;
14605        this.executeOpTree(this.convertOpList(operatorList));
14606        return svgElement;
14607      });
14608    }
14609    convertOpList(operatorList) {
14610      const operatorIdMapping = this._operatorIdMapping;
14611      const argsArray = operatorList.argsArray;
14612      const fnArray = operatorList.fnArray;
14613      const opList = [];
14614      for (let i = 0, ii = fnArray.length; i < ii; i++) {
14615        const fnId = fnArray[i];
14616        opList.push({
14617          fnId,
14618          fn: operatorIdMapping[fnId],
14619          args: argsArray[i]
14620        });
14621      }
14622      return opListToTree(opList);
14623    }
14624    executeOpTree(opTree) {
14625      for (const opTreeElement of opTree) {
14626        const fn = opTreeElement.fn;
14627        const fnId = opTreeElement.fnId;
14628        const args = opTreeElement.args;
14629        switch (fnId | 0) {
14630          case _util.OPS.beginText:
14631            this.beginText();
14632            break;
14633          case _util.OPS.dependency:
14634            break;
14635          case _util.OPS.setLeading:
14636            this.setLeading(args);
14637            break;
14638          case _util.OPS.setLeadingMoveText:
14639            this.setLeadingMoveText(args[0], args[1]);
14640            break;
14641          case _util.OPS.setFont:
14642            this.setFont(args);
14643            break;
14644          case _util.OPS.showText:
14645            this.showText(args[0]);
14646            break;
14647          case _util.OPS.showSpacedText:
14648            this.showText(args[0]);
14649            break;
14650          case _util.OPS.endText:
14651            this.endText();
14652            break;
14653          case _util.OPS.moveText:
14654            this.moveText(args[0], args[1]);
14655            break;
14656          case _util.OPS.setCharSpacing:
14657            this.setCharSpacing(args[0]);
14658            break;
14659          case _util.OPS.setWordSpacing:
14660            this.setWordSpacing(args[0]);
14661            break;
14662          case _util.OPS.setHScale:
14663            this.setHScale(args[0]);
14664            break;
14665          case _util.OPS.setTextMatrix:
14666            this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
14667            break;
14668          case _util.OPS.setTextRise:
14669            this.setTextRise(args[0]);
14670            break;
14671          case _util.OPS.setTextRenderingMode:
14672            this.setTextRenderingMode(args[0]);
14673            break;
14674          case _util.OPS.setLineWidth:
14675            this.setLineWidth(args[0]);
14676            break;
14677          case _util.OPS.setLineJoin:
14678            this.setLineJoin(args[0]);
14679            break;
14680          case _util.OPS.setLineCap:
14681            this.setLineCap(args[0]);
14682            break;
14683          case _util.OPS.setMiterLimit:
14684            this.setMiterLimit(args[0]);
14685            break;
14686          case _util.OPS.setFillRGBColor:
14687            this.setFillRGBColor(args[0], args[1], args[2]);
14688            break;
14689          case _util.OPS.setStrokeRGBColor:
14690            this.setStrokeRGBColor(args[0], args[1], args[2]);
14691            break;
14692          case _util.OPS.setStrokeColorN:
14693            this.setStrokeColorN(args);
14694            break;
14695          case _util.OPS.setFillColorN:
14696            this.setFillColorN(args);
14697            break;
14698          case _util.OPS.shadingFill:
14699            this.shadingFill(args[0]);
14700            break;
14701          case _util.OPS.setDash:
14702            this.setDash(args[0], args[1]);
14703            break;
14704          case _util.OPS.setRenderingIntent:
14705            this.setRenderingIntent(args[0]);
14706            break;
14707          case _util.OPS.setFlatness:
14708            this.setFlatness(args[0]);
14709            break;
14710          case _util.OPS.setGState:
14711            this.setGState(args[0]);
14712            break;
14713          case _util.OPS.fill:
14714            this.fill();
14715            break;
14716          case _util.OPS.eoFill:
14717            this.eoFill();
14718            break;
14719          case _util.OPS.stroke:
14720            this.stroke();
14721            break;
14722          case _util.OPS.fillStroke:
14723            this.fillStroke();
14724            break;
14725          case _util.OPS.eoFillStroke:
14726            this.eoFillStroke();
14727            break;
14728          case _util.OPS.clip:
14729            this.clip("nonzero");
14730            break;
14731          case _util.OPS.eoClip:
14732            this.clip("evenodd");
14733            break;
14734          case _util.OPS.paintSolidColorImageMask:
14735            this.paintSolidColorImageMask();
14736            break;
14737          case _util.OPS.paintImageXObject:
14738            this.paintImageXObject(args[0]);
14739            break;
14740          case _util.OPS.paintInlineImageXObject:
14741            this.paintInlineImageXObject(args[0]);
14742            break;
14743          case _util.OPS.paintImageMaskXObject:
14744            this.paintImageMaskXObject(args[0]);
14745            break;
14746          case _util.OPS.paintFormXObjectBegin:
14747            this.paintFormXObjectBegin(args[0], args[1]);
14748            break;
14749          case _util.OPS.paintFormXObjectEnd:
14750            this.paintFormXObjectEnd();
14751            break;
14752          case _util.OPS.closePath:
14753            this.closePath();
14754            break;
14755          case _util.OPS.closeStroke:
14756            this.closeStroke();
14757            break;
14758          case _util.OPS.closeFillStroke:
14759            this.closeFillStroke();
14760            break;
14761          case _util.OPS.closeEOFillStroke:
14762            this.closeEOFillStroke();
14763            break;
14764          case _util.OPS.nextLine:
14765            this.nextLine();
14766            break;
14767          case _util.OPS.transform:
14768            this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
14769            break;
14770          case _util.OPS.constructPath:
14771            this.constructPath(args[0], args[1]);
14772            break;
14773          case _util.OPS.endPath:
14774            this.endPath();
14775            break;
14776          case 92:
14777            this.group(opTreeElement.items);
14778            break;
14779          default:
14780            (0, _util.warn)(`Unimplemented operator ${fn}`);
14781            break;
14782        }
14783      }
14784    }
14785    setWordSpacing(wordSpacing) {
14786      this.current.wordSpacing = wordSpacing;
14787    }
14788    setCharSpacing(charSpacing) {
14789      this.current.charSpacing = charSpacing;
14790    }
14791    nextLine() {
14792      this.moveText(0, this.current.leading);
14793    }
14794    setTextMatrix(a, b, c, d, e, f) {
14795      const current = this.current;
14796      current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
14797      current.textMatrixScale = Math.hypot(a, b);
14798      current.x = current.lineX = 0;
14799      current.y = current.lineY = 0;
14800      current.xcoords = [];
14801      current.ycoords = [];
14802      current.tspan = this.svgFactory.createElement("svg:tspan");
14803      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
14804      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
14805      current.tspan.setAttributeNS(null, "y", pf(-current.y));
14806      current.txtElement = this.svgFactory.createElement("svg:text");
14807      current.txtElement.append(current.tspan);
14808    }
14809    beginText() {
14810      const current = this.current;
14811      current.x = current.lineX = 0;
14812      current.y = current.lineY = 0;
14813      current.textMatrix = _util.IDENTITY_MATRIX;
14814      current.lineMatrix = _util.IDENTITY_MATRIX;
14815      current.textMatrixScale = 1;
14816      current.tspan = this.svgFactory.createElement("svg:tspan");
14817      current.txtElement = this.svgFactory.createElement("svg:text");
14818      current.txtgrp = this.svgFactory.createElement("svg:g");
14819      current.xcoords = [];
14820      current.ycoords = [];
14821    }
14822    moveText(x, y) {
14823      const current = this.current;
14824      current.x = current.lineX += x;
14825      current.y = current.lineY += y;
14826      current.xcoords = [];
14827      current.ycoords = [];
14828      current.tspan = this.svgFactory.createElement("svg:tspan");
14829      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
14830      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
14831      current.tspan.setAttributeNS(null, "y", pf(-current.y));
14832    }
14833    showText(glyphs) {
14834      const current = this.current;
14835      const font = current.font;
14836      const fontSize = current.fontSize;
14837      if (fontSize === 0) {
14838        return;
14839      }
14840      const fontSizeScale = current.fontSizeScale;
14841      const charSpacing = current.charSpacing;
14842      const wordSpacing = current.wordSpacing;
14843      const fontDirection = current.fontDirection;
14844      const textHScale = current.textHScale * fontDirection;
14845      const vertical = font.vertical;
14846      const spacingDir = vertical ? 1 : -1;
14847      const defaultVMetrics = font.defaultVMetrics;
14848      const widthAdvanceScale = fontSize * current.fontMatrix[0];
14849      let x = 0;
14850      for (const glyph of glyphs) {
14851        if (glyph === null) {
14852          x += fontDirection * wordSpacing;
14853          continue;
14854        }
14854 else if (typeof glyph === "number") {
14855          x += spacingDir * glyph * fontSize / 1000;
14856          continue;
14857        }
14858        const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
14859        const character = glyph.fontChar;
14860        let scaledX, scaledY;
14861        let width = glyph.width;
14862        if (vertical) {
14863          let vx;
14864          const vmetric = glyph.vmetric || defaultVMetrics;
14865          vx = glyph.vmetric ? vmetric[1] : width * 0.5;
14866          vx = -vx * widthAdvanceScale;
14867          const vy = vmetric[2] * widthAdvanceScale;
14868          width = vmetric ? -vmetric[0] : width;
14869          scaledX = vx / fontSizeScale;
14870          scaledY = (x + vy) / fontSizeScale;
14871        } else {
14872          scaledX = x / fontSizeScale;
14873          scaledY = 0;
14874        }
14875        if (glyph.isInFont || font.missingFile) {
14876          current.xcoords.push(current.x + scaledX);
14877          if (vertical) {
14878            current.ycoords.push(-current.y + scaledY);
14879          }
14880          current.tspan.textContent += character;
14881        } else {}
14882        let charWidth;
14883        if (vertical) {
14884          charWidth = width * widthAdvanceScale - spacing * fontDirection;
14885        } else {
14886          charWidth = width * widthAdvanceScale + spacing * fontDirection;
14887        }
14888        x += charWidth;
14889      }
14890      current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
14891      if (vertical) {
14892        current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
14893      } else {
14894        current.tspan.setAttributeNS(null, "y", pf(-current.y));
14895      }
14896      if (vertical) {
14897        current.y -= x;
14898      } else {
14899        current.x += x * textHScale;
14900      }
14901      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
14902      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
14903      if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
14904        current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
14905      }
14906      if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
14907        current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
14908      }
14909      const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
14910      if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
14911        if (current.fillColor !== SVG_DEFAULTS.fillColor) {
14912          current.tspan.setAttributeNS(null, "fill", current.fillColor);
14913        }
14914        if (current.fillAlpha < 1) {
14915          current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
14916        }
14917      } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
14918        current.tspan.setAttributeNS(null, "fill", "transparent");
14919      } else {
14920        current.tspan.setAttributeNS(null, "fill", "none");
14921      }
14922      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
14923        const lineWidthScale = 1 / (current.textMatrixScale || 1);
14924        this._setStrokeAttributes(current.tspan, lineWidthScale);
14925      }
14926      let textMatrix = current.textMatrix;
14927      if (current.textRise !== 0) {
14928        textMatrix = textMatrix.slice();
14929        textMatrix[5] += current.textRise;
14930      }
14931      current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
14932      current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
14933      current.txtElement.append(current.tspan);
14934      current.txtgrp.append(current.txtElement);
14935      this._ensureTransformGroup().append(current.txtElement);
14936    }
14937    setLeadingMoveText(x, y) {
14938      this.setLeading(-y);
14939      this.moveText(x, y);
14940    }
14941    addFontStyle(fontObj) {
14942      if (!fontObj.data) {
14943        throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
14944      }
14945      if (!this.cssStyle) {
14946        this.cssStyle = this.svgFactory.createElement("svg:style");
14947        this.cssStyle.setAttributeNS(null, "type", "text/css");
14948        this.defs.append(this.cssStyle);
14949      }
14950      const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
14951      this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
14952    }
14953    setFont(details) {
14954      const current = this.current;
14955      const fontObj = this.commonObjs.get(details[0]);
14956      let size = details[1];
14957      current.font = fontObj;
14958      if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
14959        this.addFontStyle(fontObj);
14960        this.embeddedFonts[fontObj.loadedName] = fontObj;
14961      }
14962      current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
14963      let bold = "normal";
14964      if (fontObj.black) {
14965        bold = "900";
14966      } else if (fontObj.bold) {
14967        bold = "bold";
14968      }
14969      const italic = fontObj.italic ? "italic" : "normal";
14970      if (size < 0) {
14971        size = -size;
14972        current.fontDirection = -1;
14973      } else {
14974        current.fontDirection = 1;
14975      }
14976      current.fontSize = size;
14977      current.fontFamily = fontObj.loadedName;
14978      current.fontWeight = bold;
14979      current.fontStyle = italic;
14980      current.tspan = this.svgFactory.createElement("svg:tspan");
14981      current.tspan.setAttributeNS(null, "y", pf(-current.y));
14982      current.xcoords = [];
14983      current.ycoords = [];
14984    }
14985    endText() {
14986      const current = this.current;
14987      if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
14988        current.element = current.txtElement;
14989        this.clip("nonzero");
14990        this.endPath();
14991      }
14992    }
14993    setLineWidth(width) {
14994      if (width > 0) {
14995        this.current.lineWidth = width;
14996      }
14997    }
14998    setLineCap(style) {
14999      this.current.lineCap = LINE_CAP_STYLES[style];
15000    }
15001    setLineJoin(style) {
15002      this.current.lineJoin = LINE_JOIN_STYLES[style];
15003    }
15004    setMiterLimit(limit) {
15005      this.current.miterLimit = limit;
15006    }
15007    setStrokeAlpha(strokeAlpha) {
15008      this.current.strokeAlpha = strokeAlpha;
15009    }
15010    setStrokeRGBColor(r, g, b) {
15011      this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
15012    }
15013    setFillAlpha(fillAlpha) {
15014      this.current.fillAlpha = fillAlpha;
15015    }
15016    setFillRGBColor(r, g, b) {
15017      this.current.fillColor = _util.Util.makeHexColor(r, g, b);
15018      this.current.tspan = this.svgFactory.createElement("svg:tspan");
15019      this.current.xcoords = [];
15020      this.current.ycoords = [];
15021    }
15022    setStrokeColorN(args) {
15023      this.current.strokeColor = this._makeColorN_Pattern(args);
15024    }
15025    setFillColorN(args) {
15026      this.current.fillColor = this._makeColorN_Pattern(args);
15027    }
15028    shadingFill(args) {
15029      const width = this.viewport.width;
15030      const height = this.viewport.height;
15031      const inv = _util.Util.inverseTransform(this.transformMatrix);
15032      const bl = _util.Util.applyTransform([0, 0], inv);
15033      const br = _util.Util.applyTransform([0, height], inv);
15034      const ul = _util.Util.applyTransform([width, 0], inv);
15035      const ur = _util.Util.applyTransform([width, height], inv);
15036      const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
15037      const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
15038      const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
15039      const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
15040      const rect = this.svgFactory.createElement("svg:rect");
15041      rect.setAttributeNS(null, "x", x0);
15042      rect.setAttributeNS(null, "y", y0);
15043      rect.setAttributeNS(null, "width", x1 - x0);
15044      rect.setAttributeNS(null, "height", y1 - y0);
15045      rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
15046      if (this.current.fillAlpha < 1) {
15047        rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
15048      }
15049      this._ensureTransformGroup().append(rect);
15050    }
15051    _makeColorN_Pattern(args) {
15052      if (args[0] === "TilingPattern") {
15053        return this._makeTilingPattern(args);
15054      }
15055      return this._makeShadingPattern(args);
15056    }
15057    _makeTilingPattern(args) {
15058      const color = args[1];
15059      const operatorList = args[2];
15060      const matrix = args[3] || _util.IDENTITY_MATRIX;
15061      const [x0, y0, x1, y1] = args[4];
15062      const xstep = args[5];
15063      const ystep = args[6];
15064      const paintType = args[7];
15065      const tilingId = `shading${shadingCount++}`;
15066      const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0
15066], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
15067      const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
15068      const txstep = xstep * xscale;
15069      const tystep = ystep * yscale;
15070      const tiling = this.svgFactory.createElement("svg:pattern");
15071      tiling.setAttributeNS(null, "id", tilingId);
15072      tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
15073      tiling.setAttributeNS(null, "width", txstep);
15074      tiling.setAttributeNS(null, "height", tystep);
15075      tiling.setAttributeNS(null, "x", `${tx0}`);
15076      tiling.setAttributeNS(null, "y", `${ty0}`);
15077      const svg = this.svg;
15078      const transformMatrix = this.transformMatrix;
15079      const fillColor = this.current.fillColor;
15080      const strokeColor = this.current.strokeColor;
15081      const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
15082      this.svg = bbox;
15083      this.transformMatrix = matrix;
15084      if (paintType === 2) {
15085        const cssColor = _util.Util.makeHexColor(...color);
15086        this.current.fillColor = cssColor;
15087        this.current.strokeColor = cssColor;
15088      }
15089      this.executeOpTree(this.convertOpList(operatorList));
15090      this.svg = svg;
15091      this.transformMatrix = transformMatrix;
15092      this.current.fillColor = fillColor;
15093      this.current.strokeColor = strokeColor;
15094      tiling.append(bbox.childNodes[0]);
15095      this.defs.append(tiling);
15096      return `url(#${tilingId})`;
15097    }
15098    _makeShadingPattern(args) {
15099      if (typeof args === "string") {
15100        args = this.objs.get(args);
15101      }
15102      switch (args[0]) {
15103        case "RadialAxial":
15104          const shadingId = `shading${shadingCount++}`;
15105          const colorStops = args[3];
15106          let gradient;
15107          switch (args[1]) {
15108            case "axial":
15109              const point0 = args[4];
15110              const point1 = args[5];
15111              gradient = this.svgFactory.createElement("svg:linearGradient");
15112              gradient.setAttributeNS(null, "id", shadingId);
15113              gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
15114              gradient.setAttributeNS(null, "x1", point0[0]);
15115              gradient.setAttributeNS(null, "y1", point0[1]);
15116              gradient.setAttributeNS(null, "x2", point1[0]);
15117              gradient.setAttributeNS(null, "y2", point1[1]);
15118              break;
15119            case "radial":
15120              const focalPoint = args[4];
15121              const circlePoint = args[5];
15122              const focalRadius = args[6];
15123              const circleRadius = args[7];
15124              gradient = this.svgFactory.createElement("svg:radialGradient");
15125              gradient.setAttributeNS(null, "id", shadingId);
15126              gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
15127              gradient.setAttributeNS(null, "cx", circlePoint[0]);
15128              gradient.setAttributeNS(null, "cy", circlePoint[1]);
15129              gradient.setAttributeNS(null, "r", circleRadius);
15130              gradient.setAttributeNS(null, "fx", focalPoint[0]);
15131              gradient.setAttributeNS(null, "fy", focalPoint[1]);
15132              gradient.setAttributeNS(null, "fr", focalRadius);
15133              break;
15134            default:
15135              throw new Error(`Unknown RadialAxial type: ${args[1]}`);
15136          }
15137          for (const colorStop of colorStops) {
15138            const stop = this.svgFactory.createElement("svg:stop");
15139            stop.setAttributeNS(null, "offset", colorStop[0]);
15140            stop.setAttributeNS(null, "stop-color", colorStop[1]);
15141            gradient.append(stop);
15142          }
15143          this.defs.append(gradient);
15144          return `url(#${shadingId})`;
15145        case "Mesh":
15146          (0, _util.warn)("Unimplemented pattern Mesh");
15147          return null;
15148        case "Dummy":
15149          return "hotpink";
15150        default:
15151          throw new Error(`Unknown IR type: ${args[0]}`);
15152      }
15153    }
15154    setDash(dashArray, dashPhase) {
15155      this.current.dashArray = dashArray;
15156      this.current.dashPhase = dashPhase;
15157    }
15158    constructPath(ops, args) {
15159      const current = this.current;
15160      let x = current.x,
15161        y = current.y;
15162      let d = [];
15163      let j = 0;
15164      for (const op of ops) {
15165        switch (op | 0) {
15166          case _util.OPS.rectangle:
15167            x = args[j++];
15168            y = args[j++];
15169            const width = args[j++];
15170            const height = args[j++];
15171            const xw = x + width;
15172            const yh = y + height;
15173            d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
15174            break;
15175          case _util.OPS.moveTo:
15176            x = args[j++];
15177            y = args[j++];
15178            d.push("M", pf(x), pf(y));
15179            break;
15180          case _util.OPS.lineTo:
15181            x = args[j++];
15182            y = args[j++];
15183            d.push("L", pf(x), pf(y));
15184            break;
15185          case _util.OPS.curveTo:
15186            x = args[j + 4];
15187            y = args[j + 5];
15188            d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
15189            j += 6;
15190            break;
15191          case _util.OPS.curveTo2:
15192            d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
15193            x = args[j + 2];
15194            y = args[j + 3];
15195            j += 4;
15196            break;
15197          case _util.OPS.curveTo3:
15198            x = args[j + 2];
15199            y = args[j + 3];
15200            d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
15201            j += 4;
15202            break;
15203          case _util.OPS.closePath:
15204            d.push("Z");
15205            break;
15206        }
15207      }
15208      d = d.join(" ");
15209      if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
15210        d = current.path.getAttributeNS(null, "d") + d;
15211      } else {
15212        current.path = this.svgFactory.createElement("svg:path");
15213        this._ensureTransformGroup().append(current.path);
15214      }
15215      current.path.setAttributeNS(null, "d", d);
15216      current.path.setAttributeNS(null, "fill", "none");
15217      current.element = current.path;
15218      current.setCurrentPoint(x, y);
15219    }
15220    endPath() {
15221      const current = this.current;
15222      current.path = null;
15223      if (!this.pendingClip) {
15224        return;
15225      }
15226      if (!current.element) {
15227        this.pendingClip = null;
15228        return;
15229      }
15230      const clipId = `clippath${clipCount++}`;
15231      const clipPath = this.svgFactory.createElement("svg:clipPath");
15232      clipPath.setAttributeNS(null, "id", clipId);
15233      clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
15234      const clipElement = current.element.cloneNode(true);
15235      if (this.pendingClip === "evenodd") {
15236        clipElement.setAttributeNS(null, "clip-rule", "evenodd");
15237      } else {
15238        clipElement.setAttributeNS(null, "clip-rule", "nonzero");
15239      }
15240      this.pendingClip = null;
15241      clipPath.append(clipElement);
15242      this.defs.append(clipPath);
15243      if (current.activeClipUrl) {
15244        current.clipGroup = null;
15245        for (const prev of this.extraStack) {
15246          prev.clipGroup = null;
15247        }
15248        clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
15249      }
15250      current.activeClipUrl = `url(#${clipId})`;
15251      this.tgrp = null;
15252    }
15253    clip(type) {
15254      this.pendingClip = type;
15255    }
15256    closePath() {
15257      const current = this.current;
15258      if (current.path) {
15259        const d = `${current.path.getAttributeNS(null, "d")}Z`;
15260        current.path.setAttributeNS(null, "d", d);
15261      }
15262    }
15263    setLeading(leading) {
15264      this.current.leading = -leading;
15265    }
15266    setTextRise(textRise) {
15267      this.current.textRise = textRise;
15268    }
15269    setTextRenderingMode(textRenderingMode) {
15270      this.current.textRenderingMode = textRenderingMode;
15271    }
15272    setHScale(scale) {
15273      this.current.textHScale = scale / 100;
15274    }
15275    setRenderingIntent(intent) {}
15276    setFlatness(flatness) {}
15277    setGState(states) {
15278      for (const [key, value] of states) {
15279        switch (key) {
15280          case "LW":
15281            this.setLineWidth(value);
15282            break;
15283          case "LC":
15284            this.setLineCap(value);
15285            break;
15286          case "LJ":
15287            this.setLineJoin(value);
15288            break;
15289          case "ML":
15290            this.setMiterLimit(value);
15291            break;
15292          case "D":
15293            this.setDash(value[0], value[1]);
15294            break;
15295          case "RI":
15296            this.setRenderingIntent(value);
15297            break;
15298          case "FL":
15299            this.setFlatness(value);
15300            break;
15301          case "Font":
15302            this.setFont(value);
15303            break;
15304          case "CA":
15305            this.setStrokeAlpha(value);
15306            break;
15307          case "ca":
15308            this.setFillAlpha(value);
15309            break;
15310          default:
15311            (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
15312            break;
15313        }
15314      }
15315    }
15316    fill() {
15317      const current = this.current;
15318      if (current.element) {
15319        current.element.setAttributeNS(null, "fill", current.fillColor);
15320        current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
15321        this.endPath();
15322      }
15323    }
15324    stroke() {
15325      const current = this.current;
15326      if (current.element) {
15327        this._setStrokeAttributes(current.element);
15328        current.element.setAttributeNS(null, "fill", "none");
15329        this.endPath();
15330      }
15331    }
15332    _setStrokeAttributes(element, lineWidthScale = 1) {
15333      const current = this.current;
15334      let dashArray = current.dashArray;
15335      if (lineWidthScale !== 1 && dashArray.length > 0) {
15336        dashArray = dashArray.map(function (value) {
15337          return lineWidthScale * value;
15338        });
15339      }
15340      element.setAttributeNS(null, "stroke", current.strokeColor);
15341      element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
15342      element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
15343      element.setAttributeNS(null, "stroke-linecap", current.lineCap);
15344      element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
15345      element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
15346      element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
15347      element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
15348    }
15349    eoFill() {
15350      this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
15351      this.fill();
15352    }
15353    fillStroke() {
15354      this.stroke();
15355      this.fill();
15356    }
15357    eoFillStroke() {
15358      this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
15359      this.fillStroke();
15360    }
15361    closeStroke() {
15362      this.closePath();
15363      this.stroke();
15364    }
15365    closeFillStroke() {
15366      this.closePath();
15367      this.fillStroke();
15368    }
15369    closeEOFillStroke() {
15370      this.closePath();
15371      this.eoFillStroke();
15372    }
15373    paintSolidColorImageMask() {
15374      const rect = this.svgFactory.createElement("svg:rect");
15375      rect.setAttributeNS(null, "x", "0");
15376      rect.setAttributeNS(null, "y", "0");
15377      rect.setAttributeNS(null, "width", "1px");
15378      rect.setAttributeNS(null, "height", "1px");
15379      rect.setAttributeNS(null, "fill", this.current.fillColor);
15380      this._ensureTransformGroup().append(rect);
15381    }
15382    paintImageXObject(objId) {
15383      const imgData = this.getObject(objId);
15384      if (!imgData) {
15385        (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
15386        return;
15387      }
15388      this.paintInlineImageXObject(imgData);
15389    }
15390    paintInlineImageXObject(imgData, mask) {
15391      const width = imgData.width;
15392      const height = imgData.height;
15393      const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
15394      const cliprect = this.svgFactory.createElement("svg:rect");
15395      cliprect.setAttributeNS(null, "x", "0");
15396      cliprect.setAttributeNS(null, "y", "0");
15397      cliprect.setAttributeNS(null, "width", pf(width));
15398      cliprect.setAttributeNS(null, "height", pf(height));
15399      this.current.element = cliprect;
15400      this.clip("nonzero");
15401      const imgEl = this.svgFactory.createElement("svg:image");
15402      imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
15403      imgEl.setAttributeNS(null, "x", "0");
15404      imgEl.setAttributeNS(null, "y", pf(-height));
15405      imgEl.setAttributeNS(null, "width", pf(width) + "px");
15406      imgEl.setAttributeNS(null, "height", pf(height) + "px");
15407      imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
15408      if (mask) {
15409        mask.append(imgEl);
15410      } else {
15411        this._ensureTransformGroup().append(imgEl);
15412      }
15413    }
15414    paintImageMaskXObject(img) {
15415      const imgData = this.getObject(img.data, img);
15416      if (imgData.bitmap) {
15417        (0, _util.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, " + "ensure that the `isOffscreenCanvasSupported` API parameter is disabled.");
15418        return;
15419      }
15420      const current = this.current;
15421      const width = imgData.width;
15422      const height = imgData.height;
15423      const fillColor = current.fillColor;
15424      current.maskId = `mask${maskCount++}`;
15425      const mask = this.svgFactory.createElement("svg:mask");
15426      mask.setAttributeNS(null, "id", current.maskId);
15427      const rect = this.svgFactory.createElement("svg:rect");
15428      rect.setAttributeNS(null, "x", "0");
15429      rect.setAttributeNS(null, "y", "0");
15430      rect.setAttributeNS(null, "width", pf(width));
15431      rect.setAttributeNS(null, "height", pf(height));
15432      rect.setAttributeNS(null, "fill", fillColor);
15433      rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
15434      this.defs.append(mask);
15435      this._ensureTransformGroup().append(rect);
15436      this.paintInlineImageXObject(imgData, mask);
15437    }
15438    paintFormXObjectBegin(matrix, bbox) {
15439      if (Array.isArray(matrix) && matrix.length === 6) {
15440        this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
15441      }
15442      if (bbox) {
15443        const width = bbox[2] - bbox[0];
15444        const height = bbox[3] - bbox[1];
15445        const cliprect = this.svgFactory.createElement("svg:rect");
15446        cliprect.setAttributeNS(null, "x", bbox[0]);
15447        cliprect.setAttributeNS(null, "y", bbox[1]);
15448        cliprect.setAttributeNS(null, "width", pf(width));
15449        cliprect.setAttributeNS(null, "height", pf(height));
15450        this.current.element = cliprect;
15451        this.clip("nonzero");
15452        this.endPath();
15453      }
15454    }
15455    paintFormXObjectEnd() {}
15456    _initialize(viewport) {
15457      const svg = this.svgFactory.create(viewport.width, viewport.height);
15458      const definitions = this.svgFactory.createElement("svg:defs");
15459      svg.append(definitions);
15460      this.defs = definitions;
15461      const rootGroup = this.svgFactory.createElement("svg:g");
15462      rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
15463      svg.append(rootGroup);
15464      this.svg = rootGroup;
15465      return svg;
15466    }
15467    _ensureClipGroup() {
15468      if (!this.current.clipGroup) {
15469        const clipGroup = this.svgFactory.createElement("svg:g");
15470        clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
15471        this.svg.append(clipGroup);
15472        this.current.clipGroup = clipGroup;
15473      }
15474      return this.current.clipGroup;
15475    }
15476    _ensureTransformGroup() {
15477      if (!this.tgrp) {
15478        this.tgrp = this.svgFactory.createElement("svg:g");
15479        this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
15480        if (this.current.activeClipUrl) {
15481          this._ensureClipGroup().append(this.tgrp);
15482        } else {
15483          this.svg.append(this.tgrp);
15484        }
15485      }
15486      return this.tgrp;
15487    }
15488  };
15489}
15490
15491/***/ })
15492/******/ 	]);
15493/************************************************************************/
15494/******/ 	// The module cache
15495/******/ 	var __webpack_module_cache__ = {};
15496/******/ 	
15497/******/ 	// The require function
15498/******/ 	function __w_pdfjs_require__(moduleId) {
15499/******/ 		// Check if module is in cache
15500/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
15501/******/ 		if (cachedModule !== undefined) {
15502/******/ 			return cachedModule.exports;
15503/******/ 		}
15504/******/ 		// Create a new module (and put it into the cache)
15505/******/ 		var module = __webpack_module_cache__[moduleId] = {
15506/******/ 			// no module.id needed
15507/******/ 			// no module.loaded needed
15508/******/ 			exports: {}
15509/******/ 		};
15510/******/ 	
15511/******/ 		// Execute the module function
15512/******/ 		__webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
15513/******/ 	
15514/******/ 		// Return the exports of the module
15515/******/ 		return module.exports;
15516/******/ 	}
15517/******/ 	
15518/************************************************************************/
15519var __webpack_exports__ = {};
15520// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
15521(() => {
15522var exports = __webpack_exports__;
15523
15524
15525Object.defineProperty(exports, "__esModule", ({
15526  value: true
15527}));
15528Object.defineProperty(exports, "AbortException", ({
15529  enumerable: true,
15530  get: function () {
15531    return _util.AbortException;
15532  }
15533}));
15534Object.defineProperty(exports, "AnnotationEditorLayer", ({
15535  enumerable: true,
15536  get: function () {
15537    return _annotation_editor_layer.AnnotationEditorLayer;
15538  }
15539}));
15540Object.defineProperty(exports, "AnnotationEditorParamsType", ({
15541  enumerable: true,
15542  get: function () {
15543    return _util.AnnotationEditorParamsType;
15544  }
15545}));
15546Object.defineProperty(exports, "AnnotationEditorType", ({
15547  enumerable: true,
15548  get: function () {
15549    return _util.AnnotationEditorType;
15550  }
15551}));
15552Object.defineProperty(exports, "AnnotationEditorUIManager", ({
15553  enumerable: true,
15554  get: function () {
15555    return _tools.AnnotationEditorUIManager;
15556  }
15557}));
15558Object.defineProperty(exports, "AnnotationLayer", ({
15559  enumerable: true,
15560  get: function () {
15561    return _annotation_layer.AnnotationLayer;
15562  }
15563}));
15564Object.defineProperty(exports, "AnnotationMode", ({
15565  enumerable: true,
15566  get: function () {
15567    return _util.AnnotationMode;
15568  }
15569}));
15570Object.defineProperty(exports, "CMapCompressionType", ({
15571  enumerable: true,
15572  get: function () {
15573    return _util.CMapCompressionType;
15574  }
15575}));
15576Object.defineProperty(exports, "FeatureTest", ({
15577  enumerable: true,
15578  get: function () {
15579    return _util.FeatureTest;
15580  }
15581}));
15582Object.defineProperty(exports, "GlobalWorkerOptions", ({
15583  enumerable: true,
15584  get: function () {
15585    return _worker_options.GlobalWorkerOptions;
15586  }
15587}));
15588Object.defineProperty(exports, "InvalidPDFException", ({
15589  enumerable: true,
15590  get: function () {
15591    return _util.InvalidPDFException;
15592  }
15593}));
15594Object.defineProperty(exports, "MissingPDFException", ({
15595  enumerable: true,
15596  get: function () {
15597    return _util.MissingPDFException;
15598  }
15599}));
15600Object.defineProperty(exports, "OPS", ({
15601  enumerable: true,
15602  get: function () {
15603    return _util.OPS;
15604  }
15605}));
15606Object.defineProperty(exports, "PDFDataRangeTransport", ({
15607  enumerable: true,
15608  get: function () {
15609    return _api.PDFDataRangeTransport;
15610  }
15611}));
15612Object.defineProperty(exports, "PDFDateString", ({
15613  enumerable: true,
15614  get: function () {
15615    return _display_utils.PDFDateString;
15616  }
15617}));
15618Object.defineProperty(exports, "PDFWorker", ({
15619  enumerable: true,
15620  get: function () {
15621    return _api.PDFWorker;
15622  }
15623}));
15624Object.defineProperty(exports, "PasswordResponses", ({
15625  enumerable: true,
15626  get: function () {
15627    return _util.PasswordResponses;
15628  }
15629}));
15630Object.defineProperty(exports, "PermissionFlag", ({
15631  enumerable: true,
15632  get: function () {
15633    return _util.PermissionFlag;
15634  }
15635}));
15636Object.defineProperty(exports, "PixelsPerInch", ({
15637  enumerable: true,
15638  get: function () {
15639    return _display_utils.PixelsPerInch;
15640  }
15641}));
15642Object.defineProperty(exports, "RenderingCancelledException", ({
15643  enumerable: true,
15644  get: function () {
15645    return _display_utils.RenderingCancelledException;
15646  }
15647}));
15648Object.defineProperty(exports, "SVGGraphics", ({
15649  enumerable: true,
15650  get: function () {
15651    return _svg.SVGGraphics;
15652  }
15653}));
15654Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
15655  enumerable: true,
15656  get: function () {
15657    return _util.UNSUPPORTED_FEATURES;
15658  }
15659}));
15660Object.defineProperty(exports, "UnexpectedResponseException", ({
15661  enumerable: true,
15662  get: function () {
15663    return _util.UnexpectedResponseException;
15664  }
15665}));
15666Object.defineProperty(exports, "Util", ({
15667  enumerable: true,
15668  get: function () {
15669    return _util.Util;
15670  }
15671}));
15672Object.defineProperty(exports, "VerbosityLevel", ({
15673  enumerable: true,
15674  get: function () {
15675    return _util.VerbosityLevel;
15676  }
15677}));
15678Object.defineProperty(exports, "XfaLayer", ({
15679  enumerable: true,
15680  get: function () {
15681    return _xfa_layer.XfaLayer;
15682  }
15683}));
15684Object.defineProperty(exports, "build", ({
15685  enumerable: true,
15686  get: function () {
15687    return _api.build;
15688  }
15689}));
15690Object.defineProperty(exports, "createPromiseCapability", ({
15691  enumerable: true,
15692  get: function () {
15693    return _util.createPromiseCapability;
15694  }
15695}));
15696Object.defineProperty(exports, "createValidAbsoluteUrl", ({
15697  enumerable: true,
15698  get: function () {
15699    return _util.createValidAbsoluteUrl;
15700  }
15701}));
15702Object.defineProperty(exports, "getDocument", ({
15703  enumerable: true,
15704  get: function () {
15705    return _api.getDocument;
15706  }
15707}));
15708Object.defineProperty(exports, "getFilenameFromUrl", ({
15709  enumerable: true,
15710  get: function () {
15711    return _display_utils.getFilenameFromUrl;
15712  }
15713}));
15714Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
15715  enumerable: true,
15716  get: function () {
15717    return _display_utils.getPdfFilenameFromUrl;
15718  }
15719}));
15720Object.defineProperty(exports, "getXfaPageViewport", ({
15721  enumerable: true,
15722  get: function () {
15723    return _display_utils.getXfaPageViewport;
15724  }
15725}));
15726Object.defineProperty(exports, "isDataScheme", ({
15727  enumerable: true,
15728  get: function () {
15729    return _display_utils.isDataScheme;
15730  }
15731}));
15732Object.defineProperty(exports, "isPdfFile", ({
15733  enumerable: true,
15734  get: function () {
15735    return _display_utils.isPdfFile;
15736  }
15737}));
15738Object.defineProperty(exports, "loadScript", ({
15739  enumerable: true,
15740  get: function () {
15741    return _display_utils.loadScript;
15742  }
15743}));
15744Object.defineProperty(exports, "renderTextLayer", ({
15745  enumerable: true,
15746  get: function () {
15747    return _text_layer.renderTextLayer;
15748  }
15749}));
15750Object.defineProperty(exports, "setLayerDimensions", ({
15751  enumerable: true,
15752  get: function () {
15753    return _display_utils.setLayerDimensions;
15754  }
15755}));
15756Object.defineProperty(exports, "shadow", ({
15757  enumerable: true,
15758  get: function () {
15759    return _util.shadow;
15760  }
15761}));
15762Object.defineProperty(exports, "updateTextLayer", ({
15763  enumerable: true,
15764  get: function () {
15765    return _text_layer.updateTextLayer;
15766  }
15767}));
15768Object.defineProperty(exports, "version", ({
15769  enumerable: true,
15770  get: function () {
15771    return _api.version;
15772  }
15773}));
15774var _util = __w_pdfjs_require__(1);
15775var _api = __w_pdfjs_require__(2);
15776var _display_utils = __w_pdfjs_require__(6);
15777var _text_layer = __w_pdfjs_require__(26);
15778var _annotation_editor_layer = __w_pdfjs_require__(27);
15779var _tools = __w_pdfjs_require__(5);
15780var _annotation_layer = __w_pdfjs_require__(32);
15781var _worker_options = __w_pdfjs_require__(14);
15782var _svg = __w_pdfjs_require__(35);
15783var _xfa_layer = __w_pdfjs_require__(34);
15784const pdfjsVersion = '3.4.120';
15785const pdfjsBuild = 'af6414988';
15786})();
15787
15788/******/ 	return __webpack_exports__;
15789/******/ })()
15790;
15791});
15792//# sourceMappingURL=pdf.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.