2 * @licstart The following is the entire license notice for the
3 * JavaScript code in this page
5 * Copyright 2024 Mozilla Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * @licend The above is the entire license notice for the
20 * JavaScript code in this page
23 var __webpack_exports__ = {};
25 ;// ./src/scripting_api/constants.js
26 const Border = Object.freeze({
33 const Cursor = Object.freeze({
38 const Display = Object.freeze({
44 const Font = Object.freeze({
47 TimesI: "Times-Italic",
48 TimesBI: "Times-BoldItalic",
50 HelvB: "Helvetica-Bold",
51 HelvI: "Helvetica-Oblique",
52 HelvBI: "Helvetica-BoldOblique",
54 CourB: "Courier-Bold",
55 CourI: "Courier-Oblique",
56 CourBI: "Courier-BoldOblique",
58 ZapfD: "ZapfDingbats",
59 KaGo: "HeiseiKakuGo-W5-UniJIS-UCS2-H",
60 KaMi: "HeiseiMin-W3-UniJIS-UCS2-H"
62 const Highlight = Object.freeze({
68 const Position = Object.freeze({
77 const ScaleHow = Object.freeze({
81 const ScaleWhen = Object.freeze({
87 const Style = Object.freeze({
95 const Trans = Object.freeze({
96 blindsH: "BlindsHorizontal",
97 blindsV: "BlindsVertical",
100 dissolve: "Dissolve",
101 glitterD: "GlitterDown",
102 glitterR: "GlitterRight",
103 glitterRD: "GlitterRightDown",
106 splitHI: "SplitHorizontalIn",
107 splitHO: "SplitHorizontalOut",
108 splitVI: "SplitVerticalIn",
109 splitVO: "SplitVerticalOut",
115 const ZoomType = Object.freeze({
120 fitV: "FitVisibleWidth",
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",
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
158 function createActionsMap(actions) {
159 const actionsMap = new Map();
161 for (const [eventType, actionsForEvent] of Object.entries(actions)) {
162 actionsMap.set(eventType, actionsForEvent);
167 function getFieldType(actions) {
168 let format = actions.get("Format");
170 return FieldType.none;
173 format = format.trim();
174 if (format.startsWith("AFNumber_")) {
175 return FieldType.number;
177 if (format.startsWith("AFPercent_")) {
178 return FieldType.percent;
180 if (format.startsWith("AFDate_")) {
181 return FieldType.date;
183 if (format.startsWith("AFTime_")) {
184 return FieldType.time;
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)];
201 return ["CMYK", 0, 0, 0, 1 - g];
204 return ["RGB", g, g, g];
207 g = scaleAndClamp(g);
211 const G = makeColorComp(g);
212 return `#${G}${G}${G}`;
214 static RGB_G([r, g, b]) {
215 return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
217 static RGB_rgb(color) {
218 return color.map(scaleAndClamp);
220 static RGB_HTML(color) {
221 return `#${color.map(makeColorComp).join("")}`;
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)];
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))];
235 static CMYK_HTML(components) {
236 const rgb = this.CMYK_RGB(components).slice(1);
237 return this.RGB_HTML(rgb);
239 static RGB_CMYK([r, g, b]) {
243 const k = Math.min(c, m, y);
244 return ["CMYK", c, m, y, k];
248 ;// ./src/scripting_api/pdf_object.js
251 this._expandos = Object.create(null);
252 this._send = data.send || null;
253 this._id = data.id || null;
257 ;// ./src/scripting_api/color.js
260 class Color extends PDFObject {
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];
276 static _isValidSpace(cColorSpace) {
277 return typeof cColorSpace === "string" && (cColorSpace === "T" || cColorSpace === "G" || cColorSpace === "RGB" || cColorSpace === "CMYK");
279 static _isValidColor(colorArray) {
280 if (!Array.isArray(colorArray) || colorArray.length === 0) {
283 const space = colorArray[0];
284 if (!Color._isValidSpace(space)) {
289 if (colorArray.length !== 1) {
294 if (colorArray.length !== 2) {
299 if (colorArray.length !== 4) {
304 if (colorArray.length !== 5) {
311 return colorArray.slice(1).every(c => typeof c === "number" && c >= 0 && c <= 1);
313 static _getCorrectColor(colorArray) {
314 return Color._isValidColor(colorArray) ? colorArray : ["G", 0];
316 convert(colorArray, cColorSpace) {
317 if (!Color._isValidSpace(cColorSpace)) {
320 if (cColorSpace === "T") {
323 colorArray = Color._getCorrectColor(colorArray);
324 if (colorArray[0] === cColorSpace) {
327 if (colorArray[0] === "T") {
328 return this.convert(this.black, cColorSpace);
330 return ColorConverters[`${colorArray[0]}_${cColorSpace}`](colorArray.slice(1));
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";
338 if (colorArray1[0] !== colorArray2[0]) {
339 colorArray2 = this.convert(colorArray2, colorArray1[0]);
341 return colorArray1.slice(1).every((c, i) => c === colorArray2[i + 1]);
345 ;// ./src/scripting_api/field.js
349 class Field extends PDFObject {
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];
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 || "";
419 get currentValueIndices() {
420 if (!this._isChoice) {
423 return this._currentValueIndices;
425 set currentValueIndices(indices) {
426 if (!this._isChoice) {
429 if (!Array.isArray(indices)) {
432 if (!indices.every(i => typeof i === "number" && Number.isInteger(i) && i >= 0 && i < this.numItems)) {
436 if (this.multipleSelection) {
437 this._currentValueIndices = indices;
439 indices.forEach(i => {
440 this._value.push(this._items[i].displayValue);
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];
453 return this._fillColor;
455 set fillColor(color) {
456 if (Color._isValidColor(color)) {
457 this._fillColor = color;
461 return this.fillColor;
464 this.fillColor = color;
467 return this._charLimit;
469 set charLimit(limit) {
470 if (typeof limit !== "number") {
471 throw new Error("Invalid argument value");
473 this._charLimit = Math.max(0, Math.floor(limit));
476 if (!this._isChoice) {
477 throw new Error("Not a choice widget");
479 return this._items.length;
482 throw new Error("field.numItems is read-only");
485 return this._strokeColor;
487 set strokeColor(color) {
488 if (Color._isValidColor(color)) {
489 this._strokeColor = color;
493 return this.strokeColor;
495 set borderColor(color) {
496 this.strokeColor = color;
502 throw new Error("field.page is read-only");
505 return this._rotation;
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");
516 this._rotation = angle;
519 return this._textColor;
521 set textColor(color) {
522 if (Color._isValidColor(color)) {
523 this._textColor = color;
527 return this.textColor;
530 this.textColor = color;
536 if (this._isChoice) {
537 this._setChoiceValue(value);
540 if (value === "" || typeof value !== "string" || this._fieldType >= FieldType.date) {
541 this._originalValue = undefined;
545 this._originalValue = value;
546 const _value = value.trim().replace(",", ".");
547 this._value = !isNaN(_value) ? parseFloat(_value) : value;
550 return this._originalValue ?? this.value;
552 _setChoiceValue(value) {
553 if (this.multipleSelection) {
554 if (!Array.isArray(value)) {
557 const values = new Set(value);
558 if (Array.isArray(this._currentValueIndices)) {
559 this._currentValueIndices.length = 0;
560 this._value.length = 0;
562 this._currentValueIndices = [];
565 this._items.forEach((item, i) => {
566 if (values.has(item.exportValue)) {
567 this._currentValueIndices.push(i);
568 this._value.push(item.exportValue);
572 if (Array.isArray(value)) {
575 const index = this._items.findIndex(({
577 }) => value === exportValue);
579 this._currentValueIndices = index;
580 this._value = this._items[index].exportValue;
584 get valueAsString() {
585 return (this._value ?? "").toString();
587 set valueAsString(_) {}
588 browseForFileToSubmit() {
589 if (this._browseForFileToSubmit) {
590 this._browseForFileToSubmit();
593 buttonGetCaption(nFace = 0) {
594 if (this._buttonCaption) {
595 return this._buttonCaption[nFace];
599 buttonGetIcon(nFace = 0) {
600 if (this._buttonIcon) {
601 return this._buttonIcon[nFace];
605 buttonImportIcon(cPath = null, nPave = 0) {}
606 buttonSetCaption(cCaption, nFace = 0) {
607 if (!this._buttonCaption) {
608 this._buttonCaption = ["", "", ""];
610 this._buttonCaption[nFace] = cCaption;
612 buttonSetIcon(oIcon, nFace = 0) {
613 if (!this._buttonIcon) {
614 this._buttonIcon = [null, null, null];
616 this._buttonIcon[nFace] = oIcon;
618 checkThisBox(nWidget, bCheckIt = true) {}
620 if (!this._isChoice) {
621 throw new Error("Not a choice widget");
629 deleteItemAt(nIdx = null) {
630 if (!this._isChoice) {
631 throw new Error("Not a choice widget");
633 if (!this.numItems) {
637 nIdx = Array.isArray(this._currentValueIndices) ? this._currentValueIndices[0] : this._currentValueIndices;
640 if (nIdx < 0 || nIdx >= this.numItems) {
641 nIdx = this.numItems - 1;
643 this._items.splice(nIdx, 1);
644 if (Array.isArray(this._currentValueIndices)) {
645 let index = this._currentValueIndices.findIndex(i => i >= nIdx);
647 if (this._currentValueIndices[index] === nIdx) {
648 this._currentValueIndices.splice(index, 1);
650 for (const ii = this._currentValueIndices.length; index < ii; index++) {
651 --this._currentValueIndices[index];
654 } else if (this._currentValueIndices === nIdx) {
655 this._currentValueIndices = this.numItems > 0 ? 0 : -1;
656 } else if (this._currentValueIndices > nIdx) {
657 --this._currentValueIndices;
664 getItemAt(nIdx = -1, bExportValue = false) {
665 if (!this._isChoice) {
666 throw new Error("Not a choice widget");
668 if (nIdx < 0 || nIdx >= this.numItems) {
669 nIdx = this.numItems - 1;
671 const item = this._items[nIdx];
672 return bExportValue ? item.exportValue : item.displayValue;
677 const fillArrayWithKids = kidIds => {
678 for (const id of kidIds) {
679 const obj = this._appObjects[id];
683 if (obj.obj._hasValue) {
684 array.push(obj.wrapped);
686 if (obj.obj._kidIds) {
687 fillArrayWithKids(obj.obj._kidIds);
691 fillArrayWithKids(this._kidIds);
694 if (this._children === null) {
695 this._children = this._document.obj._getTerminalChildren(this._fieldPath);
697 return this._children;
702 isBoxChecked(nWidget) {
705 isDefaultChecked(nWidget) {
708 insertItemAt(cName, cExport = undefined, nIdx = 0) {
709 if (!this._isChoice) {
710 throw new Error("Not a choice widget");
715 if (nIdx < 0 || nIdx > this.numItems) {
716 nIdx = this.numItems;
718 if (this._items.some(({
720 }) => displayValue === cName)) {
723 if (cExport === undefined) {
730 this._items.splice(nIdx, 0, data);
731 if (Array.isArray(this._currentValueIndices)) {
732 let index = this._currentValueIndices.findIndex(i => i >= nIdx);
734 for (const ii = this._currentValueIndices.length; index < ii; index++) {
735 ++this._currentValueIndices[index];
738 } else if (this._currentValueIndices >= nIdx) {
739 ++this._currentValueIndices;
749 setAction(cTrigger, cScript) {
750 if (typeof cTrigger !== "string" || typeof cScript !== "string") {
753 if (!(cTrigger in this._actions)) {
754 this._actions[cTrigger] = [];
756 this._actions[cTrigger].push(cScript);
765 if (!this._isChoice) {
766 throw new Error("Not a choice widget");
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() || "";
775 displayValue = exportValue = element?.toString() || "";
782 this._currentValueIndices = 0;
789 signatureGetModifications() {}
790 signatureGetSeedValue() {}
792 signatureSetSeedValue() {}
794 signatureValidate() {}
799 this.value = this.defaultValue;
802 const eventName = event.name;
803 if (!this._actions.has(eventName)) {
806 const actions = this._actions.get(eventName);
808 for (const action of actions) {
809 this._globalEval(action);
818 class RadioButtonField extends Field {
819 constructor(otherButtons, 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;
832 this._hasBeenInitialized = true;
833 this._value = data.value || "";
836 return this._radioIds.filter(id => id !== this._id);
843 if (!this._hasBeenInitialized) {
846 if (value === null || value === undefined) {
849 const i = this.exportValues.indexOf(value);
850 if (0 <= i && i < this._radioIds.length) {
851 this._id = this._radioIds[i];
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];
859 checkThisBox(nWidget, bCheckIt = true) {
860 if (nWidget < 0 || nWidget >= this._radioIds.length || !bCheckIt) {
863 this._id = this._radioIds[nWidget];
864 this._value = this.exportValues[nWidget];
870 isBoxChecked(nWidget) {
871 return nWidget >= 0 && nWidget < this._radioIds.length && this._id === this._radioIds[nWidget];
873 isDefaultChecked(nWidget) {
874 return nWidget >= 0 && nWidget < this.exportValues.length && this.defaultValue === this.exportValues[nWidget];
876 _getExportValue(state) {
877 const i = this._radioIds.indexOf(this._id);
878 return this.exportValues[i];
881 const i = this._radioIds.indexOf(this._id);
882 this._actions = this._radioActions[i];
883 return super._runActions(event);
889 class CheckboxField extends RadioButtonField {
894 if (!value || value === "Off") {
900 _getExportValue(state) {
901 return state ? super._getExportValue(state) : "Off";
903 isBoxChecked(nWidget) {
904 if (this._value === "Off") {
907 return super.isBoxChecked(nWidget);
909 isDefaultChecked(nWidget) {
910 if (this.defaultValue === "Off") {
911 return this._value === "Off";
913 return super.isDefaultChecked(nWidget);
915 checkThisBox(nWidget, bCheckIt = true) {
916 if (nWidget < 0 || nWidget >= this._radioIds.length) {
919 this._id = this._radioIds[nWidget];
920 this._value = bCheckIt ? this.exportValues[nWidget] : "Off";
928 ;// ./src/scripting_api/aform.js
931 constructor(document, app, util, color) {
932 this._document = document;
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])?)*$");
940 _mkTargetName(event) {
941 return event.target ? `[ ${event.target.name} ]` : "";
943 _parseDate(cFormat, cDate, strict = false) {
946 date = this._util._scand(cFormat, cDate, strict);
954 date = Date.parse(cDate);
955 return isNaN(date) ? null : new Date(date);
957 AFMergeChange(event = globalThis.event) {
958 if (event.willCommit) {
959 return event.value.toString();
961 return this._app._eventDispatcher.mergeChange(event);
963 AFParseDateEx(cString, cOrder) {
964 return this._parseDate(cOrder, cString);
967 if (typeof str === "number") {
970 if (!str || typeof str !== "string") {
973 const first = str.charAt(0);
974 if (first === "." || first === ",") {
977 const numbers = str.match(/(\d+)/g);
978 if (numbers.length === 0) {
984 if (typeof str === "number") {
987 if (typeof str !== "string") {
990 str = str.trim().replace(",", ".");
991 const number = parseFloat(str);
992 if (isNaN(number) || !isFinite(number)) {
997 AFMakeArrayFromList(string) {
998 if (typeof string === "string") {
999 return string.split(/, ?/g);
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) {
1010 const sign = Math.sign(value);
1012 let hasParen = false;
1013 if (sign === -1 && bCurrencyPrepend && negStyle === 0) {
1016 if ((negStyle === 2 || negStyle === 3) && sign === -1) {
1020 if (bCurrencyPrepend) {
1021 buf.push(strCurrency);
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);
1031 if (negStyle === 1 || negStyle === 3) {
1032 event.target.textColor = sign === 1 ? this._color.black : this._color.red;
1034 if ((negStyle !== 0 || bCurrencyPrepend) && sign === -1) {
1037 const formatStr = buf.join("");
1038 event.value = this._util.printf(formatStr, value);
1040 AFNumber_Keystroke(nDec, sepStyle, negStyle, currStyle, strCurrency, bCurrencyPrepend) {
1041 const event = globalThis.event;
1042 let value = this.AFMergeChange(event);
1046 value = value.trim();
1049 pattern = event.willCommit ? /^[+-]?(\d+(,\d*)?|,\d+)$/ : /^[+-]?\d*,?\d*$/;
1051 pattern = event.willCommit ? /^[+-]?(\d+(\.\d*)?|\.\d+)$/ : /^[+-]?\d*\.?\d*$/;
1053 if (!pattern.test(value)) {
1054 if (event.willCommit) {
1055 const err = `${GlobalConstants.IDS_INVALID_VALUE} ${this._mkTargetName(event)}`;
1056 this._app.alert(err);
1060 if (event.willCommit && sepStyle > 1) {
1061 event.value = parseFloat(value.replace(",", "."));
1064 AFPercent_Format(nDec, sepStyle, percentPrepend = false) {
1065 if (typeof nDec !== "number") {
1068 if (typeof sepStyle !== "number") {
1072 throw new Error("Invalid nDec value in AFPercent_Format");
1074 const event = globalThis.event;
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) {
1086 const formatStr = `%,${sepStyle}.${nDec}f`;
1087 value = this._util.printf(formatStr, value * 100);
1088 event.value = percentPrepend ? `%${value}` : `${value}%`;
1090 AFPercent_Keystroke(nDec, sepStyle) {
1091 this.AFNumber_Keystroke(nDec, sepStyle, 0, 0, "", true);
1093 AFDate_FormatEx(cFormat) {
1094 const event = globalThis.event;
1095 const value = event.value;
1099 const date = this._parseDate(cFormat, value);
1100 if (date !== null) {
1101 event.value = this._util.printd(cFormat, date);
1104 AFDate_Format(pdf) {
1105 if (pdf >= 0 && pdf < this._dateFormats.length) {
1106 this.AFDate_FormatEx(this._dateFormats[pdf]);
1109 AFDate_KeystrokeEx(cFormat) {
1110 const event = globalThis.event;
1111 if (!event.willCommit) {
1114 const value = this.AFMergeChange(event);
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);
1126 AFDate_Keystroke(pdf) {
1127 if (pdf >= 0 && pdf < this._dateFormats.length) {
1128 this.AFDate_KeystrokeEx(this._dateFormats[pdf]);
1131 AFRange_Validate(bGreaterThan, nGreaterThan, bLessThan, nLessThan) {
1132 const event = globalThis.event;
1136 const value = this.AFMakeNumber(event.value);
1137 if (value === null) {
1140 bGreaterThan = !!bGreaterThan;
1141 bLessThan = !!bLessThan;
1143 nGreaterThan = this.AFMakeNumber(nGreaterThan);
1144 if (nGreaterThan === null) {
1149 nLessThan = this.AFMakeNumber(nLessThan);
1150 if (nLessThan === null) {
1155 if (bGreaterThan && bLessThan) {
1156 if (value < nGreaterThan || value > nLessThan) {
1157 err = this._util.printf(GlobalConstants.IDS_GT_AND_LT, nGreaterThan, nLessThan);
1159 } else if (bGreaterThan) {
1160 if (value < nGreaterThan) {
1161 err = this._util.printf(GlobalConstants.IDS_GREATER_THAN, nGreaterThan);
1163 } else if (value > nLessThan) {
1164 err = this._util.printf(GlobalConstants.IDS_LESS_THAN, nLessThan);
1167 this._app.alert(err);
1171 AFSimple(cFunction, nValue1, nValue2) {
1172 const value1 = this.AFMakeNumber(nValue1);
1173 if (value1 === null) {
1174 throw new Error("Invalid nValue1 in AFSimple");
1176 const value2 = this.AFMakeNumber(nValue2);
1177 if (value2 === null) {
1178 throw new Error("Invalid nValue2 in AFSimple");
1180 switch (cFunction) {
1182 return (value1 + value2) / 2;
1184 return value1 + value2;
1186 return value1 * value2;
1188 return Math.min(value1, value2);
1190 return Math.max(value1, value2);
1192 throw new Error("Invalid cFunction in AFSimple");
1194 AFSimple_Calculate(cFunction, cFields) {
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)
1202 if (!(cFunction in actions)) {
1203 throw new TypeError("Invalid function in AFSimple_Calculate");
1205 const event = globalThis.event;
1207 cFields = this.AFMakeArrayFromList(cFields);
1208 for (const cField of cFields) {
1209 const field = this._document.getField(cField);
1213 for (const child of field.getArray()) {
1214 const number = this.AFMakeNumber(child.value);
1215 values.push(number ?? 0);
1218 if (values.length === 0) {
1222 const res = actions[cFunction](values);
1223 event.value = Math.round(1e6 * res) / 1e6;
1225 AFSpecial_Format(psf) {
1226 const event = globalThis.event;
1230 psf = this.AFMakeNumber(psf);
1234 formatStr = "99999";
1237 formatStr = "99999-9999";
1240 formatStr = this._util.printx("9999999999", event.value).length >= 10 ? "(999) 999-9999" : "999-9999";
1243 formatStr = "999-99-9999";
1246 throw new Error("Invalid psf in AFSpecial_Format");
1248 event.value = this._util.printx(formatStr, event.value);
1250 AFSpecial_KeystrokeEx(cMask) {
1251 const event = globalThis.event;
1252 const simplifiedFormatStr = cMask.replaceAll(/[^9AOX]/g, "");
1253 this.#AFSpecial_KeystrokeEx_helper(simplifiedFormatStr, null, false);
1258 this.#AFSpecial_KeystrokeEx_helper(cMask, null, true);
1260 #AFSpecial_KeystrokeEx_helper(cMask, value, warn) {
1264 const event = globalThis.event;
1265 value ||= this.AFMergeChange(event);
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);
1276 if (!checker(char)) {
1279 } else if (mask !== char) {
1285 const err = `${GlobalConstants.IDS_INVALID_VALUE} = "${cMask}"`;
1286 if (value.length > cMask.length) {
1288 this._app.alert(err);
1293 if (event.willCommit) {
1294 if (value.length < cMask.length) {
1296 this._app.alert(err);
1301 if (!_checkValidity(value, cMask)) {
1303 this._app.alert(err);
1308 event.value += cMask.substring(value.length);
1311 if (value.length < cMask.length) {
1312 cMask = cMask.substring(0, value.length);
1314 if (!_checkValidity(value, cMask)) {
1316 this._app.alert(err);
1321 AFSpecial_Keystroke(psf) {
1322 const event = globalThis.event;
1323 psf = this.AFMakeNumber(psf);
1324 let value = this.AFMergeChange(event);
1325 let formatStr, secondFormatStr;
1328 formatStr = "99999";
1331 formatStr = "99999-9999";
1334 formatStr = "999-9999";
1335 secondFormatStr = "(999) 999-9999";
1338 formatStr = "999-99-9999";
1341 throw new Error("Invalid psf in AFSpecial_Keystroke");
1343 const formats = secondFormatStr ? [formatStr, secondFormatStr] : [formatStr];
1344 for (const format of formats) {
1345 this.#AFSpecial_KeystrokeEx_helper(format, value, false);
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);
1360 this.AFSpecial_KeystrokeEx((secondFormatStr && value.match(/\d/g) || []).length > 7 ? secondFormatStr : formatStr);
1362 AFTime_FormatEx(cFormat) {
1363 this.AFDate_FormatEx(cFormat);
1365 AFTime_Format(pdf) {
1366 if (pdf >= 0 && pdf < this._timeFormats.length) {
1367 this.AFDate_FormatEx(this._timeFormats[pdf]);
1370 AFTime_KeystrokeEx(cFormat) {
1371 this.AFDate_KeystrokeEx(cFormat);
1373 AFTime_Keystroke(pdf) {
1374 if (pdf >= 0 && pdf < this._timeFormats.length) {
1375 this.AFDate_KeystrokeEx(this._timeFormats[pdf]);
1378 eMailValidate(str) {
1379 return this._emailRegex.test(str);
1381 AFExactMatch(rePatterns, str) {
1382 if (rePatterns instanceof RegExp) {
1383 return str.match(rePatterns)?.[0] === str || 0;
1385 return rePatterns.findIndex(re => str.match(re)?.[0] === str) + 1;
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}`;
1404 ;// ./src/scripting_api/event.js
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;
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;
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;
1439 mergeChange(event) {
1440 let value = event.value;
1441 if (Array.isArray(value)) {
1444 if (typeof value !== "string") {
1445 value = value.toString();
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}`;
1452 this._document.obj._userActivation = true;
1453 this._externalCall("setTimeout", [USERACTIVATION_CALLBACKID, USERACTIVATION_MAXTIME_VALIDITY]);
1455 dispatch(baseEvent) {
1456 const id = baseEvent.id;
1457 if (!(id in this._objects)) {
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;
1465 const eventName = event.name;
1466 if (eventName === "Open") {
1467 this.userActivation();
1468 this._document.obj._initActions();
1471 if (!["DidPrint", "DidSave", "WillPrint", "WillSave"].includes(eventName)) {
1472 this.userActivation();
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];
1487 const name = baseEvent.name;
1488 const source = this._objects[id];
1489 const event = globalThis.event = new Event(baseEvent);
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;
1503 changeEx: event.changeEx,
1504 change: event.change,
1505 selStart: event.selStart,
1506 selEnd: event.selEnd
1511 Object.defineProperty(event, "value", {
1512 configurable: false,
1519 this.runValidation(source, event);
1522 this.runActions(source, source, event, name);
1523 this.runCalculate(source, event);
1526 this.runActions(source, source, event, name);
1527 if (name !== "Keystroke") {
1531 if (event.willCommit) {
1532 this.runValidation(source, event);
1534 if (source.obj._isChoice) {
1535 source.obj.value = savedChange.changeEx;
1538 siblings: source.obj._siblings,
1539 value: source.obj.value
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;
1549 selEnd = selStart = savedChange.selStart + event.change.length;
1553 siblings: source.obj._siblings,
1555 selRange: [selStart, selEnd]
1558 } else if (!event.willCommit) {
1561 siblings: source.obj._siblings,
1562 value: savedChange.value,
1563 selRange: [savedChange.selStart, savedChange.selEnd]
1568 siblings: source.obj._siblings,
1570 formattedValue: null,
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");
1582 runValidation(source, event) {
1583 const didValidateRun = this.runActions(source, source, event, "Validate");
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?.();
1594 siblings: source.obj._siblings,
1598 event.value = savedValue;
1599 } else if (didValidateRun) {
1602 siblings: source.obj._siblings,
1604 formattedValue: null,
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;
1616 return target.obj._runActions(event);
1619 if (!this._calculationOrder || this._isCalculating || !this._document.obj.calculate) {
1622 this._isCalculating = true;
1623 const first = this._calculationOrder[0];
1624 const source = this._objects[first];
1625 globalThis.event = new Event({});
1627 this.runCalculate(source, globalThis.event);
1629 this._isCalculating = false;
1632 this._isCalculating = false;
1634 runCalculate(source, event) {
1635 if (!this._calculationOrder || !this._document.obj.calculate) {
1638 for (const targetId of this._calculationOrder) {
1639 if (!(targetId in this._objects)) {
1642 if (!this._document.obj.calculate) {
1646 const target = this._objects[targetId];
1647 let savedValue = target.obj._getValue();
1649 this.runActions(source, target, event, "Calculate");
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]);
1660 if (event.value !== null) {
1661 target.obj.value = event.value;
1663 event.value = target.obj._getValue();
1665 this.runActions(target, target, event, "Validate");
1667 if (target.obj._getValue() !== savedValue) {
1668 target.wrapped.value = savedValue;
1672 if (event.value === null) {
1673 event.value = target.obj._getValue();
1675 savedValue = target.obj._getValue();
1676 let formattedValue = null;
1677 if (this.runActions(target, target, event, "Format")) {
1678 formattedValue = event.value?.toString?.();
1682 siblings: target.obj._siblings,
1690 ;// ./src/scripting_api/fullscreen.js
1693 class FullScreen extends PDFObject {
1696 this._backgroundColor = [];
1697 this._clickAdvances = true;
1698 this._cursor = Cursor.hidden;
1699 this._defaultTransition = "";
1700 this._escapeExits = true;
1701 this._isFullScreen = true;
1703 this._timeDelay = 3600;
1704 this._usePageTiming = false;
1705 this._useTimer = false;
1707 get backgroundColor() {
1708 return this._backgroundColor;
1710 set backgroundColor(_) {}
1711 get clickAdvances() {
1712 return this._clickAdvances;
1714 set clickAdvances(_) {}
1716 return this._cursor;
1719 get defaultTransition() {
1720 return this._defaultTransition;
1722 set defaultTransition(_) {}
1724 return this._escapeExits;
1726 set escapeExits(_) {}
1727 get isFullScreen() {
1728 return this._isFullScreen;
1730 set isFullScreen(_) {}
1736 return this._timeDelay;
1740 return ["Replace", "WipeRight", "WipeLeft", "WipeDown", "WipeUp", "SplitHorizontalIn", "SplitHorizontalOut", "SplitVerticalIn", "SplitVerticalOut", "BlindsHorizontal", "BlindsVertical", "BoxIn", "BoxOut", "GlitterRight", "GlitterDown", "GlitterRightDown", "Dissolve", "Random"];
1742 set transitions(_) {
1743 throw new Error("fullscreen.transitions is read-only");
1745 get usePageTiming() {
1746 return this._usePageTiming;
1748 set usePageTiming(_) {}
1750 return this._useTimer;
1755 ;// ./src/scripting_api/thermometer.js
1757 class Thermometer extends PDFObject {
1760 this._cancelled = false;
1761 this._duration = 100;
1766 return this._cancelled;
1769 throw new Error("thermometer.cancelled is read-only");
1772 return this._duration;
1775 this._duration = val;
1793 ;// ./src/scripting_api/app.js
1800 class App extends PDFObject {
1803 this._constants = null;
1804 this._focusRect = true;
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));
1821 this._timeoutIdsRegistry = null;
1823 this._timeoutCallbackIds = new Map();
1824 this._timeoutCallbackId = USERACTIVATION_CALLBACKID + 1;
1825 this._globalEval = data.globalEval;
1826 this._externalCall = data.externalCall;
1828 _dispatchEvent(pdfEvent) {
1829 this._eventDispatcher.dispatch(pdfEvent);
1831 _registerTimeoutCallback(cExpr) {
1832 const id = this._timeoutCallbackId++;
1833 this._timeoutCallbackIds.set(id, cExpr);
1836 _unregisterTimeoutCallback(id) {
1837 this._timeoutCallbackIds.delete(id);
1843 if (callbackId === USERACTIVATION_CALLBACKID) {
1844 this._document.obj._userActivation = false;
1847 const expr = this._timeoutCallbackIds.get(callbackId);
1849 this._unregisterTimeoutCallback(callbackId);
1852 this._globalEval(expr);
1855 _registerTimeout(callbackId, interval) {
1856 const timeout = Object.create(null);
1861 this._timeoutIds.set(timeout, id);
1862 this._timeoutIdsRegistry?.register(timeout, id);
1865 _unregisterTimeout(timeout) {
1866 this._timeoutIdsRegistry?.unregister(timeout);
1867 const data = this._timeoutIds.get(timeout);
1871 this._timeoutIds.delete(timeout);
1872 this._cleanTimeout(data);
1878 this._unregisterTimeoutCallback(callbackId);
1880 this._externalCall("clearInterval", [callbackId]);
1882 this._externalCall("clearTimeout", [callbackId]);
1885 static _getPlatform(platform) {
1886 if (typeof platform === "string") {
1887 platform = platform.toLowerCase();
1888 if (platform.includes("win")) {
1890 } else if (platform.includes("mac")) {
1896 static _getLanguage(language) {
1897 const [main, sub] = language.toLowerCase().split(/[-_]/);
1900 if (sub === "cn" || sub === "sg") {
1936 return [this._document.wrapped];
1939 throw new Error("app.activeDocs is read-only");
1942 return this._document.obj.calculate;
1944 set calculate(calculate) {
1945 this._document.obj.calculate = calculate;
1948 if (!this._constants) {
1949 this._constants = Object.freeze({
1950 align: Object.freeze({
1959 return this._constants;
1962 throw new Error("app.constants is read-only");
1965 return this._focusRect;
1967 set focusRect(val) {
1968 this._focusRect = val;
1970 get formsVersion() {
1971 return FORMS_VERSION;
1973 set formsVersion(_) {
1974 throw new Error("app.formsVersion is read-only");
1976 get fromPDFConverters() {
1979 set fromPDFConverters(_) {
1980 throw new Error("app.fromPDFConverters is read-only");
1983 if (this._fs === null) {
1984 this._fs = new Proxy(new FullScreen({
1986 }), this._proxyHandler);
1991 throw new Error("app.fs is read-only");
1994 return this._language;
1997 throw new Error("app.language is read-only");
2003 throw new Error("app.media is read-only");
2009 throw new Error("app.monitors is read-only");
2015 throw new Error("app.numPlugins is read-only");
2018 return this._openInPlace;
2020 set openInPlace(val) {
2021 this._openInPlace = val;
2024 return this._platform;
2027 throw new Error("app.platform is read-only");
2033 throw new Error("app.plugins is read-only");
2035 get printColorProfiles() {
2038 set printColorProfiles(_) {
2039 throw new Error("app.printColorProfiles is read-only");
2041 get printerNames() {
2044 set printerNames(_) {
2045 throw new Error("app.printerNames is read-only");
2047 get runtimeHighlight() {
2048 return this._runtimeHighlight;
2050 set runtimeHighlight(val) {
2051 this._runtimeHighlight = val;
2053 get runtimeHighlightColor() {
2054 return this._runtimeHighlightColor;
2056 set runtimeHighlightColor(val) {
2057 if (Color._isValidColor(val)) {
2058 this._runtimeHighlightColor = val;
2062 if (this._thermometer === null) {
2063 this._thermometer = new Proxy(new Thermometer({
2065 }), this._proxyHandler);
2067 return this._thermometer;
2069 set thermometer(_) {
2070 throw new Error("app.thermometer is read-only");
2073 return this._toolbar;
2076 this._toolbar = val;
2078 get toolbarHorizontal() {
2079 return this.toolbar;
2081 set toolbarHorizontal(value) {
2082 this.toolbar = value;
2084 get toolbarVertical() {
2085 return this.toolbar;
2087 set toolbarVertical(value) {
2088 this.toolbar = value;
2094 throw new Error("app.viewerType is read-only");
2096 get viewerVariation() {
2097 return VIEWER_VARIATION;
2099 set viewerVariation(_) {
2100 throw new Error("app.viewerVariation is read-only");
2102 get viewerVersion() {
2103 return VIEWER_VERSION;
2105 set viewerVersion(_) {
2106 throw new Error("app.viewerVersion is read-only");
2111 alert(cMsg, nIcon = 0, nType = 0, cTitle = "PDF.js", oDoc = null, oCheckbox = null) {
2112 if (!this._document.obj._userActivation) {
2115 this._document.obj._userActivation = false;
2116 if (cMsg && typeof cMsg === "object") {
2120 cMsg = (cMsg || "").toString();
2124 nType = typeof nType !== "number" || isNaN(nType) || nType < 0 || nType > 3 ? 0 : nType;
2126 return this._externalCall("confirm", [cMsg]) ? 4 : 3;
2128 this._externalCall("alert", [cMsg]);
2134 clearInterval(oInterval) {
2135 this._unregisterTimeout(oInterval);
2137 clearTimeOut(oTime) {
2138 this._unregisterTimeout(oTime);
2142 execMenuItem(item) {
2143 if (!this._document.obj._userActivation) {
2146 this._document.obj._userActivation = false;
2149 if (this._document.obj._disableSaving) {
2173 if (this._document.obj._disablePrinting) {
2182 getNthPlugInName() {}
2187 hideToolbarButton() {}
2190 listToolbarButtons() {}
2201 removeToolButton() {}
2202 response(cQuestion, cTitle = "", cDefault = "", bPassword = "", cLabel = "") {
2203 if (cQuestion && typeof cQuestion === "object") {
2204 cDefault = cQuestion.cDefault;
2205 cQuestion = cQuestion.cQuestion;
2207 cQuestion = (cQuestion || "").toString();
2208 cDefault = (cDefault || "").toString();
2209 return this._externalCall("prompt", [cQuestion, cDefault || ""]);
2211 setInterval(cExpr, nMilliseconds = 0) {
2212 if (cExpr && typeof cExpr === "object") {
2213 nMilliseconds = cExpr.nMilliseconds || 0;
2214 cExpr = cExpr.cExpr;
2216 if (typeof cExpr !== "string") {
2217 throw new TypeError("First argument of app.setInterval must be a string");
2219 if (typeof nMilliseconds !== "number") {
2220 throw new TypeError("Second argument of app.setInterval must be a number");
2222 const callbackId = this._registerTimeoutCallback(cExpr);
2223 this._externalCall("setInterval", [callbackId, nMilliseconds]);
2224 return this._registerTimeout(callbackId, true);
2226 setTimeOut(cExpr, nMilliseconds = 0) {
2227 if (cExpr && typeof cExpr === "object") {
2228 nMilliseconds = cExpr.nMilliseconds || 0;
2229 cExpr = cExpr.cExpr;
2231 if (typeof cExpr !== "string") {
2232 throw new TypeError("First argument of app.setTimeOut must be a string");
2234 if (typeof nMilliseconds !== "number") {
2235 throw new TypeError("Second argument of app.setTimeOut must be a number");
2237 const callbackId = this._registerTimeoutCallback(cExpr);
2238 this._externalCall("setTimeout", [callbackId, nMilliseconds]);
2239 return this._registerTimeout(callbackId, false);
2241 trustedFunction() {}
2242 trustPropagatorFunction() {}
2245 ;// ./src/scripting_api/console.js
2247 class Console extends PDFObject {
2255 if (typeof msg === "string") {
2258 value: "PDF.js Console:: " + msg
2265 ;// ./src/scripting_api/print_params.js
2268 this.binaryOk = true;
2269 this.bitmapDPI = 150;
2276 this.colorOverride = 0;
2277 this.colorProfile = "";
2278 this.constants = Object.freeze({
2279 bookletBindings: Object.freeze({
2285 bookletDuplexMode: Object.freeze({
2290 colorOverrides: Object.freeze({
2295 fontPolicies: Object.freeze({
2300 handling: Object.freeze({
2309 interactionLevel: Object.freeze({
2314 nUpPageOrders: Object.freeze({
2316 HorizontalReversed: 1,
2319 printContents: Object.freeze({
2324 flagValues: Object.freeze({
2326 applySoftProofSettings: 1 << 1,
2327 applyWorkingColorSpaces: 1 << 2,
2328 emitHalftones: 1 << 3,
2329 emitPostScriptXObjects: 1 << 4,
2330 emitFormsAsPSForms: 1 << 5,
2332 setPageSize: 1 << 7,
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
2343 rasterFlagValues: Object.freeze({
2345 strokesToOutline: 1 << 1,
2346 allowComplexClip: 1 << 2,
2347 preserveOverprint: 1 << 3
2349 subsets: Object.freeze({
2354 tileMarks: Object.freeze({
2359 usages: Object.freeze({
2365 this.downloadFarEastFonts = false;
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 = "";
2384 this.rasterFlags = 0;
2385 this.reversePages = false;
2386 this.tileLabel = false;
2388 this.tileOverlap = 0;
2389 this.tileScale = 1.0;
2390 this.transparencyLevel = 75;
2391 this.usePrinterCRD = 0;
2392 this.useT1Conversion = 0;
2396 ;// ./src/scripting_api/doc.js
2402 const DOC_EXTERNAL = false;
2403 class InfoProxyHandler {
2404 static get(obj, prop) {
2405 return obj[prop.toLowerCase()];
2407 static set(obj, prop, value) {
2408 throw new Error(`doc.info.${prop} is read-only`);
2411 class Doc extends PDFObject {
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 = [];
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({
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;
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);
2477 this._runActions("OpenAction");
2478 this._disableSaving = false;
2480 _dispatchDocEvent(name) {
2483 this._disableSaving = true;
2484 this._runActions("OpenAction");
2485 this._disableSaving = false;
2488 this._disablePrinting = true;
2490 this._runActions(name);
2492 this._send(serializeError(error));
2495 command: "WillPrintFinished"
2497 this._disablePrinting = false;
2500 this._disableSaving = true;
2501 this._runActions(name);
2502 this._disableSaving = false;
2505 this._runActions(name);
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));
2514 this._pageNum = pageNumber - 1;
2516 for (const acts of [this._pageActions, this._otherPageActions]) {
2517 actions = acts?.get(pageNumber)?.get(name);
2519 for (const action of actions) {
2520 this._globalEval(action);
2526 const actions = this._actions.get(name);
2528 for (const action of actions) {
2529 this._globalEval(action);
2533 _addField(name, field) {
2534 this._fields.set(name, field);
2535 this._fieldNames.push(name);
2537 const po = field.obj._actions.get("PageOpen");
2538 const pc = field.obj._actions.get("PageClose");
2540 this._otherPageActions ||= new Map();
2541 let actions = this._otherPageActions.get(field.obj._page + 1);
2543 actions = new Map();
2544 this._otherPageActions.set(field.obj._page + 1, actions);
2547 let poActions = actions.get("PageOpen");
2550 actions.set("PageOpen", poActions);
2552 poActions.push(...po);
2555 let pcActions = actions.get("PageClose");
2558 actions.set("PageClose", pcActions);
2560 pcActions.push(...pc);
2565 if (!date || date.length < 15 || !date.startsWith("D:")) {
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 === "-") {
2580 second = date.substring(12, 14);
2583 const offset = date.substring(offsetPos).replaceAll("'", "");
2584 return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}${offset}`);
2587 return this._author;
2590 throw new Error("doc.author is read-only");
2593 return this._baseURL;
2595 set baseURL(baseURL) {
2596 this._baseURL = baseURL;
2598 get bookmarkRoot() {
2601 set bookmarkRoot(_) {
2602 throw new Error("doc.bookmarkRoot is read-only");
2605 return this._calculate;
2607 set calculate(calculate) {
2608 this._calculate = calculate;
2611 return this._creator;
2614 throw new Error("doc.creator is read-only");
2619 set dataObjects(_) {
2620 throw new Error("doc.dataObjects is read-only");
2626 this._delay = delay;
2632 this._dirty = dirty;
2635 return this._disclosed;
2637 set disclosed(disclosed) {
2638 this._disclosed = disclosed;
2644 throw new Error("doc.docID is read-only");
2646 get documentFileName() {
2647 return this._documentFileName;
2649 set documentFileName(_) {
2650 throw new Error("doc.documentFileName is read-only");
2652 get dynamicXFAForm() {
2655 set dynamicXFAForm(_) {
2656 throw new Error("doc.dynamicXFAForm is read-only");
2659 return DOC_EXTERNAL;
2662 throw new Error("doc.external is read-only");
2665 return this._filesize;
2668 throw new Error("doc.filesize is read-only");
2674 throw new Error("doc.hidden is read-only");
2676 get hostContainer() {
2679 set hostContainer(_) {
2680 throw new Error("doc.hostContainer is read-only");
2686 throw new Error("doc.icons is read-only");
2692 throw new Error("doc.info is read-only");
2694 get innerAppWindowRect() {
2695 return [0, 0, 0, 0];
2697 set innerAppWindowRect(_) {
2698 throw new Error("doc.innerAppWindowRect is read-only");
2700 get innerDocWindowRect() {
2701 return [0, 0, 0, 0];
2703 set innerDocWindowRect(_) {
2704 throw new Error("doc.innerDocWindowRect is read-only");
2710 throw new Error("doc.isModal is read-only");
2713 return this._keywords;
2716 throw new Error("doc.keywords is read-only");
2719 return this._layout;
2722 if (!this._userActivation) {
2725 this._userActivation = false;
2726 if (typeof value !== "string") {
2729 if (value !== "SinglePage" && value !== "OneColumn" && value !== "TwoColumnLeft" && value !== "TwoPageLeft" && value !== "TwoColumnRight" && value !== "TwoPageRight") {
2730 value = "SinglePage";
2736 this._layout = value;
2742 this._media = media;
2745 return this._metadata;
2747 set metadata(metadata) {
2748 this._metadata = metadata;
2751 return this._modDate;
2754 throw new Error("doc.modDate is read-only");
2760 throw new Error("doc.mouseX is read-only");
2766 throw new Error("doc.mouseY is read-only");
2768 get noautocomplete() {
2769 return this._noautocomplete;
2771 set noautocomplete(noautocomplete) {
2772 this._noautocomplete = noautocomplete;
2775 return this._nocache;
2777 set nocache(nocache) {
2778 this._nocache = nocache;
2781 return this._numFields;
2784 throw new Error("doc.numFields is read-only");
2787 return this._numPages;
2790 throw new Error("doc.numPages is read-only");
2792 get numTemplates() {
2795 set numTemplates(_) {
2796 throw new Error("doc.numTemplates is read-only");
2798 get outerAppWindowRect() {
2799 return [0, 0, 0, 0];
2801 set outerAppWindowRect(_) {
2802 throw new Error("doc.outerAppWindowRect is read-only");
2804 get outerDocWindowRect() {
2805 return [0, 0, 0, 0];
2807 set outerDocWindowRect(_) {
2808 throw new Error("doc.outerDocWindowRect is read-only");
2811 return this._pageNum;
2813 set pageNum(value) {
2814 if (!this._userActivation) {
2817 this._userActivation = false;
2818 if (typeof value !== "number" || value < 0 || value >= this._numPages) {
2822 command: "page-num",
2825 this._pageNum = value;
2827 get pageWindowRect() {
2828 return [0, 0, 0, 0];
2830 set pageWindowRect(_) {
2831 throw new Error("doc.pageWindowRect is read-only");
2837 throw new Error("doc.path is read-only");
2839 get permStatusReady() {
2842 set permStatusReady(_) {
2843 throw new Error("doc.permStatusReady is read-only");
2846 return this._producer;
2849 throw new Error("doc.producer is read-only");
2851 get requiresFullSave() {
2854 set requiresFullSave(_) {
2855 throw new Error("doc.requiresFullSave is read-only");
2857 get securityHandler() {
2858 return this._securityHandler;
2860 set securityHandler(_) {
2861 throw new Error("doc.securityHandler is read-only");
2863 get selectedAnnots() {
2866 set selectedAnnots(_) {
2867 throw new Error("doc.selectedAnnots is read-only");
2873 throw new Error("doc.sounds is read-only");
2875 get spellDictionaryOrder() {
2876 return this._spellDictionaryOrder;
2878 set spellDictionaryOrder(spellDictionaryOrder) {
2879 this._spellDictionaryOrder = spellDictionaryOrder;
2881 get spellLanguageOrder() {
2882 return this._spellLanguageOrder;
2884 set spellLanguageOrder(spellLanguageOrder) {
2885 this._spellLanguageOrder = spellLanguageOrder;
2888 return this._subject;
2891 throw new Error("doc.subject is read-only");
2897 throw new Error("doc.templates is read-only");
2903 throw new Error("doc.title is read-only");
2909 throw new Error("doc.URL is read-only");
2915 throw new Error("doc.viewState is read-only");
2921 throw new Error("doc.xfa is read-only");
2923 get XFAForeground() {
2926 set XFAForeground(_) {
2927 throw new Error("doc.XFAForeground is read-only");
2930 return this._zoomType;
2932 set zoomType(type) {
2933 if (!this._userActivation) {
2936 this._userActivation = false;
2937 if (typeof type !== "string") {
2962 value: "page-height"
2977 this._zoomType = type;
2983 if (!this._userActivation) {
2986 this._userActivation = false;
2987 if (typeof value !== "number" || value < 8.33 || value > 6400) {
2999 addRecipientListCryptFilter() {}
3003 addWatermarkFromFile() {}
3004 addWatermarkFromText() {}
3008 this._eventDispatcher.calculateNow();
3011 colorConvertPage() {}
3012 createDataObject() {}
3016 embedDocAsDataObject() {}
3017 embedOutputIntent() {}
3018 encryptForRecipients() {}
3019 encryptUsingPolicy() {}
3024 exportAsXFDFStr() {}
3025 exportDataObject() {}
3033 getColorConvertAction() {}
3035 getDataObjectContents() {}
3037 if (cName && typeof cName === "object") {
3038 cName = cName.cName;
3040 if (typeof cName !== "string") {
3041 throw new TypeError("Invalid field name: must be a string");
3043 const searchedField = this._fields.get(cName);
3044 if (searchedField) {
3045 return searchedField;
3047 const parts = cName.split("#");
3048 let childIndex = NaN;
3049 if (parts.length === 2) {
3050 childIndex = Math.floor(parseFloat(parts[1]));
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) {
3060 if (childIndex < children.length) {
3061 this._fields.set(cName, children[childIndex]);
3062 return children[childIndex];
3065 this._fields.set(cName, field);
3072 const field = this._getField(cName);
3076 return field.wrapped;
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);
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);
3106 getLegalWarnings() {}
3108 getNthFieldName(nIndex) {
3109 if (nIndex && typeof nIndex === "object") {
3110 nIndex = nIndex.nIndex;
3112 if (typeof nIndex !== "number") {
3113 throw new TypeError("Invalid field index: must be a number");
3115 if (0 <= nIndex && nIndex < this.numFields) {
3116 return this._fieldNames[Math.trunc(nIndex)];
3128 getPageNthWordQuads() {}
3129 getPageNumWords() {}
3130 getPageRotation() {}
3131 getPageTransition() {}
3133 return this._printParams ||= new PrintParams({
3134 lastPage: this._numPages - 1
3143 importDataObject() {}
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) {
3158 this._userActivation = false;
3159 if (bUI && typeof bUI === "object") {
3160 nStart = bUI.nStart;
3162 bSilent = bUI.bSilent;
3163 bShrinkToFit = bUI.bShrinkToFit;
3164 bPrintAsImage = bUI.bPrintAsImage;
3165 bReverse = bUI.bReverse;
3166 bAnnotations = bUI.bAnnotations;
3167 printParams = bUI.printParams;
3171 nStart = printParams.firstPage;
3172 nEnd = printParams.lastPage;
3174 nStart = typeof nStart === "number" ? Math.max(0, Math.trunc(nStart)) : 0;
3175 nEnd = typeof nEnd === "number" ? Math.max(0, Math.trunc(nEnd)) : -1;
3182 removeDataObject() {}
3186 removeRequirement() {}
3189 removeThumbnails() {}
3192 resetForm(aFields = null) {
3193 if (aFields && typeof aFields === "object" && !Array.isArray(aFields)) {
3194 aFields = aFields.aFields;
3196 if (aFields && !Array.isArray(aFields)) {
3197 aFields = [aFields];
3199 let mustCalculate = false;
3203 for (const fieldName of aFields) {
3207 if (typeof fieldName !== "string") {
3208 fieldsToReset = null;
3211 const field = this._getField(fieldName);
3215 fieldsToReset.push(field);
3216 mustCalculate = true;
3219 if (!fieldsToReset) {
3220 fieldsToReset = this._fields.values();
3221 mustCalculate = this._fields.size !== 0;
3223 for (const field of fieldsToReset) {
3224 field.obj.value = field.obj.defaultValue;
3227 siblings: field.obj._siblings,
3228 value: field.obj.defaultValue,
3229 formattedValue: null,
3233 if (mustCalculate) {
3234 this.calculateNow();
3239 selectPageNthWord() {}
3241 setDataObjectContents() {}
3246 setPageRotations() {}
3247 setPageTabOrder() {}
3248 setPageTransitions() {}
3249 spawnPageFromTemplate() {}
3254 ;// ./src/scripting_api/proxy.js
3255 class ProxyHandler {
3257 this.nosend = new Set(["delay"]);
3260 if (prop in obj._expandos) {
3261 const val = obj._expandos[prop];
3262 if (typeof val === "function") {
3263 return val.bind(obj);
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);
3276 set(obj, prop, value) {
3278 obj._kidIds.forEach(id => {
3279 obj._appObjects[id].wrapped[prop] = value;
3282 if (typeof prop === "string" && !prop.startsWith("_") && prop in obj) {
3283 const old = obj[prop];
3285 if (!this.nosend.has(prop) && obj._send && obj._id !== null && typeof old !== "function") {
3289 data[prop] = prop === "value" ? obj._getValue() : obj[prop];
3290 if (!obj._siblings) {
3293 data.siblings = obj._siblings;
3298 obj._expandos[prop] = value;
3303 return prop in obj._expandos || typeof prop === "string" && !prop.startsWith("_") && prop in obj;
3305 getPrototypeOf(obj) {
3308 setPrototypeOf(obj, proto) {
3314 preventExtensions(obj) {
3317 getOwnPropertyDescriptor(obj, prop) {
3318 if (prop in obj._expandos) {
3322 value: obj._expandos[prop]
3325 if (typeof prop === "string" && !prop.startsWith("_") && prop in obj) {
3334 defineProperty(obj, key, descriptor) {
3335 Object.defineProperty(obj._expandos, key, descriptor);
3338 deleteProperty(obj, prop) {
3339 if (prop in obj._expandos) {
3340 delete obj._expandos[prop];
3344 const fromExpandos = Reflect.ownKeys(obj._expandos);
3345 const fromObj = Reflect.ownKeys(obj).filter(k => !k.startsWith("_"));
3346 return fromExpandos.concat(fromObj);
3350 ;// ./src/scripting_api/util.js
3352 class Util extends PDFObject {
3353 #dateActionsCache = null;
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;
3364 if (args.length === 0) {
3365 throw new Error("Invalid number of params in printf");
3367 if (typeof args[0] !== "string") {
3368 throw new TypeError("First argument of printf must be a string");
3370 const pattern = /%(,[0-4])?([+ 0#]+)?(\d+)?(\.\d+)?(.)/g;
3376 return args[0].replaceAll(pattern, function (match, nDecSep, cFlags, nWidth, nPrecision, cConvChar) {
3377 if (cConvChar !== "d" && cConvChar !== "f" && cConvChar !== "s" && cConvChar !== "x") {
3379 for (const str of [nDecSep, cFlags, nWidth, nPrecision, cConvChar]) {
3384 return buf.join("");
3387 if (i === args.length) {
3388 throw new Error("Not enough arguments in printf");
3390 const arg = args[i];
3391 if (cConvChar === "s") {
3392 return arg.toString();
3396 for (const flag of cFlags) {
3415 nWidth = parseInt(nWidth);
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" : " ");
3423 if (cFlags & HASH) {
3429 nPrecision = parseInt(nPrecision.substring(1));
3431 nDecSep = nDecSep ? nDecSep.substring(1) : "0";
3432 const separators = {
3439 const [thousandSep, decimalSep] = separators[nDecSep];
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]}`;
3448 decPart = `${decimalSep}${decPart.substring(2)}`;
3451 if (decPart === "1") {
3452 intPart += Math.sign(arg);
3454 decPart = cFlags & HASH ? "." : "";
3461 } else if (cFlags & PLUS) {
3463 } else if (cFlags & SPACE) {
3466 if (thousandSep && intPart >= 1000) {
3469 buf.push((intPart % 1000).toString().padStart(3, "0"));
3470 intPart = Math.trunc(intPart / 1000);
3471 if (intPart < 1000) {
3472 buf.push(intPart.toString());
3476 intPart = buf.reverse().join(thousandSep);
3478 intPart = intPart.toString();
3480 let n = `${intPart}${decPart}`;
3481 if (nWidth !== undefined) {
3482 n = n.padStart(nWidth - sign.length, cFlags & ZERO ? "0" : " ");
3484 return `${sign}${n}`;
3487 iconStreamFromIcon() {}
3488 printd(cFormat, oDate) {
3491 return this.printd("D:yyyymmddHHMMss", oDate);
3493 return this.printd("yyyy.mm.dd HH:MM:ss", oDate);
3495 return this.printd("m/d/yy h:MM:ss tt", oDate);
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"
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()
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);
3533 return pattern.charCodeAt(1);
3536 printx(cFormat, cSource) {
3537 cSource = (cSource ?? "").toString();
3538 const handlers = [x => x, x => x.toUpperCase(), x => x.toLowerCase()];
3541 const ii = cSource.length;
3542 let currCase = handlers[0];
3543 let escaped = false;
3544 for (const command of cFormat) {
3555 buf.push(currCase(cSource.charAt(i++)));
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));
3568 const char = cSource.charAt(i++);
3569 if ("a" <= char && char <= "z" || "A" <= char && char <= "Z") {
3570 buf.push(currCase(char));
3577 const char = cSource.charAt(i++);
3578 if ("0" <= char && char <= "9") {
3586 buf.push(currCase(cSource.charAt(i++)));
3593 currCase = handlers[1];
3596 currCase = handlers[2];
3599 currCase = handlers[0];
3605 return buf.join("");
3607 #tryToGuessDate(cFormat, cDate) {
3608 let actions = (this.#dateActionsCache ||= new Map()).get(cFormat);
3611 this.#dateActionsCache.set(cFormat, actions);
3612 cFormat.replaceAll(/(d+)|(m+)|(y+)|(H+)|(M+)|(s+)/g, function (_match, d, m, y, H, M, s) {
3614 actions.push((n, data) => {
3615 if (n >= 1 && n <= 31) {
3622 actions.push((n, data) => {
3623 if (n >= 1 && n <= 12) {
3630 actions.push((n, data) => {
3633 } else if (n < 100) {
3640 actions.push((n, data) => {
3641 if (n >= 0 && n <= 23) {
3648 actions.push((n, data) => {
3649 if (n >= 0 && n <= 59) {
3656 actions.push((n, data) => {
3657 if (n >= 0 && n <= 59) {
3667 const number = /\d+/g;
3671 year: new Date().getFullYear(),
3678 while ((array = number.exec(cDate)) !== null) {
3679 if (i < actions.length) {
3680 if (!actions[i++](parseInt(array[0]), data)) {
3690 return new Date(data.year, data.month, data.day, data.hours, data.minutes, data.seconds);
3692 scand(cFormat, cDate) {
3693 return this._scand(cFormat, cDate);
3695 _scand(cFormat, cDate, strict = false) {
3696 if (typeof cDate !== "string") {
3697 return new Date(cDate);
3704 return this.scand("D:yyyymmddHHMMss", cDate);
3706 return this.scand("yyyy.mm.dd HH:MM:ss", cDate);
3708 return this.scand("m/d/yy h:MM:ss tt", cDate);
3710 if (!this._scandCache.has(cFormat)) {
3711 const months = this._months;
3712 const days = this._days;
3715 pattern: `(${months.join("|")})`,
3716 action: (value, data) => {
3717 data.month = months.indexOf(value);
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);
3727 pattern: `(\\d{2})`,
3728 action: (value, data) => {
3729 data.month = parseInt(value) - 1;
3733 pattern: `(\\d{1,2})`,
3734 action: (value, data) => {
3735 data.month = parseInt(value) - 1;
3739 pattern: `(${days.join("|")})`,
3740 action: (value, data) => {
3741 data.day = days.indexOf(value);
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);
3751 pattern: "(\\d{2})",
3752 action: (value, data) => {
3753 data.day = parseInt(value);
3757 pattern: "(\\d{1,2})",
3758 action: (value, data) => {
3759 data.day = parseInt(value);
3763 pattern: "(\\d{4})",
3764 action: (value, data) => {
3765 data.year = parseInt(value);
3769 pattern: "(\\d{2})",
3770 action: (value, data) => {
3771 data.year = 2000 + parseInt(value);
3775 pattern: "(\\d{2})",
3776 action: (value, data) => {
3777 data.hours = parseInt(value);
3781 pattern: "(\\d{1,2})",
3782 action: (value, data) => {
3783 data.hours = parseInt(value);
3787 pattern: "(\\d{2})",
3788 action: (value, data) => {
3789 data.hours = parseInt(value);
3793 pattern: "(\\d{1,2})",
3794 action: (value, data) => {
3795 data.hours = parseInt(value);
3799 pattern: "(\\d{2})",
3800 action: (value, data) => {
3801 data.minutes = parseInt(value);
3805 pattern: "(\\d{1,2})",
3806 action: (value, data) => {
3807 data.minutes = parseInt(value);
3811 pattern: "(\\d{2})",
3812 action: (value, data) => {
3813 data.seconds = parseInt(value);
3817 pattern: "(\\d{1,2})",
3818 action: (value, data) => {
3819 data.seconds = parseInt(value);
3823 pattern: "([aApP][mM])",
3824 action: (value, data) => {
3825 const char = value.charAt(0);
3826 data.am = char === "a" || char === "A";
3830 pattern: "([aApP])",
3831 action: (value, data) => {
3832 data.am = value === "a" || value === "A";
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;
3839 const re = escapedFormat.replaceAll(patterns, function (match, patternElement) {
3843 } = handlers[patternElement];
3844 actions.push(action);
3847 this._scandCache.set(cFormat, [re, actions]);
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);
3855 year: new Date().getFullYear(),
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);
3867 return new Date(data.year, data.month, data.day, data.hours, data.minutes, data.seconds);
3870 stringFromStream() {}
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();
3895 const doc = new Doc({
3902 wrapped: new Proxy(doc, proxyHandler)
3904 const app = new App({
3909 calculationOrder: data.calculationOrder,
3913 const util = new Util({
3916 const appObjects = app._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);
3929 let obj = container;
3930 if (annotations.length > 0) {
3931 obj = annotations[0];
3934 obj.globalEval = globalEval;
3935 obj.doc = _document;
3936 obj.fieldPath = name;
3937 obj.appObjects = appObjects;
3938 const otherFields = annotations.slice(1);
3943 field = new RadioButtonField(otherFields, obj);
3948 field = new CheckboxField(otherFields, obj);
3952 if (otherFields.length > 0) {
3953 obj.siblings = otherFields.map(x => x.id);
3955 field = new Field(obj);
3957 const wrapped = new Proxy(field, proxyHandler);
3962 doc._addField(name, _object);
3963 for (const object of objs) {
3964 appObjects[object.id] = _object;
3967 appObjects[container.id] = _object;
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({
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;
3992 Reader_Value_Asked: true,
3993 Viewer_Value_Asked: true
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);
4001 for (const [name, value] of Object.entries(GlobalConstants)) {
4002 Object.defineProperty(globalThis, name, {
4007 Object.defineProperties(globalThis, {
4009 value: color.convert.bind(color),
4013 value: color.equal.bind(color),
4017 const properties = Object.create(null);
4018 for (const name of Object.getOwnPropertyNames(Doc.prototype)) {
4019 if (name === "constructor" || name.startsWith("_")) {
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)
4029 properties[name] = {
4030 value: Doc.prototype[name].bind(doc)
4034 Object.defineProperties(globalThis, properties);
4036 dispatchEvent: app._dispatchEvent.bind(app),
4037 timeoutCb: app._evalCallback.bind(app)
4039 return (name, args) => {
4041 functions[name](args);
4043 send(serializeError(error));
4048 ;// ./src/pdf.scripting.js
4050 const pdfjsVersion = "5.0.98";
4051 const pdfjsBuild = "16155fd80";
4052 globalThis.pdfjsScripting = {
4053 initSandbox: initSandbox