Bug 1946184 - Fix computing the CSD margin right after calling HideWindowChrome(...
[gecko.git] / toolkit / components / pdfjs / content / build / pdf.scripting.mjs
blobcb68218488b5042e2190768b1f334b918b8d120f
1 /**
2  * @licstart The following is the entire license notice for the
3  * JavaScript code in this page
4  *
5  * Copyright 2024 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  */
23 var __webpack_exports__ = {};
25 ;// ./src/scripting_api/constants.js
26 const Border = Object.freeze({
27   s: "solid",
28   d: "dashed",
29   b: "beveled",
30   i: "inset",
31   u: "underline"
32 });
33 const Cursor = Object.freeze({
34   visible: 0,
35   hidden: 1,
36   delay: 2
37 });
38 const Display = Object.freeze({
39   visible: 0,
40   hidden: 1,
41   noPrint: 2,
42   noView: 3
43 });
44 const Font = Object.freeze({
45   Times: "Times-Roman",
46   TimesB: "Times-Bold",
47   TimesI: "Times-Italic",
48   TimesBI: "Times-BoldItalic",
49   Helv: "Helvetica",
50   HelvB: "Helvetica-Bold",
51   HelvI: "Helvetica-Oblique",
52   HelvBI: "Helvetica-BoldOblique",
53   Cour: "Courier",
54   CourB: "Courier-Bold",
55   CourI: "Courier-Oblique",
56   CourBI: "Courier-BoldOblique",
57   Symbol: "Symbol",
58   ZapfD: "ZapfDingbats",
59   KaGo: "HeiseiKakuGo-W5-UniJIS-UCS2-H",
60   KaMi: "HeiseiMin-W3-UniJIS-UCS2-H"
61 });
62 const Highlight = Object.freeze({
63   n: "none",
64   i: "invert",
65   p: "push",
66   o: "outline"
67 });
68 const Position = Object.freeze({
69   textOnly: 0,
70   iconOnly: 1,
71   iconTextV: 2,
72   textIconV: 3,
73   iconTextH: 4,
74   textIconH: 5,
75   overlay: 6
76 });
77 const ScaleHow = Object.freeze({
78   proportional: 0,
79   anamorphic: 1
80 });
81 const ScaleWhen = Object.freeze({
82   always: 0,
83   never: 1,
84   tooBig: 2,
85   tooSmall: 3
86 });
87 const Style = Object.freeze({
88   ch: "check",
89   cr: "cross",
90   di: "diamond",
91   ci: "circle",
92   st: "star",
93   sq: "square"
94 });
95 const Trans = Object.freeze({
96   blindsH: "BlindsHorizontal",
97   blindsV: "BlindsVertical",
98   boxI: "BoxIn",
99   boxO: "BoxOut",
100   dissolve: "Dissolve",
101   glitterD: "GlitterDown",
102   glitterR: "GlitterRight",
103   glitterRD: "GlitterRightDown",
104   random: "Random",
105   replace: "Replace",
106   splitHI: "SplitHorizontalIn",
107   splitHO: "SplitHorizontalOut",
108   splitVI: "SplitVerticalIn",
109   splitVO: "SplitVerticalOut",
110   wipeD: "WipeDown",
111   wipeL: "WipeLeft",
112   wipeR: "WipeRight",
113   wipeU: "WipeUp"
115 const ZoomType = Object.freeze({
116   none: "NoVary",
117   fitP: "FitPage",
118   fitW: "FitWidth",
119   fitH: "FitHeight",
120   fitV: "FitVisibleWidth",
121   pref: "Preferred",
122   refW: "ReflowWidth"
124 const GlobalConstants = Object.freeze({
125   IDS_GREATER_THAN: "Invalid value: must be greater than or equal to % s.",
126   IDS_GT_AND_LT: "Invalid value: must be greater than or equal to % s " + "and less than or equal to % s.",
127   IDS_LESS_THAN: "Invalid value: must be less than or equal to % s.",
128   IDS_INVALID_MONTH: "** Invalid **",
129   IDS_INVALID_DATE: "Invalid date / time: please ensure that the date / time exists. Field",
130   IDS_INVALID_DATE2: " should match format ",
131   IDS_INVALID_VALUE: "The value entered does not match the format of the field",
132   IDS_AM: "am",
133   IDS_PM: "pm",
134   IDS_MONTH_INFO: "January[1] February[2] March[3] April[4] May[5] " + "June[6] July[7] August[8] September[9] October[10] " + "November[11] December[12] Sept[9] Jan[1] Feb[2] Mar[3] " + "Apr[4] Jun[6] Jul[7] Aug[8] Sep[9] Oct[10] Nov[11] Dec[12]",
135   IDS_STARTUP_CONSOLE_MSG: "** ^ _ ^ **",
136   RE_NUMBER_ENTRY_DOT_SEP: ["[+-]?\\d*\\.?\\d*"],
137   RE_NUMBER_COMMIT_DOT_SEP: ["[+-]?\\d+(\\.\\d+)?", "[+-]?\\.\\d+", "[+-]?\\d+\\."],
138   RE_NUMBER_ENTRY_COMMA_SEP: ["[+-]?\\d*,?\\d*"],
139   RE_NUMBER_COMMIT_COMMA_SEP: ["[+-]?\\d+([.,]\\d+)?", "[+-]?[.,]\\d+", "[+-]?\\d+[.,]"],
140   RE_ZIP_ENTRY: ["\\d{0,5}"],
141   RE_ZIP_COMMIT: ["\\d{5}"],
142   RE_ZIP4_ENTRY: ["\\d{0,5}(\\.|[- ])?\\d{0,4}"],
143   RE_ZIP4_COMMIT: ["\\d{5}(\\.|[- ])?\\d{4}"],
144   RE_PHONE_ENTRY: ["\\d{0,3}(\\.|[- ])?\\d{0,3}(\\.|[- ])?\\d{0,4}", "\\(\\d{0,3}", "\\(\\d{0,3}\\)(\\.|[- ])?\\d{0,3}(\\.|[- ])?\\d{0,4}", "\\(\\d{0,3}(\\.|[- ])?\\d{0,3}(\\.|[- ])?\\d{0,4}", "\\d{0,3}\\)(\\.|[- ])?\\d{0,3}(\\.|[- ])?\\d{0,4}", "011(\\.|[- \\d])*"],
145   RE_PHONE_COMMIT: ["\\d{3}(\\.|[- ])?\\d{4}", "\\d{3}(\\.|[- ])?\\d{3}(\\.|[- ])?\\d{4}", "\\(\\d{3}\\)(\\.|[- ])?\\d{3}(\\.|[- ])?\\d{4}", "011(\\.|[- \\d])*"],
146   RE_SSN_ENTRY: ["\\d{0,3}(\\.|[- ])?\\d{0,2}(\\.|[- ])?\\d{0,4}"],
147   RE_SSN_COMMIT: ["\\d{3}(\\.|[- ])?\\d{2}(\\.|[- ])?\\d{4}"]
150 ;// ./src/scripting_api/common.js
151 const FieldType = {
152   none: 0,
153   number: 1,
154   percent: 2,
155   date: 3,
156   time: 4
158 function createActionsMap(actions) {
159   const actionsMap = new Map();
160   if (actions) {
161     for (const [eventType, actionsForEvent] of Object.entries(actions)) {
162       actionsMap.set(eventType, actionsForEvent);
163     }
164   }
165   return actionsMap;
167 function getFieldType(actions) {
168   let format = actions.get("Format");
169   if (!format) {
170     return FieldType.none;
171   }
172   format = format[0];
173   format = format.trim();
174   if (format.startsWith("AFNumber_")) {
175     return FieldType.number;
176   }
177   if (format.startsWith("AFPercent_")) {
178     return FieldType.percent;
179   }
180   if (format.startsWith("AFDate_")) {
181     return FieldType.date;
182   }
183   if (format.startsWith("AFTime_")) {
184     return FieldType.time;
185   }
186   return FieldType.none;
189 ;// ./src/shared/scripting_utils.js
190 function makeColorComp(n) {
191   return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
193 function scaleAndClamp(x) {
194   return Math.max(0, Math.min(255, 255 * x));
196 class ColorConverters {
197   static CMYK_G([c, y, m, k]) {
198     return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
199   }
200   static G_CMYK([g]) {
201     return ["CMYK", 0, 0, 0, 1 - g];
202   }
203   static G_RGB([g]) {
204     return ["RGB", g, g, g];
205   }
206   static G_rgb([g]) {
207     g = scaleAndClamp(g);
208     return [g, g, g];
209   }
210   static G_HTML([g]) {
211     const G = makeColorComp(g);
212     return `#${G}${G}${G}`;
213   }
214   static RGB_G([r, g, b]) {
215     return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
216   }
217   static RGB_rgb(color) {
218     return color.map(scaleAndClamp);
219   }
220   static RGB_HTML(color) {
221     return `#${color.map(makeColorComp).join("")}`;
222   }
223   static T_HTML() {
224     return "#00000000";
225   }
226   static T_rgb() {
227     return [null];
228   }
229   static CMYK_RGB([c, y, m, k]) {
230     return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
231   }
232   static CMYK_rgb([c, y, m, k]) {
233     return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))];
234   }
235   static CMYK_HTML(components) {
236     const rgb = this.CMYK_RGB(components).slice(1);
237     return this.RGB_HTML(rgb);
238   }
239   static RGB_CMYK([r, g, b]) {
240     const c = 1 - r;
241     const m = 1 - g;
242     const y = 1 - b;
243     const k = Math.min(c, m, y);
244     return ["CMYK", c, m, y, k];
245   }
248 ;// ./src/scripting_api/pdf_object.js
249 class PDFObject {
250   constructor(data) {
251     this._expandos = Object.create(null);
252     this._send = data.send || null;
253     this._id = data.id || null;
254   }
257 ;// ./src/scripting_api/color.js
260 class Color extends PDFObject {
261   constructor() {
262     super({});
263     this.transparent = ["T"];
264     this.black = ["G", 0];
265     this.white = ["G", 1];
266     this.red = ["RGB", 1, 0, 0];
267     this.green = ["RGB", 0, 1, 0];
268     this.blue = ["RGB", 0, 0, 1];
269     this.cyan = ["CMYK", 1, 0, 0, 0];
270     this.magenta = ["CMYK", 0, 1, 0, 0];
271     this.yellow = ["CMYK", 0, 0, 1, 0];
272     this.dkGray = ["G", 0.25];
273     this.gray = ["G", 0.5];
274     this.ltGray = ["G", 0.75];
275   }
276   static _isValidSpace(cColorSpace) {
277     return typeof cColorSpace === "string" && (cColorSpace === "T" || cColorSpace === "G" || cColorSpace === "RGB" || cColorSpace === "CMYK");
278   }
279   static _isValidColor(colorArray) {
280     if (!Array.isArray(colorArray) || colorArray.length === 0) {
281       return false;
282     }
283     const space = colorArray[0];
284     if (!Color._isValidSpace(space)) {
285       return false;
286     }
287     switch (space) {
288       case "T":
289         if (colorArray.length !== 1) {
290           return false;
291         }
292         break;
293       case "G":
294         if (colorArray.length !== 2) {
295           return false;
296         }
297         break;
298       case "RGB":
299         if (colorArray.length !== 4) {
300           return false;
301         }
302         break;
303       case "CMYK":
304         if (colorArray.length !== 5) {
305           return false;
306         }
307         break;
308       default:
309         return false;
310     }
311     return colorArray.slice(1).every(c => typeof c === "number" && c >= 0 && c <= 1);
312   }
313   static _getCorrectColor(colorArray) {
314     return Color._isValidColor(colorArray) ? colorArray : ["G", 0];
315   }
316   convert(colorArray, cColorSpace) {
317     if (!Color._isValidSpace(cColorSpace)) {
318       return this.black;
319     }
320     if (cColorSpace === "T") {
321       return ["T"];
322     }
323     colorArray = Color._getCorrectColor(colorArray);
324     if (colorArray[0] === cColorSpace) {
325       return colorArray;
326     }
327     if (colorArray[0] === "T") {
328       return this.convert(this.black, cColorSpace);
329     }
330     return ColorConverters[`${colorArray[0]}_${cColorSpace}`](colorArray.slice(1));
331   }
332   equal(colorArray1, colorArray2) {
333     colorArray1 = Color._getCorrectColor(colorArray1);
334     colorArray2 = Color._getCorrectColor(colorArray2);
335     if (colorArray1[0] === "T" || colorArray2[0] === "T") {
336       return colorArray1[0] === "T" && colorArray2[0] === "T";
337     }
338     if (colorArray1[0] !== colorArray2[0]) {
339       colorArray2 = this.convert(colorArray2, colorArray1[0]);
340     }
341     return colorArray1.slice(1).every((c, i) => c === colorArray2[i + 1]);
342   }
345 ;// ./src/scripting_api/field.js
349 class Field extends PDFObject {
350   constructor(data) {
351     super(data);
352     this.alignment = data.alignment || "left";
353     this.borderStyle = data.borderStyle || "";
354     this.buttonAlignX = data.buttonAlignX || 50;
355     this.buttonAlignY = data.buttonAlignY || 50;
356     this.buttonFitBounds = data.buttonFitBounds;
357     this.buttonPosition = data.buttonPosition;
358     this.buttonScaleHow = data.buttonScaleHow;
359     this.ButtonScaleWhen = data.buttonScaleWhen;
360     this.calcOrderIndex = data.calcOrderIndex;
361     this.comb = data.comb;
362     this.commitOnSelChange = data.commitOnSelChange;
363     this.currentValueIndices = data.currentValueIndices;
364     this.defaultStyle = data.defaultStyle;
365     this.defaultValue = data.defaultValue;
366     this.doNotScroll = data.doNotScroll;
367     this.doNotSpellCheck = data.doNotSpellCheck;
368     this.delay = data.delay;
369     this.display = data.display;
370     this.doc = data.doc.wrapped;
371     this.editable = data.editable;
372     this.exportValues = data.exportValues;
373     this.fileSelect = data.fileSelect;
374     this.hidden = data.hidden;
375     this.highlight = data.highlight;
376     this.lineWidth = data.lineWidth;
377     this.multiline = data.multiline;
378     this.multipleSelection = !!data.multipleSelection;
379     this.name = data.name;
380     this.password = data.password;
381     this.print = data.print;
382     this.radiosInUnison = data.radiosInUnison;
383     this.readonly = data.readonly;
384     this.rect = data.rect;
385     this.required = data.required;
386     this.richText = data.richText;
387     this.richValue = data.richValue;
388     this.style = data.style;
389     this.submitName = data.submitName;
390     this.textFont = data.textFont;
391     this.textSize = data.textSize;
392     this.type = data.type;
393     this.userName = data.userName;
394     this._actions = createActionsMap(data.actions);
395     this._browseForFileToSubmit = data.browseForFileToSubmit || null;
396     this._buttonCaption = null;
397     this._buttonIcon = null;
398     this._charLimit = data.charLimit;
399     this._children = null;
400     this._currentValueIndices = data.currentValueIndices || 0;
401     this._document = data.doc;
402     this._fieldPath = data.fieldPath;
403     this._fillColor = data.fillColor || ["T"];
404     this._isChoice = Array.isArray(data.items);
405     this._items = data.items || [];
406     this._hasValue = data.hasOwnProperty("value");
407     this._page = data.page || 0;
408     this._strokeColor = data.strokeColor || ["G", 0];
409     this._textColor = data.textColor || ["G", 0];
410     this._value = null;
411     this._kidIds = data.kidIds || null;
412     this._fieldType = getFieldType(this._actions);
413     this._siblings = data.siblings || null;
414     this._rotation = data.rotation || 0;
415     this._globalEval = data.globalEval;
416     this._appObjects = data.appObjects;
417     this.value = data.value || "";
418   }
419   get currentValueIndices() {
420     if (!this._isChoice) {
421       return 0;
422     }
423     return this._currentValueIndices;
424   }
425   set currentValueIndices(indices) {
426     if (!this._isChoice) {
427       return;
428     }
429     if (!Array.isArray(indices)) {
430       indices = [indices];
431     }
432     if (!indices.every(i => typeof i === "number" && Number.isInteger(i) && i >= 0 && i < this.numItems)) {
433       return;
434     }
435     indices.sort();
436     if (this.multipleSelection) {
437       this._currentValueIndices = indices;
438       this._value = [];
439       indices.forEach(i => {
440         this._value.push(this._items[i].displayValue);
441       });
442     } else if (indices.length > 0) {
443       indices = indices.splice(1, indices.length - 1);
444       this._currentValueIndices = indices[0];
445       this._value = this._items[this._currentValueIndices];
446     }
447     this._send({
448       id: this._id,
449       indices
450     });
451   }
452   get fillColor() {
453     return this._fillColor;
454   }
455   set fillColor(color) {
456     if (Color._isValidColor(color)) {
457       this._fillColor = color;
458     }
459   }
460   get bgColor() {
461     return this.fillColor;
462   }
463   set bgColor(color) {
464     this.fillColor = color;
465   }
466   get charLimit() {
467     return this._charLimit;
468   }
469   set charLimit(limit) {
470     if (typeof limit !== "number") {
471       throw new Error("Invalid argument value");
472     }
473     this._charLimit = Math.max(0, Math.floor(limit));
474   }
475   get numItems() {
476     if (!this._isChoice) {
477       throw new Error("Not a choice widget");
478     }
479     return this._items.length;
480   }
481   set numItems(_) {
482     throw new Error("field.numItems is read-only");
483   }
484   get strokeColor() {
485     return this._strokeColor;
486   }
487   set strokeColor(color) {
488     if (Color._isValidColor(color)) {
489       this._strokeColor = color;
490     }
491   }
492   get borderColor() {
493     return this.strokeColor;
494   }
495   set borderColor(color) {
496     this.strokeColor = color;
497   }
498   get page() {
499     return this._page;
500   }
501   set page(_) {
502     throw new Error("field.page is read-only");
503   }
504   get rotation() {
505     return this._rotation;
506   }
507   set rotation(angle) {
508     angle = Math.floor(angle);
509     if (angle % 90 !== 0) {
510       throw new Error("Invalid rotation: must be a multiple of 90");
511     }
512     angle %= 360;
513     if (angle < 0) {
514       angle += 360;
515     }
516     this._rotation = angle;
517   }
518   get textColor() {
519     return this._textColor;
520   }
521   set textColor(color) {
522     if (Color._isValidColor(color)) {
523       this._textColor = color;
524     }
525   }
526   get fgColor() {
527     return this.textColor;
528   }
529   set fgColor(color) {
530     this.textColor = color;
531   }
532   get value() {
533     return this._value;
534   }
535   set value(value) {
536     if (this._isChoice) {
537       this._setChoiceValue(value);
538       return;
539     }
540     if (value === "" || typeof value !== "string" || this._fieldType >= FieldType.date) {
541       this._originalValue = undefined;
542       this._value = value;
543       return;
544     }
545     this._originalValue = value;
546     const _value = value.trim().replace(",", ".");
547     this._value = !isNaN(_value) ? parseFloat(_value) : value;
548   }
549   _getValue() {
550     return this._originalValue ?? this.value;
551   }
552   _setChoiceValue(value) {
553     if (this.multipleSelection) {
554       if (!Array.isArray(value)) {
555         value = [value];
556       }
557       const values = new Set(value);
558       if (Array.isArray(this._currentValueIndices)) {
559         this._currentValueIndices.length = 0;
560         this._value.length = 0;
561       } else {
562         this._currentValueIndices = [];
563         this._value = [];
564       }
565       this._items.forEach((item, i) => {
566         if (values.has(item.exportValue)) {
567           this._currentValueIndices.push(i);
568           this._value.push(item.exportValue);
569         }
570       });
571     } else {
572       if (Array.isArray(value)) {
573         value = value[0];
574       }
575       const index = this._items.findIndex(({
576         exportValue
577       }) => value === exportValue);
578       if (index !== -1) {
579         this._currentValueIndices = index;
580         this._value = this._items[index].exportValue;
581       }
582     }
583   }
584   get valueAsString() {
585     return (this._value ?? "").toString();
586   }
587   set valueAsString(_) {}
588   browseForFileToSubmit() {
589     if (this._browseForFileToSubmit) {
590       this._browseForFileToSubmit();
591     }
592   }
593   buttonGetCaption(nFace = 0) {
594     if (this._buttonCaption) {
595       return this._buttonCaption[nFace];
596     }
597     return "";
598   }
599   buttonGetIcon(nFace = 0) {
600     if (this._buttonIcon) {
601       return this._buttonIcon[nFace];
602     }
603     return null;
604   }
605   buttonImportIcon(cPath = null, nPave = 0) {}
606   buttonSetCaption(cCaption, nFace = 0) {
607     if (!this._buttonCaption) {
608       this._buttonCaption = ["", "", ""];
609     }
610     this._buttonCaption[nFace] = cCaption;
611   }
612   buttonSetIcon(oIcon, nFace = 0) {
613     if (!this._buttonIcon) {
614       this._buttonIcon = [null, null, null];
615     }
616     this._buttonIcon[nFace] = oIcon;
617   }
618   checkThisBox(nWidget, bCheckIt = true) {}
619   clearItems() {
620     if (!this._isChoice) {
621       throw new Error("Not a choice widget");
622     }
623     this._items = [];
624     this._send({
625       id: this._id,
626       clear: null
627     });
628   }
629   deleteItemAt(nIdx = null) {
630     if (!this._isChoice) {
631       throw new Error("Not a choice widget");
632     }
633     if (!this.numItems) {
634       return;
635     }
636     if (nIdx === null) {
637       nIdx = Array.isArray(this._currentValueIndices) ? this._currentValueIndices[0] : this._currentValueIndices;
638       nIdx ||= 0;
639     }
640     if (nIdx < 0 || nIdx >= this.numItems) {
641       nIdx = this.numItems - 1;
642     }
643     this._items.splice(nIdx, 1);
644     if (Array.isArray(this._currentValueIndices)) {
645       let index = this._currentValueIndices.findIndex(i => i >= nIdx);
646       if (index !== -1) {
647         if (this._currentValueIndices[index] === nIdx) {
648           this._currentValueIndices.splice(index, 1);
649         }
650         for (const ii = this._currentValueIndices.length; index < ii; index++) {
651           --this._currentValueIndices[index];
652         }
653       }
654     } else if (this._currentValueIndices === nIdx) {
655       this._currentValueIndices = this.numItems > 0 ? 0 : -1;
656     } else if (this._currentValueIndices > nIdx) {
657       --this._currentValueIndices;
658     }
659     this._send({
660       id: this._id,
661       remove: nIdx
662     });
663   }
664   getItemAt(nIdx = -1, bExportValue = false) {
665     if (!this._isChoice) {
666       throw new Error("Not a choice widget");
667     }
668     if (nIdx < 0 || nIdx >= this.numItems) {
669       nIdx = this.numItems - 1;
670     }
671     const item = this._items[nIdx];
672     return bExportValue ? item.exportValue : item.displayValue;
673   }
674   getArray() {
675     if (this._kidIds) {
676       const array = [];
677       const fillArrayWithKids = kidIds => {
678         for (const id of kidIds) {
679           const obj = this._appObjects[id];
680           if (!obj) {
681             continue;
682           }
683           if (obj.obj._hasValue) {
684             array.push(obj.wrapped);
685           }
686           if (obj.obj._kidIds) {
687             fillArrayWithKids(obj.obj._kidIds);
688           }
689         }
690       };
691       fillArrayWithKids(this._kidIds);
692       return array;
693     }
694     if (this._children === null) {
695       this._children = this._document.obj._getTerminalChildren(this._fieldPath);
696     }
697     return this._children;
698   }
699   getLock() {
700     return undefined;
701   }
702   isBoxChecked(nWidget) {
703     return false;
704   }
705   isDefaultChecked(nWidget) {
706     return false;
707   }
708   insertItemAt(cName, cExport = undefined, nIdx = 0) {
709     if (!this._isChoice) {
710       throw new Error("Not a choice widget");
711     }
712     if (!cName) {
713       return;
714     }
715     if (nIdx < 0 || nIdx > this.numItems) {
716       nIdx = this.numItems;
717     }
718     if (this._items.some(({
719       displayValue
720     }) => displayValue === cName)) {
721       return;
722     }
723     if (cExport === undefined) {
724       cExport = cName;
725     }
726     const data = {
727       displayValue: cName,
728       exportValue: cExport
729     };
730     this._items.splice(nIdx, 0, data);
731     if (Array.isArray(this._currentValueIndices)) {
732       let index = this._currentValueIndices.findIndex(i => i >= nIdx);
733       if (index !== -1) {
734         for (const ii = this._currentValueIndices.length; index < ii; index++) {
735           ++this._currentValueIndices[index];
736         }
737       }
738     } else if (this._currentValueIndices >= nIdx) {
739       ++this._currentValueIndices;
740     }
741     this._send({
742       id: this._id,
743       insert: {
744         index: nIdx,
745         ...data
746       }
747     });
748   }
749   setAction(cTrigger, cScript) {
750     if (typeof cTrigger !== "string" || typeof cScript !== "string") {
751       return;
752     }
753     if (!(cTrigger in this._actions)) {
754       this._actions[cTrigger] = [];
755     }
756     this._actions[cTrigger].push(cScript);
757   }
758   setFocus() {
759     this._send({
760       id: this._id,
761       focus: true
762     });
763   }
764   setItems(oArray) {
765     if (!this._isChoice) {
766       throw new Error("Not a choice widget");
767     }
768     this._items.length = 0;
769     for (const element of oArray) {
770       let displayValue, exportValue;
771       if (Array.isArray(element)) {
772         displayValue = element[0]?.toString() || "";
773         exportValue = element[1]?.toString() || "";
774       } else {
775         displayValue = exportValue = element?.toString() || "";
776       }
777       this._items.push({
778         displayValue,
779         exportValue
780       });
781     }
782     this._currentValueIndices = 0;
783     this._send({
784       id: this._id,
785       items: this._items
786     });
787   }
788   setLock() {}
789   signatureGetModifications() {}
790   signatureGetSeedValue() {}
791   signatureInfo() {}
792   signatureSetSeedValue() {}
793   signatureSign() {}
794   signatureValidate() {}
795   _isButton() {
796     return false;
797   }
798   _reset() {
799     this.value = this.defaultValue;
800   }
801   _runActions(event) {
802     const eventName = event.name;
803     if (!this._actions.has(eventName)) {
804       return false;
805     }
806     const actions = this._actions.get(eventName);
807     try {
808       for (const action of actions) {
809         this._globalEval(action);
810       }
811     } catch (error) {
812       event.rc = false;
813       throw error;
814     }
815     return true;
816   }
818 class RadioButtonField extends Field {
819   constructor(otherButtons, data) {
820     super(data);
821     this.exportValues = [this.exportValues];
822     this._radioIds = [this._id];
823     this._radioActions = [this._actions];
824     for (const radioData of otherButtons) {
825       this.exportValues.push(radioData.exportValues);
826       this._radioIds.push(radioData.id);
827       this._radioActions.push(createActionsMap(radioData.actions));
828       if (this._value === radioData.exportValues) {
829         this._id = radioData.id;
830       }
831     }
832     this._hasBeenInitialized = true;
833     this._value = data.value || "";
834   }
835   get _siblings() {
836     return this._radioIds.filter(id => id !== this._id);
837   }
838   set _siblings(_) {}
839   get value() {
840     return this._value;
841   }
842   set value(value) {
843     if (!this._hasBeenInitialized) {
844       return;
845     }
846     if (value === null || value === undefined) {
847       this._value = "";
848     }
849     const i = this.exportValues.indexOf(value);
850     if (0 <= i && i < this._radioIds.length) {
851       this._id = this._radioIds[i];
852       this._value = value;
853     } else if (value === "Off" && this._radioIds.length === 2) {
854       const nextI = (1 + this._radioIds.indexOf(this._id)) % 2;
855       this._id = this._radioIds[nextI];
856       this._value = this.exportValues[nextI];
857     }
858   }
859   checkThisBox(nWidget, bCheckIt = true) {
860     if (nWidget < 0 || nWidget >= this._radioIds.length || !bCheckIt) {
861       return;
862     }
863     this._id = this._radioIds[nWidget];
864     this._value = this.exportValues[nWidget];
865     this._send({
866       id: this._id,
867       value: this._value
868     });
869   }
870   isBoxChecked(nWidget) {
871     return nWidget >= 0 && nWidget < this._radioIds.length && this._id === this._radioIds[nWidget];
872   }
873   isDefaultChecked(nWidget) {
874     return nWidget >= 0 && nWidget < this.exportValues.length && this.defaultValue === this.exportValues[nWidget];
875   }
876   _getExportValue(state) {
877     const i = this._radioIds.indexOf(this._id);
878     return this.exportValues[i];
879   }
880   _runActions(event) {
881     const i = this._radioIds.indexOf(this._id);
882     this._actions = this._radioActions[i];
883     return super._runActions(event);
884   }
885   _isButton() {
886     return true;
887   }
889 class CheckboxField extends RadioButtonField {
890   get value() {
891     return this._value;
892   }
893   set value(value) {
894     if (!value || value === "Off") {
895       this._value = "Off";
896     } else {
897       super.value = value;
898     }
899   }
900   _getExportValue(state) {
901     return state ? super._getExportValue(state) : "Off";
902   }
903   isBoxChecked(nWidget) {
904     if (this._value === "Off") {
905       return false;
906     }
907     return super.isBoxChecked(nWidget);
908   }
909   isDefaultChecked(nWidget) {
910     if (this.defaultValue === "Off") {
911       return this._value === "Off";
912     }
913     return super.isDefaultChecked(nWidget);
914   }
915   checkThisBox(nWidget, bCheckIt = true) {
916     if (nWidget < 0 || nWidget >= this._radioIds.length) {
917       return;
918     }
919     this._id = this._radioIds[nWidget];
920     this._value = bCheckIt ? this.exportValues[nWidget] : "Off";
921     this._send({
922       id: this._id,
923       value: this._value
924     });
925   }
928 ;// ./src/scripting_api/aform.js
930 class AForm {
931   constructor(document, app, util, color) {
932     this._document = document;
933     this._app = app;
934     this._util = util;
935     this._color = color;
936     this._dateFormats = ["m/d", "m/d/yy", "mm/dd/yy", "mm/yy", "d-mmm", "d-mmm-yy", "dd-mmm-yy", "yy-mm-dd", "mmm-yy", "mmmm-yy", "mmm d, yyyy", "mmmm d, yyyy", "m/d/yy h:MM tt", "m/d/yy HH:MM"];
937     this._timeFormats = ["HH:MM", "h:MM tt", "HH:MM:ss", "h:MM:ss tt"];
938     this._emailRegex = new RegExp("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+" + "@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?" + "(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$");
939   }
940   _mkTargetName(event) {
941     return event.target ? `[ ${event.target.name} ]` : "";
942   }
943   _parseDate(cFormat, cDate, strict = false) {
944     let date = null;
945     try {
946       date = this._util._scand(cFormat, cDate, strict);
947     } catch {}
948     if (date) {
949       return date;
950     }
951     if (strict) {
952       return null;
953     }
954     date = Date.parse(cDate);
955     return isNaN(date) ? null : new Date(date);
956   }
957   AFMergeChange(event = globalThis.event) {
958     if (event.willCommit) {
959       return event.value.toString();
960     }
961     return this._app._eventDispatcher.mergeChange(event);
962   }
963   AFParseDateEx(cString, cOrder) {
964     return this._parseDate(cOrder, cString);
965   }
966   AFExtractNums(str) {
967     if (typeof str === "number") {
968       return [str];
969     }
970     if (!str || typeof str !== "string") {
971       return null;
972     }
973     const first = str.charAt(0);
974     if (first === "." || first === ",") {
975       str = `0${str}`;
976     }
977     const numbers = str.match(/(\d+)/g);
978     if (numbers.length === 0) {
979       return null;
980     }
981     return numbers;
982   }
983   AFMakeNumber(str) {
984     if (typeof str === "number") {
985       return str;
986     }
987     if (typeof str !== "string") {
988       return null;
989     }
990     str = str.trim().replace(",", ".");
991     const number = parseFloat(str);
992     if (isNaN(number) || !isFinite(number)) {
993       return null;
994     }
995     return number;
996   }
997   AFMakeArrayFromList(string) {
998     if (typeof string === "string") {
999       return string.split(/, ?/g);
1000     }
1001     return string;
1002   }
1003   AFNumber_Format(nDec, sepStyle, negStyle, currStyle, strCurrency, bCurrencyPrepend) {
1004     const event = globalThis.event;
1005     let value = this.AFMakeNumber(event.value);
1006     if (value === null) {
1007       event.value = "";
1008       return;
1009     }
1010     const sign = Math.sign(value);
1011     const buf = [];
1012     let hasParen = false;
1013     if (sign === -1 && bCurrencyPrepend && negStyle === 0) {
1014       buf.push("-");
1015     }
1016     if ((negStyle === 2 || negStyle === 3) && sign === -1) {
1017       buf.push("(");
1018       hasParen = true;
1019     }
1020     if (bCurrencyPrepend) {
1021       buf.push(strCurrency);
1022     }
1023     sepStyle = Math.min(Math.max(0, Math.floor(sepStyle)), 4);
1024     buf.push("%,", sepStyle, ".", nDec.toString(), "f");
1025     if (!bCurrencyPrepend) {
1026       buf.push(strCurrency);
1027     }
1028     if (hasParen) {
1029       buf.push(")");
1030     }
1031     if (negStyle === 1 || negStyle === 3) {
1032       event.target.textColor = sign === 1 ? this._color.black : this._color.red;
1033     }
1034     if ((negStyle !== 0 || bCurrencyPrepend) && sign === -1) {
1035       value = -value;
1036     }
1037     const formatStr = buf.join("");
1038     event.value = this._util.printf(formatStr, value);
1039   }
1040   AFNumber_Keystroke(nDec, sepStyle, negStyle, currStyle, strCurrency, bCurrencyPrepend) {
1041     const event = globalThis.event;
1042     let value = this.AFMergeChange(event);
1043     if (!value) {
1044       return;
1045     }
1046     value = value.trim();
1047     let pattern;
1048     if (sepStyle > 1) {
1049       pattern = event.willCommit ? /^[+-]?(\d+(,\d*)?|,\d+)$/ : /^[+-]?\d*,?\d*$/;
1050     } else {
1051       pattern = event.willCommit ? /^[+-]?(\d+(\.\d*)?|\.\d+)$/ : /^[+-]?\d*\.?\d*$/;
1052     }
1053     if (!pattern.test(value)) {
1054       if (event.willCommit) {
1055         const err = `${GlobalConstants.IDS_INVALID_VALUE} ${this._mkTargetName(event)}`;
1056         this._app.alert(err);
1057       }
1058       event.rc = false;
1059     }
1060     if (event.willCommit && sepStyle > 1) {
1061       event.value = parseFloat(value.replace(",", "."));
1062     }
1063   }
1064   AFPercent_Format(nDec, sepStyle, percentPrepend = false) {
1065     if (typeof nDec !== "number") {
1066       return;
1067     }
1068     if (typeof sepStyle !== "number") {
1069       return;
1070     }
1071     if (nDec < 0) {
1072       throw new Error("Invalid nDec value in AFPercent_Format");
1073     }
1074     const event = globalThis.event;
1075     if (nDec > 512) {
1076       event.value = "%";
1077       return;
1078     }
1079     nDec = Math.floor(nDec);
1080     sepStyle = Math.min(Math.max(0, Math.floor(sepStyle)), 4);
1081     let value = this.AFMakeNumber(event.value);
1082     if (value === null) {
1083       event.value = "%";
1084       return;
1085     }
1086     const formatStr = `%,${sepStyle}.${nDec}f`;
1087     value = this._util.printf(formatStr, value * 100);
1088     event.value = percentPrepend ? `%${value}` : `${value}%`;
1089   }
1090   AFPercent_Keystroke(nDec, sepStyle) {
1091     this.AFNumber_Keystroke(nDec, sepStyle, 0, 0, "", true);
1092   }
1093   AFDate_FormatEx(cFormat) {
1094     const event = globalThis.event;
1095     const value = event.value;
1096     if (!value) {
1097       return;
1098     }
1099     const date = this._parseDate(cFormat, value);
1100     if (date !== null) {
1101       event.value = this._util.printd(cFormat, date);
1102     }
1103   }
1104   AFDate_Format(pdf) {
1105     if (pdf >= 0 && pdf < this._dateFormats.length) {
1106       this.AFDate_FormatEx(this._dateFormats[pdf]);
1107     }
1108   }
1109   AFDate_KeystrokeEx(cFormat) {
1110     const event = globalThis.event;
1111     if (!event.willCommit) {
1112       return;
1113     }
1114     const value = this.AFMergeChange(event);
1115     if (!value) {
1116       return;
1117     }
1118     if (this._parseDate(cFormat, value, true) === null) {
1119       const invalid = GlobalConstants.IDS_INVALID_DATE;
1120       const invalid2 = GlobalConstants.IDS_INVALID_DATE2;
1121       const err = `${invalid} ${this._mkTargetName(event)}${invalid2}${cFormat}`;
1122       this._app.alert(err);
1123       event.rc = false;
1124     }
1125   }
1126   AFDate_Keystroke(pdf) {
1127     if (pdf >= 0 && pdf < this._dateFormats.length) {
1128       this.AFDate_KeystrokeEx(this._dateFormats[pdf]);
1129     }
1130   }
1131   AFRange_Validate(bGreaterThan, nGreaterThan, bLessThan, nLessThan) {
1132     const event = globalThis.event;
1133     if (!event.value) {
1134       return;
1135     }
1136     const value = this.AFMakeNumber(event.value);
1137     if (value === null) {
1138       return;
1139     }
1140     bGreaterThan = !!bGreaterThan;
1141     bLessThan = !!bLessThan;
1142     if (bGreaterThan) {
1143       nGreaterThan = this.AFMakeNumber(nGreaterThan);
1144       if (nGreaterThan === null) {
1145         return;
1146       }
1147     }
1148     if (bLessThan) {
1149       nLessThan = this.AFMakeNumber(nLessThan);
1150       if (nLessThan === null) {
1151         return;
1152       }
1153     }
1154     let err = "";
1155     if (bGreaterThan && bLessThan) {
1156       if (value < nGreaterThan || value > nLessThan) {
1157         err = this._util.printf(GlobalConstants.IDS_GT_AND_LT, nGreaterThan, nLessThan);
1158       }
1159     } else if (bGreaterThan) {
1160       if (value < nGreaterThan) {
1161         err = this._util.printf(GlobalConstants.IDS_GREATER_THAN, nGreaterThan);
1162       }
1163     } else if (value > nLessThan) {
1164       err = this._util.printf(GlobalConstants.IDS_LESS_THAN, nLessThan);
1165     }
1166     if (err) {
1167       this._app.alert(err);
1168       event.rc = false;
1169     }
1170   }
1171   AFSimple(cFunction, nValue1, nValue2) {
1172     const value1 = this.AFMakeNumber(nValue1);
1173     if (value1 === null) {
1174       throw new Error("Invalid nValue1 in AFSimple");
1175     }
1176     const value2 = this.AFMakeNumber(nValue2);
1177     if (value2 === null) {
1178       throw new Error("Invalid nValue2 in AFSimple");
1179     }
1180     switch (cFunction) {
1181       case "AVG":
1182         return (value1 + value2) / 2;
1183       case "SUM":
1184         return value1 + value2;
1185       case "PRD":
1186         return value1 * value2;
1187       case "MIN":
1188         return Math.min(value1, value2);
1189       case "MAX":
1190         return Math.max(value1, value2);
1191     }
1192     throw new Error("Invalid cFunction in AFSimple");
1193   }
1194   AFSimple_Calculate(cFunction, cFields) {
1195     const actions = {
1196       AVG: args => args.reduce((acc, value) => acc + value, 0) / args.length,
1197       SUM: args => args.reduce((acc, value) => acc + value, 0),
1198       PRD: args => args.reduce((acc, value) => acc * value, 1),
1199       MIN: args => args.reduce((acc, value) => Math.min(acc, value), Number.MAX_VALUE),
1200       MAX: args => args.reduce((acc, value) => Math.max(acc, value), Number.MIN_VALUE)
1201     };
1202     if (!(cFunction in actions)) {
1203       throw new TypeError("Invalid function in AFSimple_Calculate");
1204     }
1205     const event = globalThis.event;
1206     const values = [];
1207     cFields = this.AFMakeArrayFromList(cFields);
1208     for (const cField of cFields) {
1209       const field = this._document.getField(cField);
1210       if (!field) {
1211         continue;
1212       }
1213       for (const child of field.getArray()) {
1214         const number = this.AFMakeNumber(child.value);
1215         values.push(number ?? 0);
1216       }
1217     }
1218     if (values.length === 0) {
1219       event.value = 0;
1220       return;
1221     }
1222     const res = actions[cFunction](values);
1223     event.value = Math.round(1e6 * res) / 1e6;
1224   }
1225   AFSpecial_Format(psf) {
1226     const event = globalThis.event;
1227     if (!event.value) {
1228       return;
1229     }
1230     psf = this.AFMakeNumber(psf);
1231     let formatStr;
1232     switch (psf) {
1233       case 0:
1234         formatStr = "99999";
1235         break;
1236       case 1:
1237         formatStr = "99999-9999";
1238         break;
1239       case 2:
1240         formatStr = this._util.printx("9999999999", event.value).length >= 10 ? "(999) 999-9999" : "999-9999";
1241         break;
1242       case 3:
1243         formatStr = "999-99-9999";
1244         break;
1245       default:
1246         throw new Error("Invalid psf in AFSpecial_Format");
1247     }
1248     event.value = this._util.printx(formatStr, event.value);
1249   }
1250   AFSpecial_KeystrokeEx(cMask) {
1251     const event = globalThis.event;
1252     const simplifiedFormatStr = cMask.replaceAll(/[^9AOX]/g, "");
1253     this.#AFSpecial_KeystrokeEx_helper(simplifiedFormatStr, null, false);
1254     if (event.rc) {
1255       return;
1256     }
1257     event.rc = true;
1258     this.#AFSpecial_KeystrokeEx_helper(cMask, null, true);
1259   }
1260   #AFSpecial_KeystrokeEx_helper(cMask, value, warn) {
1261     if (!cMask) {
1262       return;
1263     }
1264     const event = globalThis.event;
1265     value ||= this.AFMergeChange(event);
1266     if (!value) {
1267       return;
1268     }
1269     const checkers = new Map([["9", char => char >= "0" && char <= "9"], ["A", char => "a" <= char && char <= "z" || "A" <= char && char <= "Z"], ["O", char => "a" <= char && char <= "z" || "A" <= char && char <= "Z" || "0" <= char && char <= "9"], ["X", char => true]]);
1270     function _checkValidity(_value, _cMask) {
1271       for (let i = 0, ii = _value.length; i < ii; i++) {
1272         const mask = _cMask.charAt(i);
1273         const char = _value.charAt(i);
1274         const checker = checkers.get(mask);
1275         if (checker) {
1276           if (!checker(char)) {
1277             return false;
1278           }
1279         } else if (mask !== char) {
1280           return false;
1281         }
1282       }
1283       return true;
1284     }
1285     const err = `${GlobalConstants.IDS_INVALID_VALUE} = "${cMask}"`;
1286     if (value.length > cMask.length) {
1287       if (warn) {
1288         this._app.alert(err);
1289       }
1290       event.rc = false;
1291       return;
1292     }
1293     if (event.willCommit) {
1294       if (value.length < cMask.length) {
1295         if (warn) {
1296           this._app.alert(err);
1297         }
1298         event.rc = false;
1299         return;
1300       }
1301       if (!_checkValidity(value, cMask)) {
1302         if (warn) {
1303           this._app.alert(err);
1304         }
1305         event.rc = false;
1306         return;
1307       }
1308       event.value += cMask.substring(value.length);
1309       return;
1310     }
1311     if (value.length < cMask.length) {
1312       cMask = cMask.substring(0, value.length);
1313     }
1314     if (!_checkValidity(value, cMask)) {
1315       if (warn) {
1316         this._app.alert(err);
1317       }
1318       event.rc = false;
1319     }
1320   }
1321   AFSpecial_Keystroke(psf) {
1322     const event = globalThis.event;
1323     psf = this.AFMakeNumber(psf);
1324     let value = this.AFMergeChange(event);
1325     let formatStr, secondFormatStr;
1326     switch (psf) {
1327       case 0:
1328         formatStr = "99999";
1329         break;
1330       case 1:
1331         formatStr = "99999-9999";
1332         break;
1333       case 2:
1334         formatStr = "999-9999";
1335         secondFormatStr = "(999) 999-9999";
1336         break;
1337       case 3:
1338         formatStr = "999-99-9999";
1339         break;
1340       default:
1341         throw new Error("Invalid psf in AFSpecial_Keystroke");
1342     }
1343     const formats = secondFormatStr ? [formatStr, secondFormatStr] : [formatStr];
1344     for (const format of formats) {
1345       this.#AFSpecial_KeystrokeEx_helper(format, value, false);
1346       if (event.rc) {
1347         return;
1348       }
1349       event.rc = true;
1350     }
1351     const re = /([-()]|\s)+/g;
1352     value = value.replaceAll(re, "");
1353     for (const format of formats) {
1354       this.#AFSpecial_KeystrokeEx_helper(format.replaceAll(re, ""), value, false);
1355       if (event.rc) {
1356         return;
1357       }
1358       event.rc = true;
1359     }
1360     this.AFSpecial_KeystrokeEx((secondFormatStr && value.match(/\d/g) || []).length > 7 ? secondFormatStr : formatStr);
1361   }
1362   AFTime_FormatEx(cFormat) {
1363     this.AFDate_FormatEx(cFormat);
1364   }
1365   AFTime_Format(pdf) {
1366     if (pdf >= 0 && pdf < this._timeFormats.length) {
1367       this.AFDate_FormatEx(this._timeFormats[pdf]);
1368     }
1369   }
1370   AFTime_KeystrokeEx(cFormat) {
1371     this.AFDate_KeystrokeEx(cFormat);
1372   }
1373   AFTime_Keystroke(pdf) {
1374     if (pdf >= 0 && pdf < this._timeFormats.length) {
1375       this.AFDate_KeystrokeEx(this._timeFormats[pdf]);
1376     }
1377   }
1378   eMailValidate(str) {
1379     return this._emailRegex.test(str);
1380   }
1381   AFExactMatch(rePatterns, str) {
1382     if (rePatterns instanceof RegExp) {
1383       return str.match(rePatterns)?.[0] === str || 0;
1384     }
1385     return rePatterns.findIndex(re => str.match(re)?.[0] === str) + 1;
1386   }
1389 ;// ./src/scripting_api/app_utils.js
1390 const VIEWER_TYPE = "PDF.js";
1391 const VIEWER_VARIATION = "Full";
1392 const VIEWER_VERSION = 21.00720099;
1393 const FORMS_VERSION = 21.00720099;
1394 const USERACTIVATION_CALLBACKID = 0;
1395 const USERACTIVATION_MAXTIME_VALIDITY = 5000;
1396 function serializeError(error) {
1397   const value = `${error.toString()}\n${error.stack}`;
1398   return {
1399     command: "error",
1400     value
1401   };
1404 ;// ./src/scripting_api/event.js
1406 class Event {
1407   constructor(data) {
1408     this.change = data.change || "";
1409     this.changeEx = data.changeEx || null;
1410     this.commitKey = data.commitKey || 0;
1411     this.fieldFull = data.fieldFull || false;
1412     this.keyDown = data.keyDown || false;
1413     this.modifier = data.modifier || false;
1414     this.name = data.name;
1415     this.rc = true;
1416     this.richChange = data.richChange || [];
1417     this.richChangeEx = data.richChangeEx || [];
1418     this.richValue = data.richValue || [];
1419     this.selEnd = data.selEnd ?? -1;
1420     this.selStart = data.selStart ?? -1;
1421     this.shift = data.shift || false;
1422     this.source = data.source || null;
1423     this.target = data.target || null;
1424     this.targetName = "";
1425     this.type = "Field";
1426     this.value = data.value || "";
1427     this.willCommit = data.willCommit || false;
1428   }
1430 class EventDispatcher {
1431   constructor(document, calculationOrder, objects, externalCall) {
1432     this._document = document;
1433     this._calculationOrder = calculationOrder;
1434     this._objects = objects;
1435     this._externalCall = externalCall;
1436     this._document.obj._eventDispatcher = this;
1437     this._isCalculating = false;
1438   }
1439   mergeChange(event) {
1440     let value = event.value;
1441     if (Array.isArray(value)) {
1442       return value;
1443     }
1444     if (typeof value !== "string") {
1445       value = value.toString();
1446     }
1447     const prefix = event.selStart >= 0 ? value.substring(0, event.selStart) : "";
1448     const postfix = event.selEnd >= 0 && event.selEnd <= value.length ? value.substring(event.selEnd) : "";
1449     return `${prefix}${event.change}${postfix}`;
1450   }
1451   userActivation() {
1452     this._document.obj._userActivation = true;
1453     this._externalCall("setTimeout", [USERACTIVATION_CALLBACKID, USERACTIVATION_MAXTIME_VALIDITY]);
1454   }
1455   dispatch(baseEvent) {
1456     const id = baseEvent.id;
1457     if (!(id in this._objects)) {
1458       let event;
1459       if (id === "doc" || id === "page") {
1460         event = globalThis.event = new Event(baseEvent);
1461         event.source = event.target = this._document.wrapped;
1462         event.name = baseEvent.name;
1463       }
1464       if (id === "doc") {
1465         const eventName = event.name;
1466         if (eventName === "Open") {
1467           this.userActivation();
1468           this._document.obj._initActions();
1469           this.formatAll();
1470         }
1471         if (!["DidPrint", "DidSave", "WillPrint", "WillSave"].includes(eventName)) {
1472           this.userActivation();
1473         }
1474         this._document.obj._dispatchDocEvent(event.name);
1475       } else if (id === "page") {
1476         this.userActivation();
1477         this._document.obj._dispatchPageEvent(event.name, baseEvent.actions, baseEvent.pageNumber);
1478       } else if (id === "app" && baseEvent.name === "ResetForm") {
1479         this.userActivation();
1480         for (const fieldId of baseEvent.ids) {
1481           const obj = this._objects[fieldId];
1482           obj?.obj._reset();
1483         }
1484       }
1485       return;
1486     }
1487     const name = baseEvent.name;
1488     const source = this._objects[id];
1489     const event = globalThis.event = new Event(baseEvent);
1490     let savedChange;
1491     this.userActivation();
1492     if (source.obj._isButton()) {
1493       source.obj._id = id;
1494       event.value = source.obj._getExportValue(event.value);
1495       if (name === "Action") {
1496         source.obj._value = event.value;
1497       }
1498     }
1499     switch (name) {
1500       case "Keystroke":
1501         savedChange = {
1502           value: event.value,
1503           changeEx: event.changeEx,
1504           change: event.change,
1505           selStart: event.selStart,
1506           selEnd: event.selEnd
1507         };
1508         break;
1509       case "Blur":
1510       case "Focus":
1511         Object.defineProperty(event, "value", {
1512           configurable: false,
1513           writable: false,
1514           enumerable: true,
1515           value: event.value
1516         });
1517         break;
1518       case "Validate":
1519         this.runValidation(source, event);
1520         return;
1521       case "Action":
1522         this.runActions(source, source, event, name);
1523         this.runCalculate(source, event);
1524         return;
1525     }
1526     this.runActions(source, source, event, name);
1527     if (name !== "Keystroke") {
1528       return;
1529     }
1530     if (event.rc) {
1531       if (event.willCommit) {
1532         this.runValidation(source, event);
1533       } else {
1534         if (source.obj._isChoice) {
1535           source.obj.value = savedChange.changeEx;
1536           source.obj._send({
1537             id: source.obj._id,
1538             siblings: source.obj._siblings,
1539             value: source.obj.value
1540           });
1541           return;
1542         }
1543         const value = source.obj.value = this.mergeChange(event);
1544         let selStart, selEnd;
1545         if (event.selStart !== savedChange.selStart || event.selEnd !== savedChange.selEnd) {
1546           selStart = event.selStart;
1547           selEnd = event.selEnd;
1548         } else {
1549           selEnd = selStart = savedChange.selStart + event.change.length;
1550         }
1551         source.obj._send({
1552           id: source.obj._id,
1553           siblings: source.obj._siblings,
1554           value,
1555           selRange: [selStart, selEnd]
1556         });
1557       }
1558     } else if (!event.willCommit) {
1559       source.obj._send({
1560         id: source.obj._id,
1561         siblings: source.obj._siblings,
1562         value: savedChange.value,
1563         selRange: [savedChange.selStart, savedChange.selEnd]
1564       });
1565     } else {
1566       source.obj._send({
1567         id: source.obj._id,
1568         siblings: source.obj._siblings,
1569         value: "",
1570         formattedValue: null,
1571         selRange: [0, 0]
1572       });
1573     }
1574   }
1575   formatAll() {
1576     const event = globalThis.event = new Event({});
1577     for (const source of Object.values(this._objects)) {
1578       event.value = source.obj._getValue();
1579       this.runActions(source, source, event, "Format");
1580     }
1581   }
1582   runValidation(source, event) {
1583     const didValidateRun = this.runActions(source, source, event, "Validate");
1584     if (event.rc) {
1585       source.obj.value = event.value;
1586       this.runCalculate(source, event);
1587       const savedValue = event.value = source.obj._getValue();
1588       let formattedValue = null;
1589       if (this.runActions(source, source, event, "Format")) {
1590         formattedValue = event.value?.toString?.();
1591       }
1592       source.obj._send({
1593         id: source.obj._id,
1594         siblings: source.obj._siblings,
1595         value: savedValue,
1596         formattedValue
1597       });
1598       event.value = savedValue;
1599     } else if (didValidateRun) {
1600       source.obj._send({
1601         id: source.obj._id,
1602         siblings: source.obj._siblings,
1603         value: "",
1604         formattedValue: null,
1605         selRange: [0, 0],
1606         focus: true
1607       });
1608     }
1609   }
1610   runActions(source, target, event, eventName) {
1611     event.source = source.wrapped;
1612     event.target = target.wrapped;
1613     event.name = eventName;
1614     event.targetName = target.obj.name;
1615     event.rc = true;
1616     return target.obj._runActions(event);
1617   }
1618   calculateNow() {
1619     if (!this._calculationOrder || this._isCalculating || !this._document.obj.calculate) {
1620       return;
1621     }
1622     this._isCalculating = true;
1623     const first = this._calculationOrder[0];
1624     const source = this._objects[first];
1625     globalThis.event = new Event({});
1626     try {
1627       this.runCalculate(source, globalThis.event);
1628     } catch (error) {
1629       this._isCalculating = false;
1630       throw error;
1631     }
1632     this._isCalculating = false;
1633   }
1634   runCalculate(source, event) {
1635     if (!this._calculationOrder || !this._document.obj.calculate) {
1636       return;
1637     }
1638     for (const targetId of this._calculationOrder) {
1639       if (!(targetId in this._objects)) {
1640         continue;
1641       }
1642       if (!this._document.obj.calculate) {
1643         break;
1644       }
1645       event.value = null;
1646       const target = this._objects[targetId];
1647       let savedValue = target.obj._getValue();
1648       try {
1649         this.runActions(source, target, event, "Calculate");
1650       } catch (error) {
1651         const fieldId = target.obj._id;
1652         const serializedError = serializeError(error);
1653         serializedError.value = `Error when calculating value for field "${fieldId}"\n${serializedError.value}`;
1654         this._externalCall("send", [serializedError]);
1655         continue;
1656       }
1657       if (!event.rc) {
1658         continue;
1659       }
1660       if (event.value !== null) {
1661         target.obj.value = event.value;
1662       } else {
1663         event.value = target.obj._getValue();
1664       }
1665       this.runActions(target, target, event, "Validate");
1666       if (!event.rc) {
1667         if (target.obj._getValue() !== savedValue) {
1668           target.wrapped.value = savedValue;
1669         }
1670         continue;
1671       }
1672       if (event.value === null) {
1673         event.value = target.obj._getValue();
1674       }
1675       savedValue = target.obj._getValue();
1676       let formattedValue = null;
1677       if (this.runActions(target, target, event, "Format")) {
1678         formattedValue = event.value?.toString?.();
1679       }
1680       target.obj._send({
1681         id: target.obj._id,
1682         siblings: target.obj._siblings,
1683         value: savedValue,
1684         formattedValue
1685       });
1686     }
1687   }
1690 ;// ./src/scripting_api/fullscreen.js
1693 class FullScreen extends PDFObject {
1694   constructor(data) {
1695     super(data);
1696     this._backgroundColor = [];
1697     this._clickAdvances = true;
1698     this._cursor = Cursor.hidden;
1699     this._defaultTransition = "";
1700     this._escapeExits = true;
1701     this._isFullScreen = true;
1702     this._loop = false;
1703     this._timeDelay = 3600;
1704     this._usePageTiming = false;
1705     this._useTimer = false;
1706   }
1707   get backgroundColor() {
1708     return this._backgroundColor;
1709   }
1710   set backgroundColor(_) {}
1711   get clickAdvances() {
1712     return this._clickAdvances;
1713   }
1714   set clickAdvances(_) {}
1715   get cursor() {
1716     return this._cursor;
1717   }
1718   set cursor(_) {}
1719   get defaultTransition() {
1720     return this._defaultTransition;
1721   }
1722   set defaultTransition(_) {}
1723   get escapeExits() {
1724     return this._escapeExits;
1725   }
1726   set escapeExits(_) {}
1727   get isFullScreen() {
1728     return this._isFullScreen;
1729   }
1730   set isFullScreen(_) {}
1731   get loop() {
1732     return this._loop;
1733   }
1734   set loop(_) {}
1735   get timeDelay() {
1736     return this._timeDelay;
1737   }
1738   set timeDelay(_) {}
1739   get transitions() {
1740     return ["Replace", "WipeRight", "WipeLeft", "WipeDown", "WipeUp", "SplitHorizontalIn", "SplitHorizontalOut", "SplitVerticalIn", "SplitVerticalOut", "BlindsHorizontal", "BlindsVertical", "BoxIn", "BoxOut", "GlitterRight", "GlitterDown", "GlitterRightDown", "Dissolve", "Random"];
1741   }
1742   set transitions(_) {
1743     throw new Error("fullscreen.transitions is read-only");
1744   }
1745   get usePageTiming() {
1746     return this._usePageTiming;
1747   }
1748   set usePageTiming(_) {}
1749   get useTimer() {
1750     return this._useTimer;
1751   }
1752   set useTimer(_) {}
1755 ;// ./src/scripting_api/thermometer.js
1757 class Thermometer extends PDFObject {
1758   constructor(data) {
1759     super(data);
1760     this._cancelled = false;
1761     this._duration = 100;
1762     this._text = "";
1763     this._value = 0;
1764   }
1765   get cancelled() {
1766     return this._cancelled;
1767   }
1768   set cancelled(_) {
1769     throw new Error("thermometer.cancelled is read-only");
1770   }
1771   get duration() {
1772     return this._duration;
1773   }
1774   set duration(val) {
1775     this._duration = val;
1776   }
1777   get text() {
1778     return this._text;
1779   }
1780   set text(val) {
1781     this._text = val;
1782   }
1783   get value() {
1784     return this._value;
1785   }
1786   set value(val) {
1787     this._value = val;
1788   }
1789   begin() {}
1790   end() {}
1793 ;// ./src/scripting_api/app.js
1800 class App extends PDFObject {
1801   constructor(data) {
1802     super(data);
1803     this._constants = null;
1804     this._focusRect = true;
1805     this._fs = null;
1806     this._language = App._getLanguage(data.language);
1807     this._openInPlace = false;
1808     this._platform = App._getPlatform(data.platform);
1809     this._runtimeHighlight = false;
1810     this._runtimeHighlightColor = ["T"];
1811     this._thermometer = null;
1812     this._toolbar = false;
1813     this._document = data._document;
1814     this._proxyHandler = data.proxyHandler;
1815     this._objects = Object.create(null);
1816     this._eventDispatcher = new EventDispatcher(this._document, data.calculationOrder, this._objects, data.externalCall);
1817     this._timeoutIds = new WeakMap();
1818     if (typeof FinalizationRegistry !== "undefined") {
1819       this._timeoutIdsRegistry = new FinalizationRegistry(this._cleanTimeout.bind(this));
1820     } else {
1821       this._timeoutIdsRegistry = null;
1822     }
1823     this._timeoutCallbackIds = new Map();
1824     this._timeoutCallbackId = USERACTIVATION_CALLBACKID + 1;
1825     this._globalEval = data.globalEval;
1826     this._externalCall = data.externalCall;
1827   }
1828   _dispatchEvent(pdfEvent) {
1829     this._eventDispatcher.dispatch(pdfEvent);
1830   }
1831   _registerTimeoutCallback(cExpr) {
1832     const id = this._timeoutCallbackId++;
1833     this._timeoutCallbackIds.set(id, cExpr);
1834     return id;
1835   }
1836   _unregisterTimeoutCallback(id) {
1837     this._timeoutCallbackIds.delete(id);
1838   }
1839   _evalCallback({
1840     callbackId,
1841     interval
1842   }) {
1843     if (callbackId === USERACTIVATION_CALLBACKID) {
1844       this._document.obj._userActivation = false;
1845       return;
1846     }
1847     const expr = this._timeoutCallbackIds.get(callbackId);
1848     if (!interval) {
1849       this._unregisterTimeoutCallback(callbackId);
1850     }
1851     if (expr) {
1852       this._globalEval(expr);
1853     }
1854   }
1855   _registerTimeout(callbackId, interval) {
1856     const timeout = Object.create(null);
1857     const id = {
1858       callbackId,
1859       interval
1860     };
1861     this._timeoutIds.set(timeout, id);
1862     this._timeoutIdsRegistry?.register(timeout, id);
1863     return timeout;
1864   }
1865   _unregisterTimeout(timeout) {
1866     this._timeoutIdsRegistry?.unregister(timeout);
1867     const data = this._timeoutIds.get(timeout);
1868     if (!data) {
1869       return;
1870     }
1871     this._timeoutIds.delete(timeout);
1872     this._cleanTimeout(data);
1873   }
1874   _cleanTimeout({
1875     callbackId,
1876     interval
1877   }) {
1878     this._unregisterTimeoutCallback(callbackId);
1879     if (interval) {
1880       this._externalCall("clearInterval", [callbackId]);
1881     } else {
1882       this._externalCall("clearTimeout", [callbackId]);
1883     }
1884   }
1885   static _getPlatform(platform) {
1886     if (typeof platform === "string") {
1887       platform = platform.toLowerCase();
1888       if (platform.includes("win")) {
1889         return "WIN";
1890       } else if (platform.includes("mac")) {
1891         return "MAC";
1892       }
1893     }
1894     return "UNIX";
1895   }
1896   static _getLanguage(language) {
1897     const [main, sub] = language.toLowerCase().split(/[-_]/);
1898     switch (main) {
1899       case "zh":
1900         if (sub === "cn" || sub === "sg") {
1901           return "CHS";
1902         }
1903         return "CHT";
1904       case "da":
1905         return "DAN";
1906       case "de":
1907         return "DEU";
1908       case "es":
1909         return "ESP";
1910       case "fr":
1911         return "FRA";
1912       case "it":
1913         return "ITA";
1914       case "ko":
1915         return "KOR";
1916       case "ja":
1917         return "JPN";
1918       case "nl":
1919         return "NLD";
1920       case "no":
1921         return "NOR";
1922       case "pt":
1923         if (sub === "br") {
1924           return "PTB";
1925         }
1926         return "ENU";
1927       case "fi":
1928         return "SUO";
1929       case "SV":
1930         return "SVE";
1931       default:
1932         return "ENU";
1933     }
1934   }
1935   get activeDocs() {
1936     return [this._document.wrapped];
1937   }
1938   set activeDocs(_) {
1939     throw new Error("app.activeDocs is read-only");
1940   }
1941   get calculate() {
1942     return this._document.obj.calculate;
1943   }
1944   set calculate(calculate) {
1945     this._document.obj.calculate = calculate;
1946   }
1947   get constants() {
1948     if (!this._constants) {
1949       this._constants = Object.freeze({
1950         align: Object.freeze({
1951           left: 0,
1952           center: 1,
1953           right: 2,
1954           top: 3,
1955           bottom: 4
1956         })
1957       });
1958     }
1959     return this._constants;
1960   }
1961   set constants(_) {
1962     throw new Error("app.constants is read-only");
1963   }
1964   get focusRect() {
1965     return this._focusRect;
1966   }
1967   set focusRect(val) {
1968     this._focusRect = val;
1969   }
1970   get formsVersion() {
1971     return FORMS_VERSION;
1972   }
1973   set formsVersion(_) {
1974     throw new Error("app.formsVersion is read-only");
1975   }
1976   get fromPDFConverters() {
1977     return [];
1978   }
1979   set fromPDFConverters(_) {
1980     throw new Error("app.fromPDFConverters is read-only");
1981   }
1982   get fs() {
1983     if (this._fs === null) {
1984       this._fs = new Proxy(new FullScreen({
1985         send: this._send
1986       }), this._proxyHandler);
1987     }
1988     return this._fs;
1989   }
1990   set fs(_) {
1991     throw new Error("app.fs is read-only");
1992   }
1993   get language() {
1994     return this._language;
1995   }
1996   set language(_) {
1997     throw new Error("app.language is read-only");
1998   }
1999   get media() {
2000     return undefined;
2001   }
2002   set media(_) {
2003     throw new Error("app.media is read-only");
2004   }
2005   get monitors() {
2006     return [];
2007   }
2008   set monitors(_) {
2009     throw new Error("app.monitors is read-only");
2010   }
2011   get numPlugins() {
2012     return 0;
2013   }
2014   set numPlugins(_) {
2015     throw new Error("app.numPlugins is read-only");
2016   }
2017   get openInPlace() {
2018     return this._openInPlace;
2019   }
2020   set openInPlace(val) {
2021     this._openInPlace = val;
2022   }
2023   get platform() {
2024     return this._platform;
2025   }
2026   set platform(_) {
2027     throw new Error("app.platform is read-only");
2028   }
2029   get plugins() {
2030     return [];
2031   }
2032   set plugins(_) {
2033     throw new Error("app.plugins is read-only");
2034   }
2035   get printColorProfiles() {
2036     return [];
2037   }
2038   set printColorProfiles(_) {
2039     throw new Error("app.printColorProfiles is read-only");
2040   }
2041   get printerNames() {
2042     return [];
2043   }
2044   set printerNames(_) {
2045     throw new Error("app.printerNames is read-only");
2046   }
2047   get runtimeHighlight() {
2048     return this._runtimeHighlight;
2049   }
2050   set runtimeHighlight(val) {
2051     this._runtimeHighlight = val;
2052   }
2053   get runtimeHighlightColor() {
2054     return this._runtimeHighlightColor;
2055   }
2056   set runtimeHighlightColor(val) {
2057     if (Color._isValidColor(val)) {
2058       this._runtimeHighlightColor = val;
2059     }
2060   }
2061   get thermometer() {
2062     if (this._thermometer === null) {
2063       this._thermometer = new Proxy(new Thermometer({
2064         send: this._send
2065       }), this._proxyHandler);
2066     }
2067     return this._thermometer;
2068   }
2069   set thermometer(_) {
2070     throw new Error("app.thermometer is read-only");
2071   }
2072   get toolbar() {
2073     return this._toolbar;
2074   }
2075   set toolbar(val) {
2076     this._toolbar = val;
2077   }
2078   get toolbarHorizontal() {
2079     return this.toolbar;
2080   }
2081   set toolbarHorizontal(value) {
2082     this.toolbar = value;
2083   }
2084   get toolbarVertical() {
2085     return this.toolbar;
2086   }
2087   set toolbarVertical(value) {
2088     this.toolbar = value;
2089   }
2090   get viewerType() {
2091     return VIEWER_TYPE;
2092   }
2093   set viewerType(_) {
2094     throw new Error("app.viewerType is read-only");
2095   }
2096   get viewerVariation() {
2097     return VIEWER_VARIATION;
2098   }
2099   set viewerVariation(_) {
2100     throw new Error("app.viewerVariation is read-only");
2101   }
2102   get viewerVersion() {
2103     return VIEWER_VERSION;
2104   }
2105   set viewerVersion(_) {
2106     throw new Error("app.viewerVersion is read-only");
2107   }
2108   addMenuItem() {}
2109   addSubMenu() {}
2110   addToolButton() {}
2111   alert(cMsg, nIcon = 0, nType = 0, cTitle = "PDF.js", oDoc = null, oCheckbox = null) {
2112     if (!this._document.obj._userActivation) {
2113       return 0;
2114     }
2115     this._document.obj._userActivation = false;
2116     if (cMsg && typeof cMsg === "object") {
2117       nType = cMsg.nType;
2118       cMsg = cMsg.cMsg;
2119     }
2120     cMsg = (cMsg || "").toString();
2121     if (!cMsg) {
2122       return 0;
2123     }
2124     nType = typeof nType !== "number" || isNaN(nType) || nType < 0 || nType > 3 ? 0 : nType;
2125     if (nType >= 2) {
2126       return this._externalCall("confirm", [cMsg]) ? 4 : 3;
2127     }
2128     this._externalCall("alert", [cMsg]);
2129     return 1;
2130   }
2131   beep() {}
2132   beginPriv() {}
2133   browseForDoc() {}
2134   clearInterval(oInterval) {
2135     this._unregisterTimeout(oInterval);
2136   }
2137   clearTimeOut(oTime) {
2138     this._unregisterTimeout(oTime);
2139   }
2140   endPriv() {}
2141   execDialog() {}
2142   execMenuItem(item) {
2143     if (!this._document.obj._userActivation) {
2144       return;
2145     }
2146     this._document.obj._userActivation = false;
2147     switch (item) {
2148       case "SaveAs":
2149         if (this._document.obj._disableSaving) {
2150           return;
2151         }
2152         this._send({
2153           command: item
2154         });
2155         break;
2156       case "FirstPage":
2157       case "LastPage":
2158       case "NextPage":
2159       case "PrevPage":
2160       case "ZoomViewIn":
2161       case "ZoomViewOut":
2162         this._send({
2163           command: item
2164         });
2165         break;
2166       case "FitPage":
2167         this._send({
2168           command: "zoom",
2169           value: "page-fit"
2170         });
2171         break;
2172       case "Print":
2173         if (this._document.obj._disablePrinting) {
2174           return;
2175         }
2176         this._send({
2177           command: "print"
2178         });
2179         break;
2180     }
2181   }
2182   getNthPlugInName() {}
2183   getPath() {}
2184   goBack() {}
2185   goForward() {}
2186   hideMenuItem() {}
2187   hideToolbarButton() {}
2188   launchURL() {}
2189   listMenuItems() {}
2190   listToolbarButtons() {}
2191   loadPolicyFile() {}
2192   mailGetAddrs() {}
2193   mailMsg() {}
2194   newDoc() {}
2195   newCollection() {}
2196   newFDF() {}
2197   openDoc() {}
2198   openFDF() {}
2199   popUpMenu() {}
2200   popUpMenuEx() {}
2201   removeToolButton() {}
2202   response(cQuestion, cTitle = "", cDefault = "", bPassword = "", cLabel = "") {
2203     if (cQuestion && typeof cQuestion === "object") {
2204       cDefault = cQuestion.cDefault;
2205       cQuestion = cQuestion.cQuestion;
2206     }
2207     cQuestion = (cQuestion || "").toString();
2208     cDefault = (cDefault || "").toString();
2209     return this._externalCall("prompt", [cQuestion, cDefault || ""]);
2210   }
2211   setInterval(cExpr, nMilliseconds = 0) {
2212     if (cExpr && typeof cExpr === "object") {
2213       nMilliseconds = cExpr.nMilliseconds || 0;
2214       cExpr = cExpr.cExpr;
2215     }
2216     if (typeof cExpr !== "string") {
2217       throw new TypeError("First argument of app.setInterval must be a string");
2218     }
2219     if (typeof nMilliseconds !== "number") {
2220       throw new TypeError("Second argument of app.setInterval must be a number");
2221     }
2222     const callbackId = this._registerTimeoutCallback(cExpr);
2223     this._externalCall("setInterval", [callbackId, nMilliseconds]);
2224     return this._registerTimeout(callbackId, true);
2225   }
2226   setTimeOut(cExpr, nMilliseconds = 0) {
2227     if (cExpr && typeof cExpr === "object") {
2228       nMilliseconds = cExpr.nMilliseconds || 0;
2229       cExpr = cExpr.cExpr;
2230     }
2231     if (typeof cExpr !== "string") {
2232       throw new TypeError("First argument of app.setTimeOut must be a string");
2233     }
2234     if (typeof nMilliseconds !== "number") {
2235       throw new TypeError("Second argument of app.setTimeOut must be a number");
2236     }
2237     const callbackId = this._registerTimeoutCallback(cExpr);
2238     this._externalCall("setTimeout", [callbackId, nMilliseconds]);
2239     return this._registerTimeout(callbackId, false);
2240   }
2241   trustedFunction() {}
2242   trustPropagatorFunction() {}
2245 ;// ./src/scripting_api/console.js
2247 class Console extends PDFObject {
2248   clear() {
2249     this._send({
2250       id: "clear"
2251     });
2252   }
2253   hide() {}
2254   println(msg) {
2255     if (typeof msg === "string") {
2256       this._send({
2257         command: "println",
2258         value: "PDF.js Console:: " + msg
2259       });
2260     }
2261   }
2262   show() {}
2265 ;// ./src/scripting_api/print_params.js
2266 class PrintParams {
2267   constructor(data) {
2268     this.binaryOk = true;
2269     this.bitmapDPI = 150;
2270     this.booklet = {
2271       binding: 0,
2272       duplexMode: 0,
2273       subsetFrom: 0,
2274       subsetTo: -1
2275     };
2276     this.colorOverride = 0;
2277     this.colorProfile = "";
2278     this.constants = Object.freeze({
2279       bookletBindings: Object.freeze({
2280         Left: 0,
2281         Right: 1,
2282         LeftTall: 2,
2283         RightTall: 3
2284       }),
2285       bookletDuplexMode: Object.freeze({
2286         BothSides: 0,
2287         FrontSideOnly: 1,
2288         BasicSideOnly: 2
2289       }),
2290       colorOverrides: Object.freeze({
2291         auto: 0,
2292         gray: 1,
2293         mono: 2
2294       }),
2295       fontPolicies: Object.freeze({
2296         everyPage: 0,
2297         jobStart: 1,
2298         pageRange: 2
2299       }),
2300       handling: Object.freeze({
2301         none: 0,
2302         fit: 1,
2303         shrink: 2,
2304         tileAll: 3,
2305         tileLarge: 4,
2306         nUp: 5,
2307         booklet: 6
2308       }),
2309       interactionLevel: Object.freeze({
2310         automatic: 0,
2311         full: 1,
2312         silent: 2
2313       }),
2314       nUpPageOrders: Object.freeze({
2315         Horizontal: 0,
2316         HorizontalReversed: 1,
2317         Vertical: 2
2318       }),
2319       printContents: Object.freeze({
2320         doc: 0,
2321         docAndComments: 1,
2322         formFieldsOnly: 2
2323       }),
2324       flagValues: Object.freeze({
2325         applyOverPrint: 1,
2326         applySoftProofSettings: 1 << 1,
2327         applyWorkingColorSpaces: 1 << 2,
2328         emitHalftones: 1 << 3,
2329         emitPostScriptXObjects: 1 << 4,
2330         emitFormsAsPSForms: 1 << 5,
2331         maxJP2KRes: 1 << 6,
2332         setPageSize: 1 << 7,
2333         suppressBG: 1 << 8,
2334         suppressCenter: 1 << 9,
2335         suppressCJKFontSubst: 1 << 10,
2336         suppressCropClip: 1 << 1,
2337         suppressRotate: 1 << 12,
2338         suppressTransfer: 1 << 13,
2339         suppressUCR: 1 << 14,
2340         useTrapAnnots: 1 << 15,
2341         usePrintersMarks: 1 << 16
2342       }),
2343       rasterFlagValues: Object.freeze({
2344         textToOutline: 1,
2345         strokesToOutline: 1 << 1,
2346         allowComplexClip: 1 << 2,
2347         preserveOverprint: 1 << 3
2348       }),
2349       subsets: Object.freeze({
2350         all: 0,
2351         even: 1,
2352         odd: 2
2353       }),
2354       tileMarks: Object.freeze({
2355         none: 0,
2356         west: 1,
2357         east: 2
2358       }),
2359       usages: Object.freeze({
2360         auto: 0,
2361         use: 1,
2362         noUse: 2
2363       })
2364     });
2365     this.downloadFarEastFonts = false;
2366     this.fileName = "";
2367     this.firstPage = 0;
2368     this.flags = 0;
2369     this.fontPolicy = 0;
2370     this.gradientDPI = 150;
2371     this.interactive = 1;
2372     this.lastPage = data.lastPage;
2373     this.npUpAutoRotate = false;
2374     this.npUpNumPagesH = 2;
2375     this.npUpNumPagesV = 2;
2376     this.npUpPageBorder = false;
2377     this.npUpPageOrder = 0;
2378     this.pageHandling = 0;
2379     this.pageSubset = 0;
2380     this.printAsImage = false;
2381     this.printContent = 0;
2382     this.printerName = "";
2383     this.psLevel = 0;
2384     this.rasterFlags = 0;
2385     this.reversePages = false;
2386     this.tileLabel = false;
2387     this.tileMark = 0;
2388     this.tileOverlap = 0;
2389     this.tileScale = 1.0;
2390     this.transparencyLevel = 75;
2391     this.usePrinterCRD = 0;
2392     this.useT1Conversion = 0;
2393   }
2396 ;// ./src/scripting_api/doc.js
2402 const DOC_EXTERNAL = false;
2403 class InfoProxyHandler {
2404   static get(obj, prop) {
2405     return obj[prop.toLowerCase()];
2406   }
2407   static set(obj, prop, value) {
2408     throw new Error(`doc.info.${prop} is read-only`);
2409   }
2411 class Doc extends PDFObject {
2412   constructor(data) {
2413     super(data);
2414     this._expandos = globalThis;
2415     this._baseURL = data.baseURL || "";
2416     this._calculate = true;
2417     this._delay = false;
2418     this._dirty = false;
2419     this._disclosed = false;
2420     this._media = undefined;
2421     this._metadata = data.metadata || "";
2422     this._noautocomplete = undefined;
2423     this._nocache = undefined;
2424     this._spellDictionaryOrder = [];
2425     this._spellLanguageOrder = [];
2426     this._printParams = null;
2427     this._fields = new Map();
2428     this._fieldNames = [];
2429     this._event = null;
2430     this._author = data.Author || "";
2431     this._creator = data.Creator || "";
2432     this._creationDate = this._getDate(data.CreationDate) || null;
2433     this._docID = data.docID || ["", ""];
2434     this._documentFileName = data.filename || "";
2435     this._filesize = data.filesize || 0;
2436     this._keywords = data.Keywords || "";
2437     this._layout = data.layout || "";
2438     this._modDate = this._getDate(data.ModDate) || null;
2439     this._numFields = 0;
2440     this._numPages = data.numPages || 1;
2441     this._pageNum = data.pageNum || 0;
2442     this._producer = data.Producer || "";
2443     this._securityHandler = data.EncryptFilterName || null;
2444     this._subject = data.Subject || "";
2445     this._title = data.Title || "";
2446     this._URL = data.URL || "";
2447     this._info = new Proxy({
2448       title: this._title,
2449       author: this._author,
2450       authors: data.authors || [this._author],
2451       subject: this._subject,
2452       keywords: this._keywords,
2453       creator: this._creator,
2454       producer: this._producer,
2455       creationdate: this._creationDate,
2456       moddate: this._modDate,
2457       trapped: data.Trapped || "Unknown"
2458     }, InfoProxyHandler);
2459     this._zoomType = ZoomType.none;
2460     this._zoom = data.zoom || 100;
2461     this._actions = createActionsMap(data.actions);
2462     this._globalEval = data.globalEval;
2463     this._pageActions = null;
2464     this._userActivation = false;
2465     this._disablePrinting = false;
2466     this._disableSaving = false;
2467     this._otherPageActions = null;
2468   }
2469   _initActions() {
2470     const dontRun = new Set(["WillClose", "WillSave", "DidSave", "WillPrint", "DidPrint", "OpenAction"]);
2471     this._disableSaving = true;
2472     for (const actionName of this._actions.keys()) {
2473       if (!dontRun.has(actionName)) {
2474         this._runActions(actionName);
2475       }
2476     }
2477     this._runActions("OpenAction");
2478     this._disableSaving = false;
2479   }
2480   _dispatchDocEvent(name) {
2481     switch (name) {
2482       case "Open":
2483         this._disableSaving = true;
2484         this._runActions("OpenAction");
2485         this._disableSaving = false;
2486         break;
2487       case "WillPrint":
2488         this._disablePrinting = true;
2489         try {
2490           this._runActions(name);
2491         } catch (error) {
2492           this._send(serializeError(error));
2493         }
2494         this._send({
2495           command: "WillPrintFinished"
2496         });
2497         this._disablePrinting = false;
2498         break;
2499       case "WillSave":
2500         this._disableSaving = true;
2501         this._runActions(name);
2502         this._disableSaving = false;
2503         break;
2504       default:
2505         this._runActions(name);
2506     }
2507   }
2508   _dispatchPageEvent(name, actions, pageNumber) {
2509     if (name === "PageOpen") {
2510       this._pageActions ||= new Map();
2511       if (!this._pageActions.has(pageNumber)) {
2512         this._pageActions.set(pageNumber, createActionsMap(actions));
2513       }
2514       this._pageNum = pageNumber - 1;
2515     }
2516     for (const acts of [this._pageActions, this._otherPageActions]) {
2517       actions = acts?.get(pageNumber)?.get(name);
2518       if (actions) {
2519         for (const action of actions) {
2520           this._globalEval(action);
2521         }
2522       }
2523     }
2524   }
2525   _runActions(name) {
2526     const actions = this._actions.get(name);
2527     if (actions) {
2528       for (const action of actions) {
2529         this._globalEval(action);
2530       }
2531     }
2532   }
2533   _addField(name, field) {
2534     this._fields.set(name, field);
2535     this._fieldNames.push(name);
2536     this._numFields++;
2537     const po = field.obj._actions.get("PageOpen");
2538     const pc = field.obj._actions.get("PageClose");
2539     if (po || pc) {
2540       this._otherPageActions ||= new Map();
2541       let actions = this._otherPageActions.get(field.obj._page + 1);
2542       if (!actions) {
2543         actions = new Map();
2544         this._otherPageActions.set(field.obj._page + 1, actions);
2545       }
2546       if (po) {
2547         let poActions = actions.get("PageOpen");
2548         if (!poActions) {
2549           poActions = [];
2550           actions.set("PageOpen", poActions);
2551         }
2552         poActions.push(...po);
2553       }
2554       if (pc) {
2555         let pcActions = actions.get("PageClose");
2556         if (!pcActions) {
2557           pcActions = [];
2558           actions.set("PageClose", pcActions);
2559         }
2560         pcActions.push(...pc);
2561       }
2562     }
2563   }
2564   _getDate(date) {
2565     if (!date || date.length < 15 || !date.startsWith("D:")) {
2566       return date;
2567     }
2568     date = date.substring(2);
2569     const year = date.substring(0, 4);
2570     const month = date.substring(4, 6);
2571     const day = date.substring(6, 8);
2572     const hour = date.substring(8, 10);
2573     const minute = date.substring(10, 12);
2574     const o = date.charAt(12);
2575     let second, offsetPos;
2576     if (o === "Z" || o === "+" || o === "-") {
2577       second = "00";
2578       offsetPos = 12;
2579     } else {
2580       second = date.substring(12, 14);
2581       offsetPos = 14;
2582     }
2583     const offset = date.substring(offsetPos).replaceAll("'", "");
2584     return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}${offset}`);
2585   }
2586   get author() {
2587     return this._author;
2588   }
2589   set author(_) {
2590     throw new Error("doc.author is read-only");
2591   }
2592   get baseURL() {
2593     return this._baseURL;
2594   }
2595   set baseURL(baseURL) {
2596     this._baseURL = baseURL;
2597   }
2598   get bookmarkRoot() {
2599     return undefined;
2600   }
2601   set bookmarkRoot(_) {
2602     throw new Error("doc.bookmarkRoot is read-only");
2603   }
2604   get calculate() {
2605     return this._calculate;
2606   }
2607   set calculate(calculate) {
2608     this._calculate = calculate;
2609   }
2610   get creator() {
2611     return this._creator;
2612   }
2613   set creator(_) {
2614     throw new Error("doc.creator is read-only");
2615   }
2616   get dataObjects() {
2617     return [];
2618   }
2619   set dataObjects(_) {
2620     throw new Error("doc.dataObjects is read-only");
2621   }
2622   get delay() {
2623     return this._delay;
2624   }
2625   set delay(delay) {
2626     this._delay = delay;
2627   }
2628   get dirty() {
2629     return this._dirty;
2630   }
2631   set dirty(dirty) {
2632     this._dirty = dirty;
2633   }
2634   get disclosed() {
2635     return this._disclosed;
2636   }
2637   set disclosed(disclosed) {
2638     this._disclosed = disclosed;
2639   }
2640   get docID() {
2641     return this._docID;
2642   }
2643   set docID(_) {
2644     throw new Error("doc.docID is read-only");
2645   }
2646   get documentFileName() {
2647     return this._documentFileName;
2648   }
2649   set documentFileName(_) {
2650     throw new Error("doc.documentFileName is read-only");
2651   }
2652   get dynamicXFAForm() {
2653     return false;
2654   }
2655   set dynamicXFAForm(_) {
2656     throw new Error("doc.dynamicXFAForm is read-only");
2657   }
2658   get external() {
2659     return DOC_EXTERNAL;
2660   }
2661   set external(_) {
2662     throw new Error("doc.external is read-only");
2663   }
2664   get filesize() {
2665     return this._filesize;
2666   }
2667   set filesize(_) {
2668     throw new Error("doc.filesize is read-only");
2669   }
2670   get hidden() {
2671     return false;
2672   }
2673   set hidden(_) {
2674     throw new Error("doc.hidden is read-only");
2675   }
2676   get hostContainer() {
2677     return undefined;
2678   }
2679   set hostContainer(_) {
2680     throw new Error("doc.hostContainer is read-only");
2681   }
2682   get icons() {
2683     return undefined;
2684   }
2685   set icons(_) {
2686     throw new Error("doc.icons is read-only");
2687   }
2688   get info() {
2689     return this._info;
2690   }
2691   set info(_) {
2692     throw new Error("doc.info is read-only");
2693   }
2694   get innerAppWindowRect() {
2695     return [0, 0, 0, 0];
2696   }
2697   set innerAppWindowRect(_) {
2698     throw new Error("doc.innerAppWindowRect is read-only");
2699   }
2700   get innerDocWindowRect() {
2701     return [0, 0, 0, 0];
2702   }
2703   set innerDocWindowRect(_) {
2704     throw new Error("doc.innerDocWindowRect is read-only");
2705   }
2706   get isModal() {
2707     return false;
2708   }
2709   set isModal(_) {
2710     throw new Error("doc.isModal is read-only");
2711   }
2712   get keywords() {
2713     return this._keywords;
2714   }
2715   set keywords(_) {
2716     throw new Error("doc.keywords is read-only");
2717   }
2718   get layout() {
2719     return this._layout;
2720   }
2721   set layout(value) {
2722     if (!this._userActivation) {
2723       return;
2724     }
2725     this._userActivation = false;
2726     if (typeof value !== "string") {
2727       return;
2728     }
2729     if (value !== "SinglePage" && value !== "OneColumn" && value !== "TwoColumnLeft" && value !== "TwoPageLeft" && value !== "TwoColumnRight" && value !== "TwoPageRight") {
2730       value = "SinglePage";
2731     }
2732     this._send({
2733       command: "layout",
2734       value
2735     });
2736     this._layout = value;
2737   }
2738   get media() {
2739     return this._media;
2740   }
2741   set media(media) {
2742     this._media = media;
2743   }
2744   get metadata() {
2745     return this._metadata;
2746   }
2747   set metadata(metadata) {
2748     this._metadata = metadata;
2749   }
2750   get modDate() {
2751     return this._modDate;
2752   }
2753   set modDate(_) {
2754     throw new Error("doc.modDate is read-only");
2755   }
2756   get mouseX() {
2757     return 0;
2758   }
2759   set mouseX(_) {
2760     throw new Error("doc.mouseX is read-only");
2761   }
2762   get mouseY() {
2763     return 0;
2764   }
2765   set mouseY(_) {
2766     throw new Error("doc.mouseY is read-only");
2767   }
2768   get noautocomplete() {
2769     return this._noautocomplete;
2770   }
2771   set noautocomplete(noautocomplete) {
2772     this._noautocomplete = noautocomplete;
2773   }
2774   get nocache() {
2775     return this._nocache;
2776   }
2777   set nocache(nocache) {
2778     this._nocache = nocache;
2779   }
2780   get numFields() {
2781     return this._numFields;
2782   }
2783   set numFields(_) {
2784     throw new Error("doc.numFields is read-only");
2785   }
2786   get numPages() {
2787     return this._numPages;
2788   }
2789   set numPages(_) {
2790     throw new Error("doc.numPages is read-only");
2791   }
2792   get numTemplates() {
2793     return 0;
2794   }
2795   set numTemplates(_) {
2796     throw new Error("doc.numTemplates is read-only");
2797   }
2798   get outerAppWindowRect() {
2799     return [0, 0, 0, 0];
2800   }
2801   set outerAppWindowRect(_) {
2802     throw new Error("doc.outerAppWindowRect is read-only");
2803   }
2804   get outerDocWindowRect() {
2805     return [0, 0, 0, 0];
2806   }
2807   set outerDocWindowRect(_) {
2808     throw new Error("doc.outerDocWindowRect is read-only");
2809   }
2810   get pageNum() {
2811     return this._pageNum;
2812   }
2813   set pageNum(value) {
2814     if (!this._userActivation) {
2815       return;
2816     }
2817     this._userActivation = false;
2818     if (typeof value !== "number" || value < 0 || value >= this._numPages) {
2819       return;
2820     }
2821     this._send({
2822       command: "page-num",
2823       value
2824     });
2825     this._pageNum = value;
2826   }
2827   get pageWindowRect() {
2828     return [0, 0, 0, 0];
2829   }
2830   set pageWindowRect(_) {
2831     throw new Error("doc.pageWindowRect is read-only");
2832   }
2833   get path() {
2834     return "";
2835   }
2836   set path(_) {
2837     throw new Error("doc.path is read-only");
2838   }
2839   get permStatusReady() {
2840     return true;
2841   }
2842   set permStatusReady(_) {
2843     throw new Error("doc.permStatusReady is read-only");
2844   }
2845   get producer() {
2846     return this._producer;
2847   }
2848   set producer(_) {
2849     throw new Error("doc.producer is read-only");
2850   }
2851   get requiresFullSave() {
2852     return false;
2853   }
2854   set requiresFullSave(_) {
2855     throw new Error("doc.requiresFullSave is read-only");
2856   }
2857   get securityHandler() {
2858     return this._securityHandler;
2859   }
2860   set securityHandler(_) {
2861     throw new Error("doc.securityHandler is read-only");
2862   }
2863   get selectedAnnots() {
2864     return [];
2865   }
2866   set selectedAnnots(_) {
2867     throw new Error("doc.selectedAnnots is read-only");
2868   }
2869   get sounds() {
2870     return [];
2871   }
2872   set sounds(_) {
2873     throw new Error("doc.sounds is read-only");
2874   }
2875   get spellDictionaryOrder() {
2876     return this._spellDictionaryOrder;
2877   }
2878   set spellDictionaryOrder(spellDictionaryOrder) {
2879     this._spellDictionaryOrder = spellDictionaryOrder;
2880   }
2881   get spellLanguageOrder() {
2882     return this._spellLanguageOrder;
2883   }
2884   set spellLanguageOrder(spellLanguageOrder) {
2885     this._spellLanguageOrder = spellLanguageOrder;
2886   }
2887   get subject() {
2888     return this._subject;
2889   }
2890   set subject(_) {
2891     throw new Error("doc.subject is read-only");
2892   }
2893   get templates() {
2894     return [];
2895   }
2896   set templates(_) {
2897     throw new Error("doc.templates is read-only");
2898   }
2899   get title() {
2900     return this._title;
2901   }
2902   set title(_) {
2903     throw new Error("doc.title is read-only");
2904   }
2905   get URL() {
2906     return this._URL;
2907   }
2908   set URL(_) {
2909     throw new Error("doc.URL is read-only");
2910   }
2911   get viewState() {
2912     return undefined;
2913   }
2914   set viewState(_) {
2915     throw new Error("doc.viewState is read-only");
2916   }
2917   get xfa() {
2918     return this._xfa;
2919   }
2920   set xfa(_) {
2921     throw new Error("doc.xfa is read-only");
2922   }
2923   get XFAForeground() {
2924     return false;
2925   }
2926   set XFAForeground(_) {
2927     throw new Error("doc.XFAForeground is read-only");
2928   }
2929   get zoomType() {
2930     return this._zoomType;
2931   }
2932   set zoomType(type) {
2933     if (!this._userActivation) {
2934       return;
2935     }
2936     this._userActivation = false;
2937     if (typeof type !== "string") {
2938       return;
2939     }
2940     switch (type) {
2941       case ZoomType.none:
2942         this._send({
2943           command: "zoom",
2944           value: 1
2945         });
2946         break;
2947       case ZoomType.fitP:
2948         this._send({
2949           command: "zoom",
2950           value: "page-fit"
2951         });
2952         break;
2953       case ZoomType.fitW:
2954         this._send({
2955           command: "zoom",
2956           value: "page-width"
2957         });
2958         break;
2959       case ZoomType.fitH:
2960         this._send({
2961           command: "zoom",
2962           value: "page-height"
2963         });
2964         break;
2965       case ZoomType.fitV:
2966         this._send({
2967           command: "zoom",
2968           value: "auto"
2969         });
2970         break;
2971       case ZoomType.pref:
2972       case ZoomType.refW:
2973         break;
2974       default:
2975         return;
2976     }
2977     this._zoomType = type;
2978   }
2979   get zoom() {
2980     return this._zoom;
2981   }
2982   set zoom(value) {
2983     if (!this._userActivation) {
2984       return;
2985     }
2986     this._userActivation = false;
2987     if (typeof value !== "number" || value < 8.33 || value > 6400) {
2988       return;
2989     }
2990     this._send({
2991       command: "zoom",
2992       value: value / 100
2993     });
2994   }
2995   addAnnot() {}
2996   addField() {}
2997   addIcon() {}
2998   addLink() {}
2999   addRecipientListCryptFilter() {}
3000   addRequirement() {}
3001   addScript() {}
3002   addThumbnails() {}
3003   addWatermarkFromFile() {}
3004   addWatermarkFromText() {}
3005   addWeblinks() {}
3006   bringToFront() {}
3007   calculateNow() {
3008     this._eventDispatcher.calculateNow();
3009   }
3010   closeDoc() {}
3011   colorConvertPage() {}
3012   createDataObject() {}
3013   createTemplate() {}
3014   deletePages() {}
3015   deleteSound() {}
3016   embedDocAsDataObject() {}
3017   embedOutputIntent() {}
3018   encryptForRecipients() {}
3019   encryptUsingPolicy() {}
3020   exportAsFDF() {}
3021   exportAsFDFStr() {}
3022   exportAsText() {}
3023   exportAsXFDF() {}
3024   exportAsXFDFStr() {}
3025   exportDataObject() {}
3026   exportXFAData() {}
3027   extractPages() {}
3028   flattenPages() {}
3029   getAnnot() {}
3030   getAnnots() {}
3031   getAnnot3D() {}
3032   getAnnots3D() {}
3033   getColorConvertAction() {}
3034   getDataObject() {}
3035   getDataObjectContents() {}
3036   _getField(cName) {
3037     if (cName && typeof cName === "object") {
3038       cName = cName.cName;
3039     }
3040     if (typeof cName !== "string") {
3041       throw new TypeError("Invalid field name: must be a string");
3042     }
3043     const searchedField = this._fields.get(cName);
3044     if (searchedField) {
3045       return searchedField;
3046     }
3047     const parts = cName.split("#");
3048     let childIndex = NaN;
3049     if (parts.length === 2) {
3050       childIndex = Math.floor(parseFloat(parts[1]));
3051       cName = parts[0];
3052     }
3053     for (const [name, field] of this._fields.entries()) {
3054       if (name.endsWith(cName)) {
3055         if (!isNaN(childIndex)) {
3056           const children = this._getChildren(name);
3057           if (childIndex < 0 || childIndex >= children.length) {
3058             childIndex = 0;
3059           }
3060           if (childIndex < children.length) {
3061             this._fields.set(cName, children[childIndex]);
3062             return children[childIndex];
3063           }
3064         }
3065         this._fields.set(cName, field);
3066         return field;
3067       }
3068     }
3069     return null;
3070   }
3071   getField(cName) {
3072     const field = this._getField(cName);
3073     if (!field) {
3074       return null;
3075     }
3076     return field.wrapped;
3077   }
3078   _getChildren(fieldName) {
3079     const len = fieldName.length;
3080     const children = [];
3081     const pattern = /^\.[^.]+$/;
3082     for (const [name, field] of this._fields.entries()) {
3083       if (name.startsWith(fieldName)) {
3084         const finalPart = name.slice(len);
3085         if (pattern.test(finalPart)) {
3086           children.push(field);
3087         }
3088       }
3089     }
3090     return children;
3091   }
3092   _getTerminalChildren(fieldName) {
3093     const children = [];
3094     const len = fieldName.length;
3095     for (const [name, field] of this._fields.entries()) {
3096       if (name.startsWith(fieldName)) {
3097         const finalPart = name.slice(len);
3098         if (field.obj._hasValue && (finalPart === "" || finalPart.startsWith("."))) {
3099           children.push(field.wrapped);
3100         }
3101       }
3102     }
3103     return children;
3104   }
3105   getIcon() {}
3106   getLegalWarnings() {}
3107   getLinks() {}
3108   getNthFieldName(nIndex) {
3109     if (nIndex && typeof nIndex === "object") {
3110       nIndex = nIndex.nIndex;
3111     }
3112     if (typeof nIndex !== "number") {
3113       throw new TypeError("Invalid field index: must be a number");
3114     }
3115     if (0 <= nIndex && nIndex < this.numFields) {
3116       return this._fieldNames[Math.trunc(nIndex)];
3117     }
3118     return null;
3119   }
3120   getNthTemplate() {
3121     return null;
3122   }
3123   getOCGs() {}
3124   getOCGOrder() {}
3125   getPageBox() {}
3126   getPageLabel() {}
3127   getPageNthWord() {}
3128   getPageNthWordQuads() {}
3129   getPageNumWords() {}
3130   getPageRotation() {}
3131   getPageTransition() {}
3132   getPrintParams() {
3133     return this._printParams ||= new PrintParams({
3134       lastPage: this._numPages - 1
3135     });
3136   }
3137   getSound() {}
3138   getTemplate() {}
3139   getURL() {}
3140   gotoNamedDest() {}
3141   importAnFDF() {}
3142   importAnXFDF() {}
3143   importDataObject() {}
3144   importIcon() {}
3145   importSound() {}
3146   importTextData() {}
3147   importXFAData() {}
3148   insertPages() {}
3149   mailDoc() {}
3150   mailForm() {}
3151   movePage() {}
3152   newPage() {}
3153   openDataObject() {}
3154   print(bUI = true, nStart = 0, nEnd = -1, bSilent = false, bShrinkToFit = false, bPrintAsImage = false, bReverse = false, bAnnotations = true, printParams = null) {
3155     if (this._disablePrinting || !this._userActivation) {
3156       return;
3157     }
3158     this._userActivation = false;
3159     if (bUI && typeof bUI === "object") {
3160       nStart = bUI.nStart;
3161       nEnd = bUI.nEnd;
3162       bSilent = bUI.bSilent;
3163       bShrinkToFit = bUI.bShrinkToFit;
3164       bPrintAsImage = bUI.bPrintAsImage;
3165       bReverse = bUI.bReverse;
3166       bAnnotations = bUI.bAnnotations;
3167       printParams = bUI.printParams;
3168       bUI = bUI.bUI;
3169     }
3170     if (printParams) {
3171       nStart = printParams.firstPage;
3172       nEnd = printParams.lastPage;
3173     }
3174     nStart = typeof nStart === "number" ? Math.max(0, Math.trunc(nStart)) : 0;
3175     nEnd = typeof nEnd === "number" ? Math.max(0, Math.trunc(nEnd)) : -1;
3176     this._send({
3177       command: "print",
3178       start: nStart,
3179       end: nEnd
3180     });
3181   }
3182   removeDataObject() {}
3183   removeField() {}
3184   removeIcon() {}
3185   removeLinks() {}
3186   removeRequirement() {}
3187   removeScript() {}
3188   removeTemplate() {}
3189   removeThumbnails() {}
3190   removeWeblinks() {}
3191   replacePages() {}
3192   resetForm(aFields = null) {
3193     if (aFields && typeof aFields === "object" && !Array.isArray(aFields)) {
3194       aFields = aFields.aFields;
3195     }
3196     if (aFields && !Array.isArray(aFields)) {
3197       aFields = [aFields];
3198     }
3199     let mustCalculate = false;
3200     let fieldsToReset;
3201     if (aFields) {
3202       fieldsToReset = [];
3203       for (const fieldName of aFields) {
3204         if (!fieldName) {
3205           continue;
3206         }
3207         if (typeof fieldName !== "string") {
3208           fieldsToReset = null;
3209           break;
3210         }
3211         const field = this._getField(fieldName);
3212         if (!field) {
3213           continue;
3214         }
3215         fieldsToReset.push(field);
3216         mustCalculate = true;
3217       }
3218     }
3219     if (!fieldsToReset) {
3220       fieldsToReset = this._fields.values();
3221       mustCalculate = this._fields.size !== 0;
3222     }
3223     for (const field of fieldsToReset) {
3224       field.obj.value = field.obj.defaultValue;
3225       this._send({
3226         id: field.obj._id,
3227         siblings: field.obj._siblings,
3228         value: field.obj.defaultValue,
3229         formattedValue: null,
3230         selRange: [0, 0]
3231       });
3232     }
3233     if (mustCalculate) {
3234       this.calculateNow();
3235     }
3236   }
3237   saveAs() {}
3238   scroll() {}
3239   selectPageNthWord() {}
3240   setAction() {}
3241   setDataObjectContents() {}
3242   setOCGOrder() {}
3243   setPageAction() {}
3244   setPageBoxes() {}
3245   setPageLabels() {}
3246   setPageRotations() {}
3247   setPageTabOrder() {}
3248   setPageTransitions() {}
3249   spawnPageFromTemplate() {}
3250   submitForm() {}
3251   syncAnnotScan() {}
3254 ;// ./src/scripting_api/proxy.js
3255 class ProxyHandler {
3256   constructor() {
3257     this.nosend = new Set(["delay"]);
3258   }
3259   get(obj, prop) {
3260     if (prop in obj._expandos) {
3261       const val = obj._expandos[prop];
3262       if (typeof val === "function") {
3263         return val.bind(obj);
3264       }
3265       return val;
3266     }
3267     if (typeof prop === "string" && !prop.startsWith("_") && prop in obj) {
3268       const val = obj[prop];
3269       if (typeof val === "function") {
3270         return val.bind(obj);
3271       }
3272       return val;
3273     }
3274     return undefined;
3275   }
3276   set(obj, prop, value) {
3277     if (obj._kidIds) {
3278       obj._kidIds.forEach(id => {
3279         obj._appObjects[id].wrapped[prop] = value;
3280       });
3281     }
3282     if (typeof prop === "string" && !prop.startsWith("_") && prop in obj) {
3283       const old = obj[prop];
3284       obj[prop] = value;
3285       if (!this.nosend.has(prop) && obj._send && obj._id !== null && typeof old !== "function") {
3286         const data = {
3287           id: obj._id
3288         };
3289         data[prop] = prop === "value" ? obj._getValue() : obj[prop];
3290         if (!obj._siblings) {
3291           obj._send(data);
3292         } else {
3293           data.siblings = obj._siblings;
3294           obj._send(data);
3295         }
3296       }
3297     } else {
3298       obj._expandos[prop] = value;
3299     }
3300     return true;
3301   }
3302   has(obj, prop) {
3303     return prop in obj._expandos || typeof prop === "string" && !prop.startsWith("_") && prop in obj;
3304   }
3305   getPrototypeOf(obj) {
3306     return null;
3307   }
3308   setPrototypeOf(obj, proto) {
3309     return false;
3310   }
3311   isExtensible(obj) {
3312     return true;
3313   }
3314   preventExtensions(obj) {
3315     return false;
3316   }
3317   getOwnPropertyDescriptor(obj, prop) {
3318     if (prop in obj._expandos) {
3319       return {
3320         configurable: true,
3321         enumerable: true,
3322         value: obj._expandos[prop]
3323       };
3324     }
3325     if (typeof prop === "string" && !prop.startsWith("_") && prop in obj) {
3326       return {
3327         configurable: true,
3328         enumerable: true,
3329         value: obj[prop]
3330       };
3331     }
3332     return undefined;
3333   }
3334   defineProperty(obj, key, descriptor) {
3335     Object.defineProperty(obj._expandos, key, descriptor);
3336     return true;
3337   }
3338   deleteProperty(obj, prop) {
3339     if (prop in obj._expandos) {
3340       delete obj._expandos[prop];
3341     }
3342   }
3343   ownKeys(obj) {
3344     const fromExpandos = Reflect.ownKeys(obj._expandos);
3345     const fromObj = Reflect.ownKeys(obj).filter(k => !k.startsWith("_"));
3346     return fromExpandos.concat(fromObj);
3347   }
3350 ;// ./src/scripting_api/util.js
3352 class Util extends PDFObject {
3353   #dateActionsCache = null;
3354   constructor(data) {
3355     super(data);
3356     this._scandCache = new Map();
3357     this._months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
3358     this._days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
3359     this.MILLISECONDS_IN_DAY = 86400000;
3360     this.MILLISECONDS_IN_WEEK = 604800000;
3361     this._externalCall = data.externalCall;
3362   }
3363   printf(...args) {
3364     if (args.length === 0) {
3365       throw new Error("Invalid number of params in printf");
3366     }
3367     if (typeof args[0] !== "string") {
3368       throw new TypeError("First argument of printf must be a string");
3369     }
3370     const pattern = /%(,[0-4])?([+ 0#]+)?(\d+)?(\.\d+)?(.)/g;
3371     const PLUS = 1;
3372     const SPACE = 2;
3373     const ZERO = 4;
3374     const HASH = 8;
3375     let i = 0;
3376     return args[0].replaceAll(pattern, function (match, nDecSep, cFlags, nWidth, nPrecision, cConvChar) {
3377       if (cConvChar !== "d" && cConvChar !== "f" && cConvChar !== "s" && cConvChar !== "x") {
3378         const buf = ["%"];
3379         for (const str of [nDecSep, cFlags, nWidth, nPrecision, cConvChar]) {
3380           if (str) {
3381             buf.push(str);
3382           }
3383         }
3384         return buf.join("");
3385       }
3386       i++;
3387       if (i === args.length) {
3388         throw new Error("Not enough arguments in printf");
3389       }
3390       const arg = args[i];
3391       if (cConvChar === "s") {
3392         return arg.toString();
3393       }
3394       let flags = 0;
3395       if (cFlags) {
3396         for (const flag of cFlags) {
3397           switch (flag) {
3398             case "+":
3399               flags |= PLUS;
3400               break;
3401             case " ":
3402               flags |= SPACE;
3403               break;
3404             case "0":
3405               flags |= ZERO;
3406               break;
3407             case "#":
3408               flags |= HASH;
3409               break;
3410           }
3411         }
3412       }
3413       cFlags = flags;
3414       if (nWidth) {
3415         nWidth = parseInt(nWidth);
3416       }
3417       let intPart = Math.trunc(arg);
3418       if (cConvChar === "x") {
3419         let hex = Math.abs(intPart).toString(16).toUpperCase();
3420         if (nWidth !== undefined) {
3421           hex = hex.padStart(nWidth, cFlags & ZERO ? "0" : " ");
3422         }
3423         if (cFlags & HASH) {
3424           hex = `0x${hex}`;
3425         }
3426         return hex;
3427       }
3428       if (nPrecision) {
3429         nPrecision = parseInt(nPrecision.substring(1));
3430       }
3431       nDecSep = nDecSep ? nDecSep.substring(1) : "0";
3432       const separators = {
3433         0: [",", "."],
3434         1: ["", "."],
3435         2: [".", ","],
3436         3: ["", ","],
3437         4: ["'", "."]
3438       };
3439       const [thousandSep, decimalSep] = separators[nDecSep];
3440       let decPart = "";
3441       if (cConvChar === "f") {
3442         decPart = nPrecision !== undefined ? Math.abs(arg - intPart).toFixed(nPrecision) : Math.abs(arg - intPart).toString();
3443         if (decPart.length > 2) {
3444           if (/^1\.0+$/.test(decPart)) {
3445             intPart += Math.sign(arg);
3446             decPart = `${decimalSep}${decPart.split(".")[1]}`;
3447           } else {
3448             decPart = `${decimalSep}${decPart.substring(2)}`;
3449           }
3450         } else {
3451           if (decPart === "1") {
3452             intPart += Math.sign(arg);
3453           }
3454           decPart = cFlags & HASH ? "." : "";
3455         }
3456       }
3457       let sign = "";
3458       if (intPart < 0) {
3459         sign = "-";
3460         intPart = -intPart;
3461       } else if (cFlags & PLUS) {
3462         sign = "+";
3463       } else if (cFlags & SPACE) {
3464         sign = " ";
3465       }
3466       if (thousandSep && intPart >= 1000) {
3467         const buf = [];
3468         while (true) {
3469           buf.push((intPart % 1000).toString().padStart(3, "0"));
3470           intPart = Math.trunc(intPart / 1000);
3471           if (intPart < 1000) {
3472             buf.push(intPart.toString());
3473             break;
3474           }
3475         }
3476         intPart = buf.reverse().join(thousandSep);
3477       } else {
3478         intPart = intPart.toString();
3479       }
3480       let n = `${intPart}${decPart}`;
3481       if (nWidth !== undefined) {
3482         n = n.padStart(nWidth - sign.length, cFlags & ZERO ? "0" : " ");
3483       }
3484       return `${sign}${n}`;
3485     });
3486   }
3487   iconStreamFromIcon() {}
3488   printd(cFormat, oDate) {
3489     switch (cFormat) {
3490       case 0:
3491         return this.printd("D:yyyymmddHHMMss", oDate);
3492       case 1:
3493         return this.printd("yyyy.mm.dd HH:MM:ss", oDate);
3494       case 2:
3495         return this.printd("m/d/yy h:MM:ss tt", oDate);
3496     }
3497     const handlers = {
3498       mmmm: data => this._months[data.month],
3499       mmm: data => this._months[data.month].substring(0, 3),
3500       mm: data => (data.month + 1).toString().padStart(2, "0"),
3501       m: data => (data.month + 1).toString(),
3502       dddd: data => this._days[data.dayOfWeek],
3503       ddd: data => this._days[data.dayOfWeek].substring(0, 3),
3504       dd: data => data.day.toString().padStart(2, "0"),
3505       d: data => data.day.toString(),
3506       yyyy: data => data.year.toString(),
3507       yy: data => (data.year % 100).toString().padStart(2, "0"),
3508       HH: data => data.hours.toString().padStart(2, "0"),
3509       H: data => data.hours.toString(),
3510       hh: data => (1 + (data.hours + 11) % 12).toString().padStart(2, "0"),
3511       h: data => (1 + (data.hours + 11) % 12).toString(),
3512       MM: data => data.minutes.toString().padStart(2, "0"),
3513       M: data => data.minutes.toString(),
3514       ss: data => data.seconds.toString().padStart(2, "0"),
3515       s: data => data.seconds.toString(),
3516       tt: data => data.hours < 12 ? "am" : "pm",
3517       t: data => data.hours < 12 ? "a" : "p"
3518     };
3519     const data = {
3520       year: oDate.getFullYear(),
3521       month: oDate.getMonth(),
3522       day: oDate.getDate(),
3523       dayOfWeek: oDate.getDay(),
3524       hours: oDate.getHours(),
3525       minutes: oDate.getMinutes(),
3526       seconds: oDate.getSeconds()
3527     };
3528     const patterns = /(mmmm|mmm|mm|m|dddd|ddd|dd|d|yyyy|yy|HH|H|hh|h|MM|M|ss|s|tt|t|\\.)/g;
3529     return cFormat.replaceAll(patterns, function (match, pattern) {
3530       if (pattern in handlers) {
3531         return handlers[pattern](data);
3532       }
3533       return pattern.charCodeAt(1);
3534     });
3535   }
3536   printx(cFormat, cSource) {
3537     cSource = (cSource ?? "").toString();
3538     const handlers = [x => x, x => x.toUpperCase(), x => x.toLowerCase()];
3539     const buf = [];
3540     let i = 0;
3541     const ii = cSource.length;
3542     let currCase = handlers[0];
3543     let escaped = false;
3544     for (const command of cFormat) {
3545       if (escaped) {
3546         buf.push(command);
3547         escaped = false;
3548         continue;
3549       }
3550       if (i >= ii) {
3551         break;
3552       }
3553       switch (command) {
3554         case "?":
3555           buf.push(currCase(cSource.charAt(i++)));
3556           break;
3557         case "X":
3558           while (i < ii) {
3559             const char = cSource.charAt(i++);
3560             if ("a" <= char && char <= "z" || "A" <= char && char <= "Z" || "0" <= char && char <= "9") {
3561               buf.push(currCase(char));
3562               break;
3563             }
3564           }
3565           break;
3566         case "A":
3567           while (i < ii) {
3568             const char = cSource.charAt(i++);
3569             if ("a" <= char && char <= "z" || "A" <= char && char <= "Z") {
3570               buf.push(currCase(char));
3571               break;
3572             }
3573           }
3574           break;
3575         case "9":
3576           while (i < ii) {
3577             const char = cSource.charAt(i++);
3578             if ("0" <= char && char <= "9") {
3579               buf.push(char);
3580               break;
3581             }
3582           }
3583           break;
3584         case "*":
3585           while (i < ii) {
3586             buf.push(currCase(cSource.charAt(i++)));
3587           }
3588           break;
3589         case "\\":
3590           escaped = true;
3591           break;
3592         case ">":
3593           currCase = handlers[1];
3594           break;
3595         case "<":
3596           currCase = handlers[2];
3597           break;
3598         case "=":
3599           currCase = handlers[0];
3600           break;
3601         default:
3602           buf.push(command);
3603       }
3604     }
3605     return buf.join("");
3606   }
3607   #tryToGuessDate(cFormat, cDate) {
3608     let actions = (this.#dateActionsCache ||= new Map()).get(cFormat);
3609     if (!actions) {
3610       actions = [];
3611       this.#dateActionsCache.set(cFormat, actions);
3612       cFormat.replaceAll(/(d+)|(m+)|(y+)|(H+)|(M+)|(s+)/g, function (_match, d, m, y, H, M, s) {
3613         if (d) {
3614           actions.push((n, data) => {
3615             if (n >= 1 && n <= 31) {
3616               data.day = n;
3617               return true;
3618             }
3619             return false;
3620           });
3621         } else if (m) {
3622           actions.push((n, data) => {
3623             if (n >= 1 && n <= 12) {
3624               data.month = n - 1;
3625               return true;
3626             }
3627             return false;
3628           });
3629         } else if (y) {
3630           actions.push((n, data) => {
3631             if (n < 50) {
3632               n += 2000;
3633             } else if (n < 100) {
3634               n += 1900;
3635             }
3636             data.year = n;
3637             return true;
3638           });
3639         } else if (H) {
3640           actions.push((n, data) => {
3641             if (n >= 0 && n <= 23) {
3642               data.hours = n;
3643               return true;
3644             }
3645             return false;
3646           });
3647         } else if (M) {
3648           actions.push((n, data) => {
3649             if (n >= 0 && n <= 59) {
3650               data.minutes = n;
3651               return true;
3652             }
3653             return false;
3654           });
3655         } else if (s) {
3656           actions.push((n, data) => {
3657             if (n >= 0 && n <= 59) {
3658               data.seconds = n;
3659               return true;
3660             }
3661             return false;
3662           });
3663         }
3664         return "";
3665       });
3666     }
3667     const number = /\d+/g;
3668     let i = 0;
3669     let array;
3670     const data = {
3671       year: new Date().getFullYear(),
3672       month: 0,
3673       day: 1,
3674       hours: 12,
3675       minutes: 0,
3676       seconds: 0
3677     };
3678     while ((array = number.exec(cDate)) !== null) {
3679       if (i < actions.length) {
3680         if (!actions[i++](parseInt(array[0]), data)) {
3681           return null;
3682         }
3683       } else {
3684         break;
3685       }
3686     }
3687     if (i === 0) {
3688       return null;
3689     }
3690     return new Date(data.year, data.month, data.day, data.hours, data.minutes, data.seconds);
3691   }
3692   scand(cFormat, cDate) {
3693     return this._scand(cFormat, cDate);
3694   }
3695   _scand(cFormat, cDate, strict = false) {
3696     if (typeof cDate !== "string") {
3697       return new Date(cDate);
3698     }
3699     if (cDate === "") {
3700       return new Date();
3701     }
3702     switch (cFormat) {
3703       case 0:
3704         return this.scand("D:yyyymmddHHMMss", cDate);
3705       case 1:
3706         return this.scand("yyyy.mm.dd HH:MM:ss", cDate);
3707       case 2:
3708         return this.scand("m/d/yy h:MM:ss tt", cDate);
3709     }
3710     if (!this._scandCache.has(cFormat)) {
3711       const months = this._months;
3712       const days = this._days;
3713       const handlers = {
3714         mmmm: {
3715           pattern: `(${months.join("|")})`,
3716           action: (value, data) => {
3717             data.month = months.indexOf(value);
3718           }
3719         },
3720         mmm: {
3721           pattern: `(${months.map(month => month.substring(0, 3)).join("|")})`,
3722           action: (value, data) => {
3723             data.month = months.findIndex(month => month.substring(0, 3) === value);
3724           }
3725         },
3726         mm: {
3727           pattern: `(\\d{2})`,
3728           action: (value, data) => {
3729             data.month = parseInt(value) - 1;
3730           }
3731         },
3732         m: {
3733           pattern: `(\\d{1,2})`,
3734           action: (value, data) => {
3735             data.month = parseInt(value) - 1;
3736           }
3737         },
3738         dddd: {
3739           pattern: `(${days.join("|")})`,
3740           action: (value, data) => {
3741             data.day = days.indexOf(value);
3742           }
3743         },
3744         ddd: {
3745           pattern: `(${days.map(day => day.substring(0, 3)).join("|")})`,
3746           action: (value, data) => {
3747             data.day = days.findIndex(day => day.substring(0, 3) === value);
3748           }
3749         },
3750         dd: {
3751           pattern: "(\\d{2})",
3752           action: (value, data) => {
3753             data.day = parseInt(value);
3754           }
3755         },
3756         d: {
3757           pattern: "(\\d{1,2})",
3758           action: (value, data) => {
3759             data.day = parseInt(value);
3760           }
3761         },
3762         yyyy: {
3763           pattern: "(\\d{4})",
3764           action: (value, data) => {
3765             data.year = parseInt(value);
3766           }
3767         },
3768         yy: {
3769           pattern: "(\\d{2})",
3770           action: (value, data) => {
3771             data.year = 2000 + parseInt(value);
3772           }
3773         },
3774         HH: {
3775           pattern: "(\\d{2})",
3776           action: (value, data) => {
3777             data.hours = parseInt(value);
3778           }
3779         },
3780         H: {
3781           pattern: "(\\d{1,2})",
3782           action: (value, data) => {
3783             data.hours = parseInt(value);
3784           }
3785         },
3786         hh: {
3787           pattern: "(\\d{2})",
3788           action: (value, data) => {
3789             data.hours = parseInt(value);
3790           }
3791         },
3792         h: {
3793           pattern: "(\\d{1,2})",
3794           action: (value, data) => {
3795             data.hours = parseInt(value);
3796           }
3797         },
3798         MM: {
3799           pattern: "(\\d{2})",
3800           action: (value, data) => {
3801             data.minutes = parseInt(value);
3802           }
3803         },
3804         M: {
3805           pattern: "(\\d{1,2})",
3806           action: (value, data) => {
3807             data.minutes = parseInt(value);
3808           }
3809         },
3810         ss: {
3811           pattern: "(\\d{2})",
3812           action: (value, data) => {
3813             data.seconds = parseInt(value);
3814           }
3815         },
3816         s: {
3817           pattern: "(\\d{1,2})",
3818           action: (value, data) => {
3819             data.seconds = parseInt(value);
3820           }
3821         },
3822         tt: {
3823           pattern: "([aApP][mM])",
3824           action: (value, data) => {
3825             const char = value.charAt(0);
3826             data.am = char === "a" || char === "A";
3827           }
3828         },
3829         t: {
3830           pattern: "([aApP])",
3831           action: (value, data) => {
3832             data.am = value === "a" || value === "A";
3833           }
3834         }
3835       };
3836       const escapedFormat = cFormat.replaceAll(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
3837       const patterns = /(mmmm|mmm|mm|m|dddd|ddd|dd|d|yyyy|yy|HH|H|hh|h|MM|M|ss|s|tt|t)/g;
3838       const actions = [];
3839       const re = escapedFormat.replaceAll(patterns, function (match, patternElement) {
3840         const {
3841           pattern,
3842           action
3843         } = handlers[patternElement];
3844         actions.push(action);
3845         return pattern;
3846       });
3847       this._scandCache.set(cFormat, [re, actions]);
3848     }
3849     const [re, actions] = this._scandCache.get(cFormat);
3850     const matches = new RegExp(`^${re}$`, "g").exec(cDate);
3851     if (!matches || matches.length !== actions.length + 1) {
3852       return strict ? null : this.#tryToGuessDate(cFormat, cDate);
3853     }
3854     const data = {
3855       year: new Date().getFullYear(),
3856       month: 0,
3857       day: 1,
3858       hours: 12,
3859       minutes: 0,
3860       seconds: 0,
3861       am: null
3862     };
3863     actions.forEach((action, i) => action(matches[i + 1], data));
3864     if (data.am !== null) {
3865       data.hours = data.hours % 12 + (data.am ? 0 : 12);
3866     }
3867     return new Date(data.year, data.month, data.day, data.hours, data.minutes, data.seconds);
3868   }
3869   spansToXML() {}
3870   stringFromStream() {}
3871   xmlToSpans() {}
3874 ;// ./src/scripting_api/initialization.js
3885 function initSandbox(params) {
3886   delete globalThis.pdfjsScripting;
3887   const externalCall = globalThis.callExternalFunction;
3888   delete globalThis.callExternalFunction;
3889   const globalEval = code => globalThis.eval(code);
3890   const send = data => externalCall("send", [data]);
3891   const proxyHandler = new ProxyHandler();
3892   const {
3893     data
3894   } = params;
3895   const doc = new Doc({
3896     send,
3897     globalEval,
3898     ...data.docInfo
3899   });
3900   const _document = {
3901     obj: doc,
3902     wrapped: new Proxy(doc, proxyHandler)
3903   };
3904   const app = new App({
3905     send,
3906     globalEval,
3907     externalCall,
3908     _document,
3909     calculationOrder: data.calculationOrder,
3910     proxyHandler,
3911     ...data.appInfo
3912   });
3913   const util = new Util({
3914     externalCall
3915   });
3916   const appObjects = app._objects;
3917   if (data.objects) {
3918     const annotations = [];
3919     for (const [name, objs] of Object.entries(data.objects)) {
3920       annotations.length = 0;
3921       let container = null;
3922       for (const obj of objs) {
3923         if (obj.type !== "") {
3924           annotations.push(obj);
3925         } else {
3926           container = obj;
3927         }
3928       }
3929       let obj = container;
3930       if (annotations.length > 0) {
3931         obj = annotations[0];
3932         obj.send = send;
3933       }
3934       obj.globalEval = globalEval;
3935       obj.doc = _document;
3936       obj.fieldPath = name;
3937       obj.appObjects = appObjects;
3938       const otherFields = annotations.slice(1);
3939       let field;
3940       switch (obj.type) {
3941         case "radiobutton":
3942           {
3943             field = new RadioButtonField(otherFields, obj);
3944             break;
3945           }
3946         case "checkbox":
3947           {
3948             field = new CheckboxField(otherFields, obj);
3949             break;
3950           }
3951         default:
3952           if (otherFields.length > 0) {
3953             obj.siblings = otherFields.map(x => x.id);
3954           }
3955           field = new Field(obj);
3956       }
3957       const wrapped = new Proxy(field, proxyHandler);
3958       const _object = {
3959         obj: field,
3960         wrapped
3961       };
3962       doc._addField(name, _object);
3963       for (const object of objs) {
3964         appObjects[object.id] = _object;
3965       }
3966       if (container) {
3967         appObjects[container.id] = _object;
3968       }
3969     }
3970   }
3971   const color = new Color();
3972   globalThis.event = null;
3973   globalThis.global = Object.create(null);
3974   globalThis.app = new Proxy(app, proxyHandler);
3975   globalThis.color = new Proxy(color, proxyHandler);
3976   globalThis.console = new Proxy(new Console({
3977     send
3978   }), proxyHandler);
3979   globalThis.util = new Proxy(util, proxyHandler);
3980   globalThis.border = Border;
3981   globalThis.cursor = Cursor;
3982   globalThis.display = Display;
3983   globalThis.font = Font;
3984   globalThis.highlight = Highlight;
3985   globalThis.position = Position;
3986   globalThis.scaleHow = ScaleHow;
3987   globalThis.scaleWhen = ScaleWhen;
3988   globalThis.style = Style;
3989   globalThis.trans = Trans;
3990   globalThis.zoomtype = ZoomType;
3991   globalThis.ADBE = {
3992     Reader_Value_Asked: true,
3993     Viewer_Value_Asked: true
3994   };
3995   const aform = new AForm(doc, app, util, color);
3996   for (const name of Object.getOwnPropertyNames(AForm.prototype)) {
3997     if (name !== "constructor" && !name.startsWith("_")) {
3998       globalThis[name] = aform[name].bind(aform);
3999     }
4000   }
4001   for (const [name, value] of Object.entries(GlobalConstants)) {
4002     Object.defineProperty(globalThis, name, {
4003       value,
4004       writable: false
4005     });
4006   }
4007   Object.defineProperties(globalThis, {
4008     ColorConvert: {
4009       value: color.convert.bind(color),
4010       writable: true
4011     },
4012     ColorEqual: {
4013       value: color.equal.bind(color),
4014       writable: true
4015     }
4016   });
4017   const properties = Object.create(null);
4018   for (const name of Object.getOwnPropertyNames(Doc.prototype)) {
4019     if (name === "constructor" || name.startsWith("_")) {
4020       continue;
4021     }
4022     const descriptor = Object.getOwnPropertyDescriptor(Doc.prototype, name);
4023     if (descriptor.get) {
4024       properties[name] = {
4025         get: descriptor.get.bind(doc),
4026         set: descriptor.set.bind(doc)
4027       };
4028     } else {
4029       properties[name] = {
4030         value: Doc.prototype[name].bind(doc)
4031       };
4032     }
4033   }
4034   Object.defineProperties(globalThis, properties);
4035   const functions = {
4036     dispatchEvent: app._dispatchEvent.bind(app),
4037     timeoutCb: app._evalCallback.bind(app)
4038   };
4039   return (name, args) => {
4040     try {
4041       functions[name](args);
4042     } catch (error) {
4043       send(serializeError(error));
4044     }
4045   };
4048 ;// ./src/pdf.scripting.js
4050 const pdfjsVersion = "5.0.98";
4051 const pdfjsBuild = "16155fd80";
4052 globalThis.pdfjsScripting = {
4053   initSandbox: initSandbox