pdfjs-viewer-element 3.1.2 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ var n='/**\n * @licstart The following is the entire license notice for the\n * JavaScript code in this page\n *\n * Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @licend The above is the entire license notice for the\n * JavaScript code in this page\n */\n\n/**\n * pdfjsVersion = 5.5.207\n * pdfjsBuild = 527964698\n */\n/******/ var __webpack_modules__ = ({\n\n/***/ 9306\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isCallable = __webpack_require__(4901);\nvar tryToString = __webpack_require__(6823);\n\nvar $TypeError = TypeError;\n\n// `Assert: IsCallable(argument) is true`\nmodule.exports = function (argument) {\n if (isCallable(argument)) return argument;\n throw new $TypeError(tryToString(argument) + \' is not a function\');\n};\n\n\n/***/ },\n\n/***/ 6194\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar has = (__webpack_require__(2248).has);\n\n// Perform ? RequireInternalSlot(M, [[MapData]])\nmodule.exports = function (it) {\n has(it);\n return it;\n};\n\n\n/***/ },\n\n/***/ 3506\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isPossiblePrototype = __webpack_require__(3925);\n\nvar $String = String;\nvar $TypeError = TypeError;\n\nmodule.exports = function (argument) {\n if (isPossiblePrototype(argument)) return argument;\n throw new $TypeError("Can\'t set " + $String(argument) + \' as a prototype\');\n};\n\n\n/***/ },\n\n/***/ 7080\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar has = (__webpack_require__(4402).has);\n\n// Perform ? RequireInternalSlot(M, [[SetData]])\nmodule.exports = function (it) {\n has(it);\n return it;\n};\n\n\n/***/ },\n\n/***/ 3463\n(module) {\n\n\nvar $TypeError = TypeError;\n\nmodule.exports = function (argument) {\n if (typeof argument == \'string\') return argument;\n throw new $TypeError(\'Argument is not a string\');\n};\n\n\n/***/ },\n\n/***/ 4328\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar WeakMapHelpers = __webpack_require__(4995);\n\nvar weakmap = new WeakMapHelpers.WeakMap();\nvar set = WeakMapHelpers.set;\nvar remove = WeakMapHelpers.remove;\n\nmodule.exports = function (key) {\n set(weakmap, key, 1);\n remove(weakmap, key);\n return key;\n};\n\n\n/***/ },\n\n/***/ 6557\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar has = (__webpack_require__(4995).has);\n\n// Perform ? RequireInternalSlot(M, [[WeakMapData]])\nmodule.exports = function (it) {\n has(it);\n return it;\n};\n\n\n/***/ },\n\n/***/ 679\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isPrototypeOf = __webpack_require__(1625);\n\nvar $TypeError = TypeError;\n\nmodule.exports = function (it, Prototype) {\n if (isPrototypeOf(Prototype, it)) return it;\n throw new $TypeError(\'Incorrect invocation\');\n};\n\n\n/***/ },\n\n/***/ 3972\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isObject = __webpack_require__(34);\n\nvar $String = String;\nvar $TypeError = TypeError;\n\nmodule.exports = function (argument) {\n if (argument === undefined || isObject(argument)) return argument;\n throw new $TypeError($String(argument) + \' is not an object or undefined\');\n};\n\n\n/***/ },\n\n/***/ 8551\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isObject = __webpack_require__(34);\n\nvar $String = String;\nvar $TypeError = TypeError;\n\n// `Assert: Type(argument) is Object`\nmodule.exports = function (argument) {\n if (isObject(argument)) return argument;\n throw new $TypeError($String(argument) + \' is not an object\');\n};\n\n\n/***/ },\n\n/***/ 4154\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar classof = __webpack_require__(6955);\n\nvar $TypeError = TypeError;\n\n// Perform ? RequireInternalSlot(argument, [[TypedArrayName]])\n// If argument.[[TypedArrayName]] is not "Uint8Array", throw a TypeError exception\nmodule.exports = function (argument) {\n if (classof(argument) === \'Uint8Array\') return argument;\n throw new $TypeError(\'Argument is not an Uint8Array\');\n};\n\n\n/***/ },\n\n/***/ 7811\n(module) {\n\n\n// eslint-disable-next-line es/no-typed-arrays -- safe\nmodule.exports = typeof ArrayBuffer != \'undefined\' && typeof DataView != \'undefined\';\n\n\n/***/ },\n\n/***/ 7394\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar uncurryThisAccessor = __webpack_require__(6706);\nvar classof = __webpack_require__(2195);\n\nvar ArrayBuffer = globalThis.ArrayBuffer;\nvar TypeError = globalThis.TypeError;\n\n// Includes\n// - Perform ? RequireInternalSlot(O, [[ArrayBufferData]]).\n// - If IsSharedArrayBuffer(O) is true, throw a TypeError exception.\nmodule.exports = ArrayBuffer && uncurryThisAccessor(ArrayBuffer.prototype, \'byteLength\', \'get\') || function (O) {\n if (classof(O) !== \'ArrayBuffer\') throw new TypeError(\'ArrayBuffer expected\');\n return O.byteLength;\n};\n\n\n/***/ },\n\n/***/ 3238\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar NATIVE_ARRAY_BUFFER = __webpack_require__(7811);\nvar arrayBufferByteLength = __webpack_require__(7394);\n\nvar DataView = globalThis.DataView;\n\nmodule.exports = function (O) {\n if (!NATIVE_ARRAY_BUFFER || arrayBufferByteLength(O) !== 0) return false;\n try {\n // eslint-disable-next-line no-new -- thrower\n new DataView(O);\n return false;\n } catch (error) {\n return true;\n }\n};\n\n\n/***/ },\n\n/***/ 5169\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isDetached = __webpack_require__(3238);\n\nvar $TypeError = TypeError;\n\nmodule.exports = function (it) {\n if (isDetached(it)) throw new $TypeError(\'ArrayBuffer is detached\');\n return it;\n};\n\n\n/***/ },\n\n/***/ 5636\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar uncurryThis = __webpack_require__(9504);\nvar uncurryThisAccessor = __webpack_require__(6706);\nvar toIndex = __webpack_require__(7696);\nvar notDetached = __webpack_require__(5169);\nvar arrayBufferByteLength = __webpack_require__(7394);\nvar detachTransferable = __webpack_require__(4483);\nvar PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(1548);\n\nvar structuredClone = globalThis.structuredClone;\nvar ArrayBuffer = globalThis.ArrayBuffer;\nvar DataView = globalThis.DataView;\nvar min = Math.min;\nvar ArrayBufferPrototype = ArrayBuffer.prototype;\nvar DataViewPrototype = DataView.prototype;\nvar slice = uncurryThis(ArrayBufferPrototype.slice);\nvar isResizable = uncurryThisAccessor(ArrayBufferPrototype, \'resizable\', \'get\');\nvar maxByteLength = uncurryThisAccessor(ArrayBufferPrototype, \'maxByteLength\', \'get\');\nvar getInt8 = uncurryThis(DataViewPrototype.getInt8);\nvar setInt8 = uncurryThis(DataViewPrototype.setInt8);\n\nmodule.exports = (PROPER_STRUCTURED_CLONE_TRANSFER || detachTransferable) && function (arrayBuffer, newLength, preserveResizability) {\n var byteLength = arrayBufferByteLength(arrayBuffer);\n var newByteLength = newLength === undefined ? byteLength : toIndex(newLength);\n var fixedLength = !isResizable || !isResizable(arrayBuffer);\n var newBuffer;\n notDetached(arrayBuffer);\n if (PROPER_STRUCTURED_CLONE_TRANSFER) {\n arrayBuffer = structuredClone(arrayBuffer, { transfer: [arrayBuffer] });\n if (byteLength === newByteLength && (preserveResizability || fixedLength)) return arrayBuffer;\n }\n if (byteLength >= newByteLength && (!preserveResizability || fixedLength)) {\n newBuffer = slice(arrayBuffer, 0, newByteLength);\n } else {\n var options = preserveResizability && !fixedLength && maxByteLength ? { maxByteLength: maxByteLength(arrayBuffer) } : undefined;\n newBuffer = new ArrayBuffer(newByteLength, options);\n var a = new DataView(arrayBuffer);\n var b = new DataView(newBuffer);\n var copyLength = min(newByteLength, byteLength);\n for (var i = 0; i < copyLength; i++) setInt8(b, i, getInt8(a, i));\n }\n if (!PROPER_STRUCTURED_CLONE_TRANSFER) detachTransferable(arrayBuffer);\n return newBuffer;\n};\n\n\n/***/ },\n\n/***/ 4644\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar NATIVE_ARRAY_BUFFER = __webpack_require__(7811);\nvar DESCRIPTORS = __webpack_require__(3724);\nvar globalThis = __webpack_require__(4576);\nvar isCallable = __webpack_require__(4901);\nvar isObject = __webpack_require__(34);\nvar hasOwn = __webpack_require__(9297);\nvar classof = __webpack_require__(6955);\nvar tryToString = __webpack_require__(6823);\nvar createNonEnumerableProperty = __webpack_require__(6699);\nvar defineBuiltIn = __webpack_require__(6840);\nvar defineBuiltInAccessor = __webpack_require__(2106);\nvar isPrototypeOf = __webpack_require__(1625);\nvar getPrototypeOf = __webpack_require__(2787);\nvar setPrototypeOf = __webpack_require__(2967);\nvar wellKnownSymbol = __webpack_require__(8227);\nvar uid = __webpack_require__(3392);\nvar InternalStateModule = __webpack_require__(1181);\n\nvar enforceInternalState = InternalStateModule.enforce;\nvar getInternalState = InternalStateModule.get;\nvar Int8Array = globalThis.Int8Array;\nvar Int8ArrayPrototype = Int8Array && Int8Array.prototype;\nvar Uint8ClampedArray = globalThis.Uint8ClampedArray;\nvar Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;\nvar TypedArray = Int8Array && getPrototypeOf(Int8Array);\nvar TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);\nvar ObjectPrototype = Object.prototype;\nvar TypeError = globalThis.TypeError;\n\nvar TO_STRING_TAG = wellKnownSymbol(\'toStringTag\');\nvar TYPED_ARRAY_TAG = uid(\'TYPED_ARRAY_TAG\');\nvar TYPED_ARRAY_CONSTRUCTOR = \'TypedArrayConstructor\';\n// Fixing native typed arrays in Opera Presto crashes the browser, see #595\nvar NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(globalThis.opera) !== \'Opera\';\nvar TYPED_ARRAY_TAG_REQUIRED = false;\nvar NAME, Constructor, Prototype;\n\nvar TypedArrayConstructorsList = {\n Int8Array: 1,\n Uint8Array: 1,\n Uint8ClampedArray: 1,\n Int16Array: 2,\n Uint16Array: 2,\n Int32Array: 4,\n Uint32Array: 4,\n Float32Array: 4,\n Float64Array: 8\n};\n\nvar BigIntArrayConstructorsList = {\n BigInt64Array: 8,\n BigUint64Array: 8\n};\n\nvar isView = function isView(it) {\n if (!isObject(it)) return false;\n var klass = classof(it);\n return klass === \'DataView\'\n || hasOwn(TypedArrayConstructorsList, klass)\n || hasOwn(BigIntArrayConstructorsList, klass);\n};\n\nvar getTypedArrayConstructor = function (it) {\n var proto = getPrototypeOf(it);\n if (!isObject(proto)) return;\n var state = getInternalState(proto);\n return (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor(proto);\n};\n\nvar isTypedArray = function (it) {\n if (!isObject(it)) return false;\n var klass = classof(it);\n return hasOwn(TypedArrayConstructorsList, klass)\n || hasOwn(BigIntArrayConstructorsList, klass);\n};\n\nvar aTypedArray = function (it) {\n if (isTypedArray(it)) return it;\n throw new TypeError(\'Target is not a typed array\');\n};\n\nvar aTypedArrayConstructor = function (C) {\n if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C;\n throw new TypeError(tryToString(C) + \' is not a typed array constructor\');\n};\n\nvar exportTypedArrayMethod = function (KEY, property, forced, options) {\n if (!DESCRIPTORS) return;\n if (forced) for (var ARRAY in TypedArrayConstructorsList) {\n var TypedArrayConstructor = globalThis[ARRAY];\n if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try {\n delete TypedArrayConstructor.prototype[KEY];\n } catch (error) {\n // old WebKit bug - some methods are non-configurable\n try {\n TypedArrayConstructor.prototype[KEY] = property;\n } catch (error2) { /* empty */ }\n }\n }\n if (!TypedArrayPrototype[KEY] || forced) {\n defineBuiltIn(TypedArrayPrototype, KEY, forced ? property\n : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options);\n }\n};\n\nvar exportTypedArrayStaticMethod = function (KEY, property, forced) {\n var ARRAY, TypedArrayConstructor;\n if (!DESCRIPTORS) return;\n if (setPrototypeOf) {\n if (forced) for (ARRAY in TypedArrayConstructorsList) {\n TypedArrayConstructor = globalThis[ARRAY];\n if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try {\n delete TypedArrayConstructor[KEY];\n } catch (error) { /* empty */ }\n }\n if (!TypedArray[KEY] || forced) {\n // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable\n try {\n return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property);\n } catch (error) { /* empty */ }\n } else return;\n }\n for (ARRAY in TypedArrayConstructorsList) {\n TypedArrayConstructor = globalThis[ARRAY];\n if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {\n defineBuiltIn(TypedArrayConstructor, KEY, property);\n }\n }\n};\n\nfor (NAME in TypedArrayConstructorsList) {\n Constructor = globalThis[NAME];\n Prototype = Constructor && Constructor.prototype;\n if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;\n else NATIVE_ARRAY_BUFFER_VIEWS = false;\n}\n\nfor (NAME in BigIntArrayConstructorsList) {\n Constructor = globalThis[NAME];\n Prototype = Constructor && Constructor.prototype;\n if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;\n}\n\n// WebKit bug - typed arrays constructors prototype is Object.prototype\nif (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) {\n // eslint-disable-next-line no-shadow -- safe\n TypedArray = function TypedArray() {\n throw new TypeError(\'Incorrect invocation\');\n };\n if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {\n if (globalThis[NAME]) setPrototypeOf(globalThis[NAME], TypedArray);\n }\n}\n\nif (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {\n TypedArrayPrototype = TypedArray.prototype;\n if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {\n if (globalThis[NAME]) setPrototypeOf(globalThis[NAME].prototype, TypedArrayPrototype);\n }\n}\n\n// WebKit bug - one more object in Uint8ClampedArray prototype chain\nif (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {\n setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);\n}\n\nif (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) {\n TYPED_ARRAY_TAG_REQUIRED = true;\n defineBuiltInAccessor(TypedArrayPrototype, TO_STRING_TAG, {\n configurable: true,\n get: function () {\n return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;\n }\n });\n for (NAME in TypedArrayConstructorsList) if (globalThis[NAME]) {\n createNonEnumerableProperty(globalThis[NAME], TYPED_ARRAY_TAG, NAME);\n }\n}\n\nmodule.exports = {\n NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,\n TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG,\n aTypedArray: aTypedArray,\n aTypedArrayConstructor: aTypedArrayConstructor,\n exportTypedArrayMethod: exportTypedArrayMethod,\n exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,\n getTypedArrayConstructor: getTypedArrayConstructor,\n isView: isView,\n isTypedArray: isTypedArray,\n TypedArray: TypedArray,\n TypedArrayPrototype: TypedArrayPrototype\n};\n\n\n/***/ },\n\n/***/ 5370\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar lengthOfArrayLike = __webpack_require__(6198);\n\nmodule.exports = function (Constructor, list, $length) {\n var index = 0;\n var length = arguments.length > 2 ? $length : lengthOfArrayLike(list);\n var result = new Constructor(length);\n while (length > index) result[index] = list[index++];\n return result;\n};\n\n\n/***/ },\n\n/***/ 9617\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar toIndexedObject = __webpack_require__(5397);\nvar toAbsoluteIndex = __webpack_require__(5610);\nvar lengthOfArrayLike = __webpack_require__(6198);\n\n// `Array.prototype.{ indexOf, includes }` methods implementation\nvar createMethod = function (IS_INCLUDES) {\n return function ($this, el, fromIndex) {\n var O = toIndexedObject($this);\n var length = lengthOfArrayLike(O);\n if (length === 0) return !IS_INCLUDES && -1;\n var index = toAbsoluteIndex(fromIndex, length);\n var value;\n // Array#includes uses SameValueZero equality algorithm\n // eslint-disable-next-line no-self-compare -- NaN check\n if (IS_INCLUDES && el !== el) while (length > index) {\n value = O[index++];\n // eslint-disable-next-line no-self-compare -- NaN check\n if (value !== value) return true;\n // Array#indexOf ignores holes, Array#includes - not\n } else for (;length > index; index++) {\n if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;\n } return !IS_INCLUDES && -1;\n };\n};\n\nmodule.exports = {\n // `Array.prototype.includes` method\n // https://tc39.es/ecma262/#sec-array.prototype.includes\n includes: createMethod(true),\n // `Array.prototype.indexOf` method\n // https://tc39.es/ecma262/#sec-array.prototype.indexof\n indexOf: createMethod(false)\n};\n\n\n/***/ },\n\n/***/ 4527\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar isArray = __webpack_require__(4376);\n\nvar $TypeError = TypeError;\n// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\n// Safari < 13 does not throw an error in this case\nvar SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {\n // makes no sense without proper strict mode support\n if (this !== undefined) return true;\n try {\n // eslint-disable-next-line es/no-object-defineproperty -- safe\n Object.defineProperty([], \'length\', { writable: false }).length = 1;\n } catch (error) {\n return error instanceof TypeError;\n }\n}();\n\nmodule.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {\n if (isArray(O) && !getOwnPropertyDescriptor(O, \'length\').writable) {\n throw new $TypeError(\'Cannot set read only .length\');\n } return O.length = length;\n} : function (O, length) {\n return O.length = length;\n};\n\n\n/***/ },\n\n/***/ 7680\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\n\nmodule.exports = uncurryThis([].slice);\n\n\n/***/ },\n\n/***/ 2804\n(module) {\n\n\nvar commonAlphabet = \'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\';\nvar base64Alphabet = commonAlphabet + \'+/\';\nvar base64UrlAlphabet = commonAlphabet + \'-_\';\n\nvar inverse = function (characters) {\n // TODO: use `Object.create(null)` in `core-js@4`\n var result = {};\n var index = 0;\n for (; index < 64; index++) result[characters.charAt(index)] = index;\n return result;\n};\n\nmodule.exports = {\n i2c: base64Alphabet,\n c2i: inverse(base64Alphabet),\n i2cUrl: base64UrlAlphabet,\n c2iUrl: inverse(base64UrlAlphabet)\n};\n\n\n/***/ },\n\n/***/ 6319\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar anObject = __webpack_require__(8551);\nvar iteratorClose = __webpack_require__(9539);\n\n// call something on iterator step with safe closing on error\nmodule.exports = function (iterator, fn, value, ENTRIES) {\n try {\n return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);\n } catch (error) {\n iteratorClose(iterator, \'throw\', error);\n }\n};\n\n\n/***/ },\n\n/***/ 2195\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\n\nvar toString = uncurryThis({}.toString);\nvar stringSlice = uncurryThis(\'\'.slice);\n\nmodule.exports = function (it) {\n return stringSlice(toString(it), 8, -1);\n};\n\n\n/***/ },\n\n/***/ 6955\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar TO_STRING_TAG_SUPPORT = __webpack_require__(2140);\nvar isCallable = __webpack_require__(4901);\nvar classofRaw = __webpack_require__(2195);\nvar wellKnownSymbol = __webpack_require__(8227);\n\nvar TO_STRING_TAG = wellKnownSymbol(\'toStringTag\');\nvar $Object = Object;\n\n// ES3 wrong here\nvar CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === \'Arguments\';\n\n// fallback for IE11 Script Access Denied error\nvar tryGet = function (it, key) {\n try {\n return it[key];\n } catch (error) { /* empty */ }\n};\n\n// getting tag from ES6+ `Object.prototype.toString`\nmodule.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {\n var O, tag, result;\n return it === undefined ? \'Undefined\' : it === null ? \'Null\'\n // @@toStringTag case\n : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == \'string\' ? tag\n // builtinTag case\n : CORRECT_ARGUMENTS ? classofRaw(O)\n // ES3 arguments fallback\n : (result = classofRaw(O)) === \'Object\' && isCallable(O.callee) ? \'Arguments\' : result;\n};\n\n\n/***/ },\n\n/***/ 7740\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar hasOwn = __webpack_require__(9297);\nvar ownKeys = __webpack_require__(5031);\nvar getOwnPropertyDescriptorModule = __webpack_require__(7347);\nvar definePropertyModule = __webpack_require__(4913);\n\nmodule.exports = function (target, source, exceptions) {\n var keys = ownKeys(source);\n var defineProperty = definePropertyModule.f;\n var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {\n defineProperty(target, key, getOwnPropertyDescriptor(source, key));\n }\n }\n};\n\n\n/***/ },\n\n/***/ 2211\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar fails = __webpack_require__(9039);\n\nmodule.exports = !fails(function () {\n function F() { /* empty */ }\n F.prototype.constructor = null;\n // eslint-disable-next-line es/no-object-getprototypeof -- required for testing\n return Object.getPrototypeOf(new F()) !== F.prototype;\n});\n\n\n/***/ },\n\n/***/ 2529\n(module) {\n\n\n// `CreateIterResultObject` abstract operation\n// https://tc39.es/ecma262/#sec-createiterresultobject\nmodule.exports = function (value, done) {\n return { value: value, done: done };\n};\n\n\n/***/ },\n\n/***/ 6699\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar definePropertyModule = __webpack_require__(4913);\nvar createPropertyDescriptor = __webpack_require__(6980);\n\nmodule.exports = DESCRIPTORS ? function (object, key, value) {\n return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));\n} : function (object, key, value) {\n object[key] = value;\n return object;\n};\n\n\n/***/ },\n\n/***/ 6980\n(module) {\n\n\nmodule.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n\n\n/***/ },\n\n/***/ 4659\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar definePropertyModule = __webpack_require__(4913);\nvar createPropertyDescriptor = __webpack_require__(6980);\n\nmodule.exports = function (object, key, value) {\n if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));\n else object[key] = value;\n};\n\n\n/***/ },\n\n/***/ 2106\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar makeBuiltIn = __webpack_require__(283);\nvar defineProperty = __webpack_require__(4913);\n\nmodule.exports = function (target, name, descriptor) {\n if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });\n if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });\n return defineProperty.f(target, name, descriptor);\n};\n\n\n/***/ },\n\n/***/ 6840\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isCallable = __webpack_require__(4901);\nvar definePropertyModule = __webpack_require__(4913);\nvar makeBuiltIn = __webpack_require__(283);\nvar defineGlobalProperty = __webpack_require__(9433);\n\nmodule.exports = function (O, key, value, options) {\n if (!options) options = {};\n var simple = options.enumerable;\n var name = options.name !== undefined ? options.name : key;\n if (isCallable(value)) makeBuiltIn(value, name, options);\n if (options.global) {\n if (simple) O[key] = value;\n else defineGlobalProperty(key, value);\n } else {\n try {\n if (!options.unsafe) delete O[key];\n else if (O[key]) simple = true;\n } catch (error) { /* empty */ }\n if (simple) O[key] = value;\n else definePropertyModule.f(O, key, {\n value: value,\n enumerable: false,\n configurable: !options.nonConfigurable,\n writable: !options.nonWritable\n });\n } return O;\n};\n\n\n/***/ },\n\n/***/ 6279\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar defineBuiltIn = __webpack_require__(6840);\n\nmodule.exports = function (target, src, options) {\n for (var key in src) defineBuiltIn(target, key, src[key], options);\n return target;\n};\n\n\n/***/ },\n\n/***/ 9433\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\n\n// eslint-disable-next-line es/no-object-defineproperty -- safe\nvar defineProperty = Object.defineProperty;\n\nmodule.exports = function (key, value) {\n try {\n defineProperty(globalThis, key, { value: value, configurable: true, writable: true });\n } catch (error) {\n globalThis[key] = value;\n } return value;\n};\n\n\n/***/ },\n\n/***/ 3724\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar fails = __webpack_require__(9039);\n\n// Detect IE8\'s incomplete defineProperty implementation\nmodule.exports = !fails(function () {\n // eslint-disable-next-line es/no-object-defineproperty -- required for testing\n return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;\n});\n\n\n/***/ },\n\n/***/ 4483\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar getBuiltInNodeModule = __webpack_require__(9429);\nvar PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(1548);\n\nvar structuredClone = globalThis.structuredClone;\nvar $ArrayBuffer = globalThis.ArrayBuffer;\nvar $MessageChannel = globalThis.MessageChannel;\nvar detach = false;\nvar WorkerThreads, channel, buffer, $detach;\n\nif (PROPER_STRUCTURED_CLONE_TRANSFER) {\n detach = function (transferable) {\n structuredClone(transferable, { transfer: [transferable] });\n };\n} else if ($ArrayBuffer) try {\n if (!$MessageChannel) {\n WorkerThreads = getBuiltInNodeModule(\'worker_threads\');\n if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel;\n }\n\n if ($MessageChannel) {\n channel = new $MessageChannel();\n buffer = new $ArrayBuffer(2);\n\n $detach = function (transferable) {\n channel.port1.postMessage(null, [transferable]);\n };\n\n if (buffer.byteLength === 2) {\n $detach(buffer);\n if (buffer.byteLength === 0) detach = $detach;\n }\n }\n} catch (error) { /* empty */ }\n\nmodule.exports = detach;\n\n\n/***/ },\n\n/***/ 4055\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar isObject = __webpack_require__(34);\n\nvar document = globalThis.document;\n// typeof document.createElement is \'object\' in old IE\nvar EXISTS = isObject(document) && isObject(document.createElement);\n\nmodule.exports = function (it) {\n return EXISTS ? document.createElement(it) : {};\n};\n\n\n/***/ },\n\n/***/ 6837\n(module) {\n\n\nvar $TypeError = TypeError;\nvar MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991\n\nmodule.exports = function (it) {\n if (it > MAX_SAFE_INTEGER) throw $TypeError(\'Maximum allowed index exceeded\');\n return it;\n};\n\n\n/***/ },\n\n/***/ 5002\n(module) {\n\n\nmodule.exports = {\n IndexSizeError: { s: \'INDEX_SIZE_ERR\', c: 1, m: 1 },\n DOMStringSizeError: { s: \'DOMSTRING_SIZE_ERR\', c: 2, m: 0 },\n HierarchyRequestError: { s: \'HIERARCHY_REQUEST_ERR\', c: 3, m: 1 },\n WrongDocumentError: { s: \'WRONG_DOCUMENT_ERR\', c: 4, m: 1 },\n InvalidCharacterError: { s: \'INVALID_CHARACTER_ERR\', c: 5, m: 1 },\n NoDataAllowedError: { s: \'NO_DATA_ALLOWED_ERR\', c: 6, m: 0 },\n NoModificationAllowedError: { s: \'NO_MODIFICATION_ALLOWED_ERR\', c: 7, m: 1 },\n NotFoundError: { s: \'NOT_FOUND_ERR\', c: 8, m: 1 },\n NotSupportedError: { s: \'NOT_SUPPORTED_ERR\', c: 9, m: 1 },\n InUseAttributeError: { s: \'INUSE_ATTRIBUTE_ERR\', c: 10, m: 1 },\n InvalidStateError: { s: \'INVALID_STATE_ERR\', c: 11, m: 1 },\n SyntaxError: { s: \'SYNTAX_ERR\', c: 12, m: 1 },\n InvalidModificationError: { s: \'INVALID_MODIFICATION_ERR\', c: 13, m: 1 },\n NamespaceError: { s: \'NAMESPACE_ERR\', c: 14, m: 1 },\n InvalidAccessError: { s: \'INVALID_ACCESS_ERR\', c: 15, m: 1 },\n ValidationError: { s: \'VALIDATION_ERR\', c: 16, m: 0 },\n TypeMismatchError: { s: \'TYPE_MISMATCH_ERR\', c: 17, m: 1 },\n SecurityError: { s: \'SECURITY_ERR\', c: 18, m: 1 },\n NetworkError: { s: \'NETWORK_ERR\', c: 19, m: 1 },\n AbortError: { s: \'ABORT_ERR\', c: 20, m: 1 },\n URLMismatchError: { s: \'URL_MISMATCH_ERR\', c: 21, m: 1 },\n QuotaExceededError: { s: \'QUOTA_EXCEEDED_ERR\', c: 22, m: 1 },\n TimeoutError: { s: \'TIMEOUT_ERR\', c: 23, m: 1 },\n InvalidNodeTypeError: { s: \'INVALID_NODE_TYPE_ERR\', c: 24, m: 1 },\n DataCloneError: { s: \'DATA_CLONE_ERR\', c: 25, m: 1 }\n};\n\n\n/***/ },\n\n/***/ 8727\n(module) {\n\n\n// IE8- don\'t enum bug keys\nmodule.exports = [\n \'constructor\',\n \'hasOwnProperty\',\n \'isPrototypeOf\',\n \'propertyIsEnumerable\',\n \'toLocaleString\',\n \'toString\',\n \'valueOf\'\n];\n\n\n/***/ },\n\n/***/ 6193\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar ENVIRONMENT = __webpack_require__(4215);\n\nmodule.exports = ENVIRONMENT === \'NODE\';\n\n\n/***/ },\n\n/***/ 2839\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\n\nvar navigator = globalThis.navigator;\nvar userAgent = navigator && navigator.userAgent;\n\nmodule.exports = userAgent ? String(userAgent) : \'\';\n\n\n/***/ },\n\n/***/ 9519\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar userAgent = __webpack_require__(2839);\n\nvar process = globalThis.process;\nvar Deno = globalThis.Deno;\nvar versions = process && process.versions || Deno && Deno.version;\nvar v8 = versions && versions.v8;\nvar match, version;\n\nif (v8) {\n match = v8.split(\'.\');\n // in old Chrome, versions of V8 isn\'t V8 = Chrome / 10\n // but their correct versions are not interesting for us\n version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);\n}\n\n// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`\n// so check `userAgent` even if `.v8` exists, but 0\nif (!version && userAgent) {\n match = userAgent.match(/Edge\\/(\\d+)/);\n if (!match || match[1] >= 74) {\n match = userAgent.match(/Chrome\\/(\\d+)/);\n if (match) version = +match[1];\n }\n}\n\nmodule.exports = version;\n\n\n/***/ },\n\n/***/ 4215\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\n/* global Bun, Deno -- detection */\nvar globalThis = __webpack_require__(4576);\nvar userAgent = __webpack_require__(2839);\nvar classof = __webpack_require__(2195);\n\nvar userAgentStartsWith = function (string) {\n return userAgent.slice(0, string.length) === string;\n};\n\nmodule.exports = (function () {\n if (userAgentStartsWith(\'Bun/\')) return \'BUN\';\n if (userAgentStartsWith(\'Cloudflare-Workers\')) return \'CLOUDFLARE\';\n if (userAgentStartsWith(\'Deno/\')) return \'DENO\';\n if (userAgentStartsWith(\'Node.js/\')) return \'NODE\';\n if (globalThis.Bun && typeof Bun.version == \'string\') return \'BUN\';\n if (globalThis.Deno && typeof Deno.version == \'object\') return \'DENO\';\n if (classof(globalThis.process) === \'process\') return \'NODE\';\n if (globalThis.window && globalThis.document) return \'BROWSER\';\n return \'REST\';\n})();\n\n\n/***/ },\n\n/***/ 8574\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\n\nvar $Error = Error;\nvar replace = uncurryThis(\'\'.replace);\n\nvar TEST = (function (arg) { return String(new $Error(arg).stack); })(\'zxcasd\');\n// eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe\nvar V8_OR_CHAKRA_STACK_ENTRY = /\\n\\s*at [^:]*:[^\\n]*/;\nvar IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);\n\nmodule.exports = function (stack, dropEntries) {\n if (IS_V8_OR_CHAKRA_STACK && typeof stack == \'string\' && !$Error.prepareStackTrace) {\n while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, \'\');\n } return stack;\n};\n\n\n/***/ },\n\n/***/ 6518\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar getOwnPropertyDescriptor = (__webpack_require__(7347).f);\nvar createNonEnumerableProperty = __webpack_require__(6699);\nvar defineBuiltIn = __webpack_require__(6840);\nvar defineGlobalProperty = __webpack_require__(9433);\nvar copyConstructorProperties = __webpack_require__(7740);\nvar isForced = __webpack_require__(2796);\n\n/*\n options.target - name of the target object\n options.global - target is the global object\n options.stat - export as static methods of target\n options.proto - export as prototype methods of target\n options.real - real prototype method for the `pure` version\n options.forced - export even if the native feature is available\n options.bind - bind methods to the target, required for the `pure` version\n options.wrap - wrap constructors to preventing global pollution, required for the `pure` version\n options.unsafe - use the simple assignment of property instead of delete + defineProperty\n options.sham - add a flag to not completely full polyfills\n options.enumerable - export as enumerable property\n options.dontCallGetSet - prevent calling a getter on target\n options.name - the .name of the function if it does not match the key\n*/\nmodule.exports = function (options, source) {\n var TARGET = options.target;\n var GLOBAL = options.global;\n var STATIC = options.stat;\n var FORCED, target, key, targetProperty, sourceProperty, descriptor;\n if (GLOBAL) {\n target = globalThis;\n } else if (STATIC) {\n target = globalThis[TARGET] || defineGlobalProperty(TARGET, {});\n } else {\n target = globalThis[TARGET] && globalThis[TARGET].prototype;\n }\n if (target) for (key in source) {\n sourceProperty = source[key];\n if (options.dontCallGetSet) {\n descriptor = getOwnPropertyDescriptor(target, key);\n targetProperty = descriptor && descriptor.value;\n } else targetProperty = target[key];\n FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? \'.\' : \'#\') + key, options.forced);\n // contained in target\n if (!FORCED && targetProperty !== undefined) {\n if (typeof sourceProperty == typeof targetProperty) continue;\n copyConstructorProperties(sourceProperty, targetProperty);\n }\n // add a flag to not completely full polyfills\n if (options.sham || (targetProperty && targetProperty.sham)) {\n createNonEnumerableProperty(sourceProperty, \'sham\', true);\n }\n defineBuiltIn(target, key, sourceProperty, options);\n }\n};\n\n\n/***/ },\n\n/***/ 9039\n(module) {\n\n\nmodule.exports = function (exec) {\n try {\n return !!exec();\n } catch (error) {\n return true;\n }\n};\n\n\n/***/ },\n\n/***/ 8745\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar NATIVE_BIND = __webpack_require__(616);\n\nvar FunctionPrototype = Function.prototype;\nvar apply = FunctionPrototype.apply;\nvar call = FunctionPrototype.call;\n\n// eslint-disable-next-line es/no-function-prototype-bind, es/no-reflect -- safe\nmodule.exports = typeof Reflect == \'object\' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () {\n return call.apply(apply, arguments);\n});\n\n\n/***/ },\n\n/***/ 6080\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(7476);\nvar aCallable = __webpack_require__(9306);\nvar NATIVE_BIND = __webpack_require__(616);\n\nvar bind = uncurryThis(uncurryThis.bind);\n\n// optional / simple context binding\nmodule.exports = function (fn, that) {\n aCallable(fn);\n return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n\n\n/***/ },\n\n/***/ 616\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar fails = __webpack_require__(9039);\n\nmodule.exports = !fails(function () {\n // eslint-disable-next-line es/no-function-prototype-bind -- safe\n var test = (function () { /* empty */ }).bind();\n // eslint-disable-next-line no-prototype-builtins -- safe\n return typeof test != \'function\' || test.hasOwnProperty(\'prototype\');\n});\n\n\n/***/ },\n\n/***/ 9565\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar NATIVE_BIND = __webpack_require__(616);\n\nvar call = Function.prototype.call;\n// eslint-disable-next-line es/no-function-prototype-bind -- safe\nmodule.exports = NATIVE_BIND ? call.bind(call) : function () {\n return call.apply(call, arguments);\n};\n\n\n/***/ },\n\n/***/ 350\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar hasOwn = __webpack_require__(9297);\n\nvar FunctionPrototype = Function.prototype;\n// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\nvar getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;\n\nvar EXISTS = hasOwn(FunctionPrototype, \'name\');\n// additional protection from minified / mangled / dropped function names\nvar PROPER = EXISTS && (function something() { /* empty */ }).name === \'something\';\nvar CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, \'name\').configurable));\n\nmodule.exports = {\n EXISTS: EXISTS,\n PROPER: PROPER,\n CONFIGURABLE: CONFIGURABLE\n};\n\n\n/***/ },\n\n/***/ 6706\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\nvar aCallable = __webpack_require__(9306);\n\nmodule.exports = function (object, key, method) {\n try {\n // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\n return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));\n } catch (error) { /* empty */ }\n};\n\n\n/***/ },\n\n/***/ 7476\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar classofRaw = __webpack_require__(2195);\nvar uncurryThis = __webpack_require__(9504);\n\nmodule.exports = function (fn) {\n // Nashorn bug:\n // https://github.com/zloirock/core-js/issues/1128\n // https://github.com/zloirock/core-js/issues/1130\n if (classofRaw(fn) === \'Function\') return uncurryThis(fn);\n};\n\n\n/***/ },\n\n/***/ 9504\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar NATIVE_BIND = __webpack_require__(616);\n\nvar FunctionPrototype = Function.prototype;\nvar call = FunctionPrototype.call;\n// eslint-disable-next-line es/no-function-prototype-bind -- safe\nvar uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);\n\nmodule.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) {\n return function () {\n return call.apply(fn, arguments);\n };\n};\n\n\n/***/ },\n\n/***/ 944\n(module) {\n\n\nvar $TypeError = TypeError;\n\nmodule.exports = function (options) {\n var alphabet = options && options.alphabet;\n if (alphabet === undefined || alphabet === \'base64\' || alphabet === \'base64url\') return alphabet || \'base64\';\n throw new $TypeError(\'Incorrect `alphabet` option\');\n};\n\n\n/***/ },\n\n/***/ 9429\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar IS_NODE = __webpack_require__(6193);\n\nmodule.exports = function (name) {\n if (IS_NODE) {\n try {\n return globalThis.process.getBuiltinModule(name);\n } catch (error) { /* empty */ }\n try {\n // eslint-disable-next-line no-new-func -- safe\n return Function(\'return require("\' + name + \'")\')();\n } catch (error) { /* empty */ }\n }\n};\n\n\n/***/ },\n\n/***/ 7751\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar isCallable = __webpack_require__(4901);\n\nvar aFunction = function (argument) {\n return isCallable(argument) ? argument : undefined;\n};\n\nmodule.exports = function (namespace, method) {\n return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method];\n};\n\n\n/***/ },\n\n/***/ 1767\n(module) {\n\n\n// `GetIteratorDirect(obj)` abstract operation\n// https://tc39.es/ecma262/#sec-getiteratordirect\nmodule.exports = function (obj) {\n return {\n iterator: obj,\n next: obj.next,\n done: false\n };\n};\n\n\n/***/ },\n\n/***/ 8646\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar call = __webpack_require__(9565);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar getIteratorMethod = __webpack_require__(851);\n\nmodule.exports = function (obj, stringHandling) {\n if (!stringHandling || typeof obj !== \'string\') anObject(obj);\n var method = getIteratorMethod(obj);\n return getIteratorDirect(anObject(method !== undefined ? call(method, obj) : obj));\n};\n\n\n/***/ },\n\n/***/ 851\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar classof = __webpack_require__(6955);\nvar getMethod = __webpack_require__(5966);\nvar isNullOrUndefined = __webpack_require__(4117);\nvar Iterators = __webpack_require__(6269);\nvar wellKnownSymbol = __webpack_require__(8227);\n\nvar ITERATOR = wellKnownSymbol(\'iterator\');\n\nmodule.exports = function (it) {\n if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)\n || getMethod(it, \'@@iterator\')\n || Iterators[classof(it)];\n};\n\n\n/***/ },\n\n/***/ 81\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar call = __webpack_require__(9565);\nvar aCallable = __webpack_require__(9306);\nvar anObject = __webpack_require__(8551);\nvar tryToString = __webpack_require__(6823);\nvar getIteratorMethod = __webpack_require__(851);\n\nvar $TypeError = TypeError;\n\nmodule.exports = function (argument, usingIterator) {\n var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;\n if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));\n throw new $TypeError(tryToString(argument) + \' is not iterable\');\n};\n\n\n/***/ },\n\n/***/ 5966\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar aCallable = __webpack_require__(9306);\nvar isNullOrUndefined = __webpack_require__(4117);\n\n// `GetMethod` abstract operation\n// https://tc39.es/ecma262/#sec-getmethod\nmodule.exports = function (V, P) {\n var func = V[P];\n return isNullOrUndefined(func) ? undefined : aCallable(func);\n};\n\n\n/***/ },\n\n/***/ 3789\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar aCallable = __webpack_require__(9306);\nvar anObject = __webpack_require__(8551);\nvar call = __webpack_require__(9565);\nvar toIntegerOrInfinity = __webpack_require__(1291);\nvar getIteratorDirect = __webpack_require__(1767);\n\nvar INVALID_SIZE = \'Invalid size\';\nvar $RangeError = RangeError;\nvar $TypeError = TypeError;\nvar max = Math.max;\n\nvar SetRecord = function (set, intSize) {\n this.set = set;\n this.size = max(intSize, 0);\n this.has = aCallable(set.has);\n this.keys = aCallable(set.keys);\n};\n\nSetRecord.prototype = {\n getIterator: function () {\n return getIteratorDirect(anObject(call(this.keys, this.set)));\n },\n includes: function (it) {\n return call(this.has, this.set, it);\n }\n};\n\n// `GetSetRecord` abstract operation\n// https://tc39.es/proposal-set-methods/#sec-getsetrecord\nmodule.exports = function (obj) {\n anObject(obj);\n var numSize = +obj.size;\n // NOTE: If size is undefined, then numSize will be NaN\n // eslint-disable-next-line no-self-compare -- NaN check\n if (numSize !== numSize) throw new $TypeError(INVALID_SIZE);\n var intSize = toIntegerOrInfinity(numSize);\n if (intSize < 0) throw new $RangeError(INVALID_SIZE);\n return new SetRecord(obj, intSize);\n};\n\n\n/***/ },\n\n/***/ 4576\n(module) {\n\n\nvar check = function (it) {\n return it && it.Math === Math && it;\n};\n\n// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\nmodule.exports =\n // eslint-disable-next-line es/no-global-this -- safe\n check(typeof globalThis == \'object\' && globalThis) ||\n check(typeof window == \'object\' && window) ||\n // eslint-disable-next-line no-restricted-globals -- safe\n check(typeof self == \'object\' && self) ||\n check(typeof global == \'object\' && global) ||\n check(typeof this == \'object\' && this) ||\n // eslint-disable-next-line no-new-func -- fallback\n (function () { return this; })() || Function(\'return this\')();\n\n\n/***/ },\n\n/***/ 9297\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\nvar toObject = __webpack_require__(8981);\n\nvar hasOwnProperty = uncurryThis({}.hasOwnProperty);\n\n// `HasOwnProperty` abstract operation\n// https://tc39.es/ecma262/#sec-hasownproperty\n// eslint-disable-next-line es/no-object-hasown -- safe\nmodule.exports = Object.hasOwn || function hasOwn(it, key) {\n return hasOwnProperty(toObject(it), key);\n};\n\n\n/***/ },\n\n/***/ 421\n(module) {\n\n\nmodule.exports = {};\n\n\n/***/ },\n\n/***/ 397\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar getBuiltIn = __webpack_require__(7751);\n\nmodule.exports = getBuiltIn(\'document\', \'documentElement\');\n\n\n/***/ },\n\n/***/ 5917\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar fails = __webpack_require__(9039);\nvar createElement = __webpack_require__(4055);\n\n// Thanks to IE8 for its funny defineProperty\nmodule.exports = !DESCRIPTORS && !fails(function () {\n // eslint-disable-next-line es/no-object-defineproperty -- required for testing\n return Object.defineProperty(createElement(\'div\'), \'a\', {\n get: function () { return 7; }\n }).a !== 7;\n});\n\n\n/***/ },\n\n/***/ 7055\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\nvar fails = __webpack_require__(9039);\nvar classof = __webpack_require__(2195);\n\nvar $Object = Object;\nvar split = uncurryThis(\'\'.split);\n\n// fallback for non-array-like ES3 and non-enumerable old V8 strings\nmodule.exports = fails(function () {\n // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346\n // eslint-disable-next-line no-prototype-builtins -- safe\n return !$Object(\'z\').propertyIsEnumerable(0);\n}) ? function (it) {\n return classof(it) === \'String\' ? split(it, \'\') : $Object(it);\n} : $Object;\n\n\n/***/ },\n\n/***/ 3167\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isCallable = __webpack_require__(4901);\nvar isObject = __webpack_require__(34);\nvar setPrototypeOf = __webpack_require__(2967);\n\n// makes subclassing work correct for wrapped built-ins\nmodule.exports = function ($this, dummy, Wrapper) {\n var NewTarget, NewTargetPrototype;\n if (\n // it can work only with native `setPrototypeOf`\n setPrototypeOf &&\n // we haven\'t completely correct pre-ES6 way for getting `new.target`, so use this\n isCallable(NewTarget = dummy.constructor) &&\n NewTarget !== Wrapper &&\n isObject(NewTargetPrototype = NewTarget.prototype) &&\n NewTargetPrototype !== Wrapper.prototype\n ) setPrototypeOf($this, NewTargetPrototype);\n return $this;\n};\n\n\n/***/ },\n\n/***/ 3706\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\nvar isCallable = __webpack_require__(4901);\nvar store = __webpack_require__(7629);\n\nvar functionToString = uncurryThis(Function.toString);\n\n// this helper broken in `core-js@3.4.1-3.4.4`, so we can\'t use `shared` helper\nif (!isCallable(store.inspectSource)) {\n store.inspectSource = function (it) {\n return functionToString(it);\n };\n}\n\nmodule.exports = store.inspectSource;\n\n\n/***/ },\n\n/***/ 1181\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar NATIVE_WEAK_MAP = __webpack_require__(8622);\nvar globalThis = __webpack_require__(4576);\nvar isObject = __webpack_require__(34);\nvar createNonEnumerableProperty = __webpack_require__(6699);\nvar hasOwn = __webpack_require__(9297);\nvar shared = __webpack_require__(7629);\nvar sharedKey = __webpack_require__(6119);\nvar hiddenKeys = __webpack_require__(421);\n\nvar OBJECT_ALREADY_INITIALIZED = \'Object already initialized\';\nvar TypeError = globalThis.TypeError;\nvar WeakMap = globalThis.WeakMap;\nvar set, get, has;\n\nvar enforce = function (it) {\n return has(it) ? get(it) : set(it, {});\n};\n\nvar getterFor = function (TYPE) {\n return function (it) {\n var state;\n if (!isObject(it) || (state = get(it)).type !== TYPE) {\n throw new TypeError(\'Incompatible receiver, \' + TYPE + \' required\');\n } return state;\n };\n};\n\nif (NATIVE_WEAK_MAP || shared.state) {\n var store = shared.state || (shared.state = new WeakMap());\n /* eslint-disable no-self-assign -- prototype methods protection */\n store.get = store.get;\n store.has = store.has;\n store.set = store.set;\n /* eslint-enable no-self-assign -- prototype methods protection */\n set = function (it, metadata) {\n if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);\n metadata.facade = it;\n store.set(it, metadata);\n return metadata;\n };\n get = function (it) {\n return store.get(it) || {};\n };\n has = function (it) {\n return store.has(it);\n };\n} else {\n var STATE = sharedKey(\'state\');\n hiddenKeys[STATE] = true;\n set = function (it, metadata) {\n if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);\n metadata.facade = it;\n createNonEnumerableProperty(it, STATE, metadata);\n return metadata;\n };\n get = function (it) {\n return hasOwn(it, STATE) ? it[STATE] : {};\n };\n has = function (it) {\n return hasOwn(it, STATE);\n };\n}\n\nmodule.exports = {\n set: set,\n get: get,\n has: has,\n enforce: enforce,\n getterFor: getterFor\n};\n\n\n/***/ },\n\n/***/ 4209\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar wellKnownSymbol = __webpack_require__(8227);\nvar Iterators = __webpack_require__(6269);\n\nvar ITERATOR = wellKnownSymbol(\'iterator\');\nvar ArrayPrototype = Array.prototype;\n\n// check on default Array iterator\nmodule.exports = function (it) {\n return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);\n};\n\n\n/***/ },\n\n/***/ 4376\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar classof = __webpack_require__(2195);\n\n// `IsArray` abstract operation\n// https://tc39.es/ecma262/#sec-isarray\n// eslint-disable-next-line es/no-array-isarray -- safe\nmodule.exports = Array.isArray || function isArray(argument) {\n return classof(argument) === \'Array\';\n};\n\n\n/***/ },\n\n/***/ 1108\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar classof = __webpack_require__(6955);\n\nmodule.exports = function (it) {\n var klass = classof(it);\n return klass === \'BigInt64Array\' || klass === \'BigUint64Array\';\n};\n\n\n/***/ },\n\n/***/ 4901\n(module) {\n\n\n// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot\nvar documentAll = typeof document == \'object\' && document.all;\n\n// `IsCallable` abstract operation\n// https://tc39.es/ecma262/#sec-iscallable\n// eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing\nmodule.exports = typeof documentAll == \'undefined\' && documentAll !== undefined ? function (argument) {\n return typeof argument == \'function\' || argument === documentAll;\n} : function (argument) {\n return typeof argument == \'function\';\n};\n\n\n/***/ },\n\n/***/ 2796\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar fails = __webpack_require__(9039);\nvar isCallable = __webpack_require__(4901);\n\nvar replacement = /#|\\.prototype\\./;\n\nvar isForced = function (feature, detection) {\n var value = data[normalize(feature)];\n return value === POLYFILL ? true\n : value === NATIVE ? false\n : isCallable(detection) ? fails(detection)\n : !!detection;\n};\n\nvar normalize = isForced.normalize = function (string) {\n return String(string).replace(replacement, \'.\').toLowerCase();\n};\n\nvar data = isForced.data = {};\nvar NATIVE = isForced.NATIVE = \'N\';\nvar POLYFILL = isForced.POLYFILL = \'P\';\n\nmodule.exports = isForced;\n\n\n/***/ },\n\n/***/ 4117\n(module) {\n\n\n// we can\'t use just `it == null` since of `document.all` special case\n// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec\nmodule.exports = function (it) {\n return it === null || it === undefined;\n};\n\n\n/***/ },\n\n/***/ 34\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isCallable = __webpack_require__(4901);\n\nmodule.exports = function (it) {\n return typeof it == \'object\' ? it !== null : isCallable(it);\n};\n\n\n/***/ },\n\n/***/ 3925\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isObject = __webpack_require__(34);\n\nmodule.exports = function (argument) {\n return isObject(argument) || argument === null;\n};\n\n\n/***/ },\n\n/***/ 6395\n(module) {\n\n\nmodule.exports = false;\n\n\n/***/ },\n\n/***/ 5810\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isObject = __webpack_require__(34);\nvar getInternalState = (__webpack_require__(1181).get);\n\nmodule.exports = function isRawJSON(O) {\n if (!isObject(O)) return false;\n var state = getInternalState(O);\n return !!state && state.type === \'RawJSON\';\n};\n\n\n/***/ },\n\n/***/ 757\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar getBuiltIn = __webpack_require__(7751);\nvar isCallable = __webpack_require__(4901);\nvar isPrototypeOf = __webpack_require__(1625);\nvar USE_SYMBOL_AS_UID = __webpack_require__(7040);\n\nvar $Object = Object;\n\nmodule.exports = USE_SYMBOL_AS_UID ? function (it) {\n return typeof it == \'symbol\';\n} : function (it) {\n var $Symbol = getBuiltIn(\'Symbol\');\n return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));\n};\n\n\n/***/ },\n\n/***/ 507\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar call = __webpack_require__(9565);\n\nmodule.exports = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) {\n var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator;\n var next = record.next;\n var step, result;\n while (!(step = call(next, iterator)).done) {\n result = fn(step.value);\n if (result !== undefined) return result;\n }\n};\n\n\n/***/ },\n\n/***/ 2652\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar bind = __webpack_require__(6080);\nvar call = __webpack_require__(9565);\nvar anObject = __webpack_require__(8551);\nvar tryToString = __webpack_require__(6823);\nvar isArrayIteratorMethod = __webpack_require__(4209);\nvar lengthOfArrayLike = __webpack_require__(6198);\nvar isPrototypeOf = __webpack_require__(1625);\nvar getIterator = __webpack_require__(81);\nvar getIteratorMethod = __webpack_require__(851);\nvar iteratorClose = __webpack_require__(9539);\n\nvar $TypeError = TypeError;\n\nvar Result = function (stopped, result) {\n this.stopped = stopped;\n this.result = result;\n};\n\nvar ResultPrototype = Result.prototype;\n\nmodule.exports = function (iterable, unboundFunction, options) {\n var that = options && options.that;\n var AS_ENTRIES = !!(options && options.AS_ENTRIES);\n var IS_RECORD = !!(options && options.IS_RECORD);\n var IS_ITERATOR = !!(options && options.IS_ITERATOR);\n var INTERRUPTED = !!(options && options.INTERRUPTED);\n var fn = bind(unboundFunction, that);\n var iterator, iterFn, index, length, result, next, step;\n\n var stop = function (condition) {\n if (iterator) iteratorClose(iterator, \'normal\');\n return new Result(true, condition);\n };\n\n var callFn = function (value) {\n if (AS_ENTRIES) {\n anObject(value);\n return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);\n } return INTERRUPTED ? fn(value, stop) : fn(value);\n };\n\n if (IS_RECORD) {\n iterator = iterable.iterator;\n } else if (IS_ITERATOR) {\n iterator = iterable;\n } else {\n iterFn = getIteratorMethod(iterable);\n if (!iterFn) throw new $TypeError(tryToString(iterable) + \' is not iterable\');\n // optimisation for array iterators\n if (isArrayIteratorMethod(iterFn)) {\n for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {\n result = callFn(iterable[index]);\n if (result && isPrototypeOf(ResultPrototype, result)) return result;\n } return new Result(false);\n }\n iterator = getIterator(iterable, iterFn);\n }\n\n next = IS_RECORD ? iterable.next : iterator.next;\n while (!(step = call(next, iterator)).done) {\n try {\n result = callFn(step.value);\n } catch (error) {\n iteratorClose(iterator, \'throw\', error);\n }\n if (typeof result == \'object\' && result && isPrototypeOf(ResultPrototype, result)) return result;\n } return new Result(false);\n};\n\n\n/***/ },\n\n/***/ 1385\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar iteratorClose = __webpack_require__(9539);\n\nmodule.exports = function (iters, kind, value) {\n for (var i = iters.length - 1; i >= 0; i--) {\n if (iters[i] === undefined) continue;\n try {\n value = iteratorClose(iters[i].iterator, kind, value);\n } catch (error) {\n kind = \'throw\';\n value = error;\n }\n }\n if (kind === \'throw\') throw value;\n return value;\n};\n\n\n/***/ },\n\n/***/ 9539\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar call = __webpack_require__(9565);\nvar anObject = __webpack_require__(8551);\nvar getMethod = __webpack_require__(5966);\n\nmodule.exports = function (iterator, kind, value) {\n var innerResult, innerError;\n anObject(iterator);\n try {\n innerResult = getMethod(iterator, \'return\');\n if (!innerResult) {\n if (kind === \'throw\') throw value;\n return value;\n }\n innerResult = call(innerResult, iterator);\n } catch (error) {\n innerError = true;\n innerResult = error;\n }\n if (kind === \'throw\') throw value;\n if (innerError) throw innerResult;\n anObject(innerResult);\n return value;\n};\n\n\n/***/ },\n\n/***/ 9462\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar call = __webpack_require__(9565);\nvar create = __webpack_require__(2360);\nvar createNonEnumerableProperty = __webpack_require__(6699);\nvar defineBuiltIns = __webpack_require__(6279);\nvar wellKnownSymbol = __webpack_require__(8227);\nvar InternalStateModule = __webpack_require__(1181);\nvar getMethod = __webpack_require__(5966);\nvar IteratorPrototype = (__webpack_require__(7657).IteratorPrototype);\nvar createIterResultObject = __webpack_require__(2529);\nvar iteratorClose = __webpack_require__(9539);\nvar iteratorCloseAll = __webpack_require__(1385);\n\nvar TO_STRING_TAG = wellKnownSymbol(\'toStringTag\');\nvar ITERATOR_HELPER = \'IteratorHelper\';\nvar WRAP_FOR_VALID_ITERATOR = \'WrapForValidIterator\';\nvar NORMAL = \'normal\';\nvar THROW = \'throw\';\nvar setInternalState = InternalStateModule.set;\n\nvar createIteratorProxyPrototype = function (IS_ITERATOR) {\n var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER);\n\n return defineBuiltIns(create(IteratorPrototype), {\n next: function next() {\n var state = getInternalState(this);\n // for simplification:\n // for `%WrapForValidIteratorPrototype%.next` or with `state.returnHandlerResult` our `nextHandler` returns `IterResultObject`\n // for `%IteratorHelperPrototype%.next` - just a value\n if (IS_ITERATOR) return state.nextHandler();\n if (state.done) return createIterResultObject(undefined, true);\n try {\n var result = state.nextHandler();\n return state.returnHandlerResult ? result : createIterResultObject(result, state.done);\n } catch (error) {\n state.done = true;\n throw error;\n }\n },\n \'return\': function () {\n var state = getInternalState(this);\n var iterator = state.iterator;\n state.done = true;\n if (IS_ITERATOR) {\n var returnMethod = getMethod(iterator, \'return\');\n return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true);\n }\n if (state.inner) try {\n iteratorClose(state.inner.iterator, NORMAL);\n } catch (error) {\n return iteratorClose(iterator, THROW, error);\n }\n if (state.openIters) try {\n iteratorCloseAll(state.openIters, NORMAL);\n } catch (error) {\n return iteratorClose(iterator, THROW, error);\n }\n if (iterator) iteratorClose(iterator, NORMAL);\n return createIterResultObject(undefined, true);\n }\n });\n};\n\nvar WrapForValidIteratorPrototype = createIteratorProxyPrototype(true);\nvar IteratorHelperPrototype = createIteratorProxyPrototype(false);\n\ncreateNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, \'Iterator Helper\');\n\nmodule.exports = function (nextHandler, IS_ITERATOR, RETURN_HANDLER_RESULT) {\n var IteratorProxy = function Iterator(record, state) {\n if (state) {\n state.iterator = record.iterator;\n state.next = record.next;\n } else state = record;\n state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER;\n state.returnHandlerResult = !!RETURN_HANDLER_RESULT;\n state.nextHandler = nextHandler;\n state.counter = 0;\n state.done = false;\n setInternalState(this, state);\n };\n\n IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype;\n\n return IteratorProxy;\n};\n\n\n/***/ },\n\n/***/ 684\n(module) {\n\n\n// Should throw an error on invalid iterator\n// https://issues.chromium.org/issues/336839115\nmodule.exports = function (methodName, argument) {\n // eslint-disable-next-line es/no-iterator -- required for testing\n var method = typeof Iterator == \'function\' && Iterator.prototype[methodName];\n if (method) try {\n method.call({ next: null }, argument).next();\n } catch (error) {\n return true;\n }\n};\n\n\n/***/ },\n\n/***/ 4549\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\n\n// https://github.com/tc39/ecma262/pull/3467\nmodule.exports = function (METHOD_NAME, ExpectedError) {\n var Iterator = globalThis.Iterator;\n var IteratorPrototype = Iterator && Iterator.prototype;\n var method = IteratorPrototype && IteratorPrototype[METHOD_NAME];\n\n var CLOSED = false;\n\n if (method) try {\n method.call({\n next: function () { return { done: true }; },\n \'return\': function () { CLOSED = true; }\n }, -1);\n } catch (error) {\n // https://bugs.webkit.org/show_bug.cgi?id=291195\n if (!(error instanceof ExpectedError)) CLOSED = false;\n }\n\n if (!CLOSED) return method;\n};\n\n\n/***/ },\n\n/***/ 7657\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar fails = __webpack_require__(9039);\nvar isCallable = __webpack_require__(4901);\nvar isObject = __webpack_require__(34);\nvar create = __webpack_require__(2360);\nvar getPrototypeOf = __webpack_require__(2787);\nvar defineBuiltIn = __webpack_require__(6840);\nvar wellKnownSymbol = __webpack_require__(8227);\nvar IS_PURE = __webpack_require__(6395);\n\nvar ITERATOR = wellKnownSymbol(\'iterator\');\nvar BUGGY_SAFARI_ITERATORS = false;\n\n// `%IteratorPrototype%` object\n// https://tc39.es/ecma262/#sec-%iteratorprototype%-object\nvar IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;\n\n/* eslint-disable es/no-array-prototype-keys -- safe */\nif ([].keys) {\n arrayIterator = [].keys();\n // Safari 8 has buggy iterators w/o `next`\n if (!(\'next\' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;\n else {\n PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));\n if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;\n }\n}\n\nvar NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {\n var test = {};\n // FF44- legacy iterators case\n return IteratorPrototype[ITERATOR].call(test) !== test;\n});\n\nif (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};\nelse if (IS_PURE) IteratorPrototype = create(IteratorPrototype);\n\n// `%IteratorPrototype%[@@iterator]()` method\n// https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator\nif (!isCallable(IteratorPrototype[ITERATOR])) {\n defineBuiltIn(IteratorPrototype, ITERATOR, function () {\n return this;\n });\n}\n\nmodule.exports = {\n IteratorPrototype: IteratorPrototype,\n BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS\n};\n\n\n/***/ },\n\n/***/ 6269\n(module) {\n\n\nmodule.exports = {};\n\n\n/***/ },\n\n/***/ 6198\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar toLength = __webpack_require__(8014);\n\n// `LengthOfArrayLike` abstract operation\n// https://tc39.es/ecma262/#sec-lengthofarraylike\nmodule.exports = function (obj) {\n return toLength(obj.length);\n};\n\n\n/***/ },\n\n/***/ 283\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\nvar fails = __webpack_require__(9039);\nvar isCallable = __webpack_require__(4901);\nvar hasOwn = __webpack_require__(9297);\nvar DESCRIPTORS = __webpack_require__(3724);\nvar CONFIGURABLE_FUNCTION_NAME = (__webpack_require__(350).CONFIGURABLE);\nvar inspectSource = __webpack_require__(3706);\nvar InternalStateModule = __webpack_require__(1181);\n\nvar enforceInternalState = InternalStateModule.enforce;\nvar getInternalState = InternalStateModule.get;\nvar $String = String;\n// eslint-disable-next-line es/no-object-defineproperty -- safe\nvar defineProperty = Object.defineProperty;\nvar stringSlice = uncurryThis(\'\'.slice);\nvar replace = uncurryThis(\'\'.replace);\nvar join = uncurryThis([].join);\n\nvar CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {\n return defineProperty(function () { /* empty */ }, \'length\', { value: 8 }).length !== 8;\n});\n\nvar TEMPLATE = String(String).split(\'String\');\n\nvar makeBuiltIn = module.exports = function (value, name, options) {\n if (stringSlice($String(name), 0, 7) === \'Symbol(\') {\n name = \'[\' + replace($String(name), /^Symbol\\(([^)]*)\\).*$/, \'$1\') + \']\';\n }\n if (options && options.getter) name = \'get \' + name;\n if (options && options.setter) name = \'set \' + name;\n if (!hasOwn(value, \'name\') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {\n if (DESCRIPTORS) defineProperty(value, \'name\', { value: name, configurable: true });\n else value.name = name;\n }\n if (CONFIGURABLE_LENGTH && options && hasOwn(options, \'arity\') && value.length !== options.arity) {\n defineProperty(value, \'length\', { value: options.arity });\n }\n try {\n if (options && hasOwn(options, \'constructor\') && options.constructor) {\n if (DESCRIPTORS) defineProperty(value, \'prototype\', { writable: false });\n // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable\n } else if (value.prototype) value.prototype = undefined;\n } catch (error) { /* empty */ }\n var state = enforceInternalState(value);\n if (!hasOwn(state, \'source\')) {\n state.source = join(TEMPLATE, typeof name == \'string\' ? name : \'\');\n } return value;\n};\n\n// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n// eslint-disable-next-line no-extend-native -- required\nFunction.prototype.toString = makeBuiltIn(function toString() {\n return isCallable(this) && getInternalState(this).source || inspectSource(this);\n}, \'toString\');\n\n\n/***/ },\n\n/***/ 2248\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\n\n// eslint-disable-next-line es/no-map -- safe\nvar MapPrototype = Map.prototype;\n\nmodule.exports = {\n // eslint-disable-next-line es/no-map -- safe\n Map: Map,\n set: uncurryThis(MapPrototype.set),\n get: uncurryThis(MapPrototype.get),\n has: uncurryThis(MapPrototype.has),\n remove: uncurryThis(MapPrototype[\'delete\']),\n proto: MapPrototype\n};\n\n\n/***/ },\n\n/***/ 741\n(module) {\n\n\nvar ceil = Math.ceil;\nvar floor = Math.floor;\n\n// `Math.trunc` method\n// https://tc39.es/ecma262/#sec-math.trunc\n// eslint-disable-next-line es/no-math-trunc -- safe\nmodule.exports = Math.trunc || function trunc(x) {\n var n = +x;\n return (n > 0 ? floor : ceil)(n);\n};\n\n\n/***/ },\n\n/***/ 7819\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\n/* eslint-disable es/no-json -- safe */\nvar fails = __webpack_require__(9039);\n\nmodule.exports = !fails(function () {\n var unsafeInt = \'9007199254740993\';\n // eslint-disable-next-line es/no-json-rawjson -- feature detection\n var raw = JSON.rawJSON(unsafeInt);\n // eslint-disable-next-line es/no-json-israwjson -- feature detection\n return !JSON.isRawJSON(raw) || JSON.stringify(raw) !== unsafeInt;\n});\n\n\n/***/ },\n\n/***/ 6043\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar aCallable = __webpack_require__(9306);\n\nvar $TypeError = TypeError;\n\nvar PromiseCapability = function (C) {\n var resolve, reject;\n this.promise = new C(function ($$resolve, $$reject) {\n if (resolve !== undefined || reject !== undefined) throw new $TypeError(\'Bad Promise constructor\');\n resolve = $$resolve;\n reject = $$reject;\n });\n this.resolve = aCallable(resolve);\n this.reject = aCallable(reject);\n};\n\n// `NewPromiseCapability` abstract operation\n// https://tc39.es/ecma262/#sec-newpromisecapability\nmodule.exports.f = function (C) {\n return new PromiseCapability(C);\n};\n\n\n/***/ },\n\n/***/ 2603\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar toString = __webpack_require__(655);\n\nmodule.exports = function (argument, $default) {\n return argument === undefined ? arguments.length < 2 ? \'\' : $default : toString(argument);\n};\n\n\n/***/ },\n\n/***/ 4149\n(module) {\n\n\nvar $RangeError = RangeError;\n\nmodule.exports = function (it) {\n // eslint-disable-next-line no-self-compare -- NaN check\n if (it === it) return it;\n throw new $RangeError(\'NaN is not allowed\');\n};\n\n\n/***/ },\n\n/***/ 2360\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\n/* global ActiveXObject -- old IE, WSH */\nvar anObject = __webpack_require__(8551);\nvar definePropertiesModule = __webpack_require__(6801);\nvar enumBugKeys = __webpack_require__(8727);\nvar hiddenKeys = __webpack_require__(421);\nvar html = __webpack_require__(397);\nvar documentCreateElement = __webpack_require__(4055);\nvar sharedKey = __webpack_require__(6119);\n\nvar GT = \'>\';\nvar LT = \'<\';\nvar PROTOTYPE = \'prototype\';\nvar SCRIPT = \'script\';\nvar IE_PROTO = sharedKey(\'IE_PROTO\');\n\nvar EmptyConstructor = function () { /* empty */ };\n\nvar scriptTag = function (content) {\n return LT + SCRIPT + GT + content + LT + \'/\' + SCRIPT + GT;\n};\n\n// Create object with fake `null` prototype: use ActiveX Object with cleared prototype\nvar NullProtoObjectViaActiveX = function (activeXDocument) {\n activeXDocument.write(scriptTag(\'\'));\n activeXDocument.close();\n var temp = activeXDocument.parentWindow.Object;\n // eslint-disable-next-line no-useless-assignment -- avoid memory leak\n activeXDocument = null;\n return temp;\n};\n\n// Create object with fake `null` prototype: use iframe Object with cleared prototype\nvar NullProtoObjectViaIFrame = function () {\n // Thrash, waste and sodomy: IE GC bug\n var iframe = documentCreateElement(\'iframe\');\n var JS = \'java\' + SCRIPT + \':\';\n var iframeDocument;\n iframe.style.display = \'none\';\n html.appendChild(iframe);\n // https://github.com/zloirock/core-js/issues/475\n iframe.src = String(JS);\n iframeDocument = iframe.contentWindow.document;\n iframeDocument.open();\n iframeDocument.write(scriptTag(\'document.F=Object\'));\n iframeDocument.close();\n return iframeDocument.F;\n};\n\n// Check for document.domain and active x support\n// No need to use active x approach when document.domain is not set\n// see https://github.com/es-shims/es5-shim/issues/150\n// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346\n// avoid IE GC bug\nvar activeXDocument;\nvar NullProtoObject = function () {\n try {\n activeXDocument = new ActiveXObject(\'htmlfile\');\n } catch (error) { /* ignore */ }\n NullProtoObject = typeof document != \'undefined\'\n ? document.domain && activeXDocument\n ? NullProtoObjectViaActiveX(activeXDocument) // old IE\n : NullProtoObjectViaIFrame()\n : NullProtoObjectViaActiveX(activeXDocument); // WSH\n var length = enumBugKeys.length;\n while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];\n return NullProtoObject();\n};\n\nhiddenKeys[IE_PROTO] = true;\n\n// `Object.create` method\n// https://tc39.es/ecma262/#sec-object.create\n// eslint-disable-next-line es/no-object-create -- safe\nmodule.exports = Object.create || function create(O, Properties) {\n var result;\n if (O !== null) {\n EmptyConstructor[PROTOTYPE] = anObject(O);\n result = new EmptyConstructor();\n EmptyConstructor[PROTOTYPE] = null;\n // add "__proto__" for Object.getPrototypeOf polyfill\n result[IE_PROTO] = O;\n } else result = NullProtoObject();\n return Properties === undefined ? result : definePropertiesModule.f(result, Properties);\n};\n\n\n/***/ },\n\n/***/ 6801\n(__unused_webpack_module, exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(8686);\nvar definePropertyModule = __webpack_require__(4913);\nvar anObject = __webpack_require__(8551);\nvar toIndexedObject = __webpack_require__(5397);\nvar objectKeys = __webpack_require__(1072);\n\n// `Object.defineProperties` method\n// https://tc39.es/ecma262/#sec-object.defineproperties\n// eslint-disable-next-line es/no-object-defineproperties -- safe\nexports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {\n anObject(O);\n var props = toIndexedObject(Properties);\n var keys = objectKeys(Properties);\n var length = keys.length;\n var index = 0;\n var key;\n while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);\n return O;\n};\n\n\n/***/ },\n\n/***/ 4913\n(__unused_webpack_module, exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar IE8_DOM_DEFINE = __webpack_require__(5917);\nvar V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(8686);\nvar anObject = __webpack_require__(8551);\nvar toPropertyKey = __webpack_require__(6969);\n\nvar $TypeError = TypeError;\n// eslint-disable-next-line es/no-object-defineproperty -- safe\nvar $defineProperty = Object.defineProperty;\n// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\nvar $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar ENUMERABLE = \'enumerable\';\nvar CONFIGURABLE = \'configurable\';\nvar WRITABLE = \'writable\';\n\n// `Object.defineProperty` method\n// https://tc39.es/ecma262/#sec-object.defineproperty\nexports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {\n anObject(O);\n P = toPropertyKey(P);\n anObject(Attributes);\n if (typeof O === \'function\' && P === \'prototype\' && \'value\' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {\n var current = $getOwnPropertyDescriptor(O, P);\n if (current && current[WRITABLE]) {\n O[P] = Attributes.value;\n Attributes = {\n configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],\n enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],\n writable: false\n };\n }\n } return $defineProperty(O, P, Attributes);\n} : $defineProperty : function defineProperty(O, P, Attributes) {\n anObject(O);\n P = toPropertyKey(P);\n anObject(Attributes);\n if (IE8_DOM_DEFINE) try {\n return $defineProperty(O, P, Attributes);\n } catch (error) { /* empty */ }\n if (\'get\' in Attributes || \'set\' in Attributes) throw new $TypeError(\'Accessors not supported\');\n if (\'value\' in Attributes) O[P] = Attributes.value;\n return O;\n};\n\n\n/***/ },\n\n/***/ 7347\n(__unused_webpack_module, exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar call = __webpack_require__(9565);\nvar propertyIsEnumerableModule = __webpack_require__(8773);\nvar createPropertyDescriptor = __webpack_require__(6980);\nvar toIndexedObject = __webpack_require__(5397);\nvar toPropertyKey = __webpack_require__(6969);\nvar hasOwn = __webpack_require__(9297);\nvar IE8_DOM_DEFINE = __webpack_require__(5917);\n\n// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\nvar $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\n// `Object.getOwnPropertyDescriptor` method\n// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor\nexports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {\n O = toIndexedObject(O);\n P = toPropertyKey(P);\n if (IE8_DOM_DEFINE) try {\n return $getOwnPropertyDescriptor(O, P);\n } catch (error) { /* empty */ }\n if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);\n};\n\n\n/***/ },\n\n/***/ 8480\n(__unused_webpack_module, exports, __webpack_require__) {\n\n\nvar internalObjectKeys = __webpack_require__(1828);\nvar enumBugKeys = __webpack_require__(8727);\n\nvar hiddenKeys = enumBugKeys.concat(\'length\', \'prototype\');\n\n// `Object.getOwnPropertyNames` method\n// https://tc39.es/ecma262/#sec-object.getownpropertynames\n// eslint-disable-next-line es/no-object-getownpropertynames -- safe\nexports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {\n return internalObjectKeys(O, hiddenKeys);\n};\n\n\n/***/ },\n\n/***/ 3717\n(__unused_webpack_module, exports) {\n\n\n// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe\nexports.f = Object.getOwnPropertySymbols;\n\n\n/***/ },\n\n/***/ 2787\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar hasOwn = __webpack_require__(9297);\nvar isCallable = __webpack_require__(4901);\nvar toObject = __webpack_require__(8981);\nvar sharedKey = __webpack_require__(6119);\nvar CORRECT_PROTOTYPE_GETTER = __webpack_require__(2211);\n\nvar IE_PROTO = sharedKey(\'IE_PROTO\');\nvar $Object = Object;\nvar ObjectPrototype = $Object.prototype;\n\n// `Object.getPrototypeOf` method\n// https://tc39.es/ecma262/#sec-object.getprototypeof\n// eslint-disable-next-line es/no-object-getprototypeof -- safe\nmodule.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {\n var object = toObject(O);\n if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];\n var constructor = object.constructor;\n if (isCallable(constructor) && object instanceof constructor) {\n return constructor.prototype;\n } return object instanceof $Object ? ObjectPrototype : null;\n};\n\n\n/***/ },\n\n/***/ 1625\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\n\nmodule.exports = uncurryThis({}.isPrototypeOf);\n\n\n/***/ },\n\n/***/ 1828\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\nvar hasOwn = __webpack_require__(9297);\nvar toIndexedObject = __webpack_require__(5397);\nvar indexOf = (__webpack_require__(9617).indexOf);\nvar hiddenKeys = __webpack_require__(421);\n\nvar push = uncurryThis([].push);\n\nmodule.exports = function (object, names) {\n var O = toIndexedObject(object);\n var i = 0;\n var result = [];\n var key;\n for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);\n // Don\'t enum bug & hidden keys\n while (names.length > i) if (hasOwn(O, key = names[i++])) {\n ~indexOf(result, key) || push(result, key);\n }\n return result;\n};\n\n\n/***/ },\n\n/***/ 1072\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar internalObjectKeys = __webpack_require__(1828);\nvar enumBugKeys = __webpack_require__(8727);\n\n// `Object.keys` method\n// https://tc39.es/ecma262/#sec-object.keys\n// eslint-disable-next-line es/no-object-keys -- safe\nmodule.exports = Object.keys || function keys(O) {\n return internalObjectKeys(O, enumBugKeys);\n};\n\n\n/***/ },\n\n/***/ 8773\n(__unused_webpack_module, exports) {\n\n\nvar $propertyIsEnumerable = {}.propertyIsEnumerable;\n// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\n// Nashorn ~ JDK8 bug\nvar NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);\n\n// `Object.prototype.propertyIsEnumerable` method implementation\n// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable\nexports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {\n var descriptor = getOwnPropertyDescriptor(this, V);\n return !!descriptor && descriptor.enumerable;\n} : $propertyIsEnumerable;\n\n\n/***/ },\n\n/***/ 2967\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\n/* eslint-disable no-proto -- safe */\nvar uncurryThisAccessor = __webpack_require__(6706);\nvar isObject = __webpack_require__(34);\nvar requireObjectCoercible = __webpack_require__(7750);\nvar aPossiblePrototype = __webpack_require__(3506);\n\n// `Object.setPrototypeOf` method\n// https://tc39.es/ecma262/#sec-object.setprototypeof\n// Works with __proto__ only. Old v8 can\'t work with null proto objects.\n// eslint-disable-next-line es/no-object-setprototypeof -- safe\nmodule.exports = Object.setPrototypeOf || (\'__proto__\' in {} ? function () {\n var CORRECT_SETTER = false;\n var test = {};\n var setter;\n try {\n setter = uncurryThisAccessor(Object.prototype, \'__proto__\', \'set\');\n setter(test, []);\n CORRECT_SETTER = test instanceof Array;\n } catch (error) { /* empty */ }\n return function setPrototypeOf(O, proto) {\n requireObjectCoercible(O);\n aPossiblePrototype(proto);\n if (!isObject(O)) return O;\n if (CORRECT_SETTER) setter(O, proto);\n else O.__proto__ = proto;\n return O;\n };\n}() : undefined);\n\n\n/***/ },\n\n/***/ 4270\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar call = __webpack_require__(9565);\nvar isCallable = __webpack_require__(4901);\nvar isObject = __webpack_require__(34);\n\nvar $TypeError = TypeError;\n\n// `OrdinaryToPrimitive` abstract operation\n// https://tc39.es/ecma262/#sec-ordinarytoprimitive\nmodule.exports = function (input, pref) {\n var fn, val;\n if (pref === \'string\' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;\n if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;\n if (pref !== \'string\' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;\n throw new $TypeError("Can\'t convert object to primitive value");\n};\n\n\n/***/ },\n\n/***/ 5031\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar getBuiltIn = __webpack_require__(7751);\nvar uncurryThis = __webpack_require__(9504);\nvar getOwnPropertyNamesModule = __webpack_require__(8480);\nvar getOwnPropertySymbolsModule = __webpack_require__(3717);\nvar anObject = __webpack_require__(8551);\n\nvar concat = uncurryThis([].concat);\n\n// all object keys, includes non-enumerable and symbols\nmodule.exports = getBuiltIn(\'Reflect\', \'ownKeys\') || function ownKeys(it) {\n var keys = getOwnPropertyNamesModule.f(anObject(it));\n var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;\n return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;\n};\n\n\n/***/ },\n\n/***/ 8235\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\nvar hasOwn = __webpack_require__(9297);\n\nvar $SyntaxError = SyntaxError;\nvar $parseInt = parseInt;\nvar fromCharCode = String.fromCharCode;\nvar at = uncurryThis(\'\'.charAt);\nvar slice = uncurryThis(\'\'.slice);\nvar exec = uncurryThis(/./.exec);\n\nvar codePoints = {\n \'\\\\"\': \'"\',\n \'\\\\\\\\\': \'\\\\\',\n \'\\\\/\': \'/\',\n \'\\\\b\': \'\\b\',\n \'\\\\f\': \'\\f\',\n \'\\\\n\': \'\\n\',\n \'\\\\r\': \'\\r\',\n \'\\\\t\': \'\\t\'\n};\n\nvar IS_4_HEX_DIGITS = /^[\\da-f]{4}$/i;\n// eslint-disable-next-line regexp/no-control-character -- safe\nvar IS_C0_CONTROL_CODE = /^[\\u0000-\\u001F]$/;\n\nmodule.exports = function (source, i) {\n var unterminated = true;\n var value = \'\';\n while (i < source.length) {\n var chr = at(source, i);\n if (chr === \'\\\\\') {\n var twoChars = slice(source, i, i + 2);\n if (hasOwn(codePoints, twoChars)) {\n value += codePoints[twoChars];\n i += 2;\n } else if (twoChars === \'\\\\u\') {\n i += 2;\n var fourHexDigits = slice(source, i, i + 4);\n if (!exec(IS_4_HEX_DIGITS, fourHexDigits)) throw new $SyntaxError(\'Bad Unicode escape at: \' + i);\n value += fromCharCode($parseInt(fourHexDigits, 16));\n i += 4;\n } else throw new $SyntaxError(\'Unknown escape sequence: "\' + twoChars + \'"\');\n } else if (chr === \'"\') {\n unterminated = false;\n i++;\n break;\n } else {\n if (exec(IS_C0_CONTROL_CODE, chr)) throw new $SyntaxError(\'Bad control character in string literal at: \' + i);\n value += chr;\n i++;\n }\n }\n if (unterminated) throw new $SyntaxError(\'Unterminated string at: \' + i);\n return { value: value, end: i };\n};\n\n\n/***/ },\n\n/***/ 1103\n(module) {\n\n\nmodule.exports = function (exec) {\n try {\n return { error: false, value: exec() };\n } catch (error) {\n return { error: true, value: error };\n }\n};\n\n\n/***/ },\n\n/***/ 7750\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar isNullOrUndefined = __webpack_require__(4117);\n\nvar $TypeError = TypeError;\n\n// `RequireObjectCoercible` abstract operation\n// https://tc39.es/ecma262/#sec-requireobjectcoercible\nmodule.exports = function (it) {\n if (isNullOrUndefined(it)) throw new $TypeError("Can\'t call method on " + it);\n return it;\n};\n\n\n/***/ },\n\n/***/ 9286\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar SetHelpers = __webpack_require__(4402);\nvar iterate = __webpack_require__(8469);\n\nvar Set = SetHelpers.Set;\nvar add = SetHelpers.add;\n\nmodule.exports = function (set) {\n var result = new Set();\n iterate(set, function (it) {\n add(result, it);\n });\n return result;\n};\n\n\n/***/ },\n\n/***/ 3440\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar aSet = __webpack_require__(7080);\nvar SetHelpers = __webpack_require__(4402);\nvar clone = __webpack_require__(9286);\nvar size = __webpack_require__(5170);\nvar getSetRecord = __webpack_require__(3789);\nvar iterateSet = __webpack_require__(8469);\nvar iterateSimple = __webpack_require__(507);\n\nvar has = SetHelpers.has;\nvar remove = SetHelpers.remove;\n\n// `Set.prototype.difference` method\n// https://tc39.es/ecma262/#sec-set.prototype.difference\nmodule.exports = function difference(other) {\n var O = aSet(this);\n var otherRec = getSetRecord(other);\n var result = clone(O);\n if (size(O) <= otherRec.size) iterateSet(O, function (e) {\n if (otherRec.includes(e)) remove(result, e);\n });\n else iterateSimple(otherRec.getIterator(), function (e) {\n if (has(result, e)) remove(result, e);\n });\n return result;\n};\n\n\n/***/ },\n\n/***/ 4402\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\n\n// eslint-disable-next-line es/no-set -- safe\nvar SetPrototype = Set.prototype;\n\nmodule.exports = {\n // eslint-disable-next-line es/no-set -- safe\n Set: Set,\n add: uncurryThis(SetPrototype.add),\n has: uncurryThis(SetPrototype.has),\n remove: uncurryThis(SetPrototype[\'delete\']),\n proto: SetPrototype\n};\n\n\n/***/ },\n\n/***/ 8750\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar aSet = __webpack_require__(7080);\nvar SetHelpers = __webpack_require__(4402);\nvar size = __webpack_require__(5170);\nvar getSetRecord = __webpack_require__(3789);\nvar iterateSet = __webpack_require__(8469);\nvar iterateSimple = __webpack_require__(507);\n\nvar Set = SetHelpers.Set;\nvar add = SetHelpers.add;\nvar has = SetHelpers.has;\n\n// `Set.prototype.intersection` method\n// https://tc39.es/ecma262/#sec-set.prototype.intersection\nmodule.exports = function intersection(other) {\n var O = aSet(this);\n var otherRec = getSetRecord(other);\n var result = new Set();\n\n if (size(O) > otherRec.size) {\n iterateSimple(otherRec.getIterator(), function (e) {\n if (has(O, e)) add(result, e);\n });\n } else {\n iterateSet(O, function (e) {\n if (otherRec.includes(e)) add(result, e);\n });\n }\n\n return result;\n};\n\n\n/***/ },\n\n/***/ 4449\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar aSet = __webpack_require__(7080);\nvar has = (__webpack_require__(4402).has);\nvar size = __webpack_require__(5170);\nvar getSetRecord = __webpack_require__(3789);\nvar iterateSet = __webpack_require__(8469);\nvar iterateSimple = __webpack_require__(507);\nvar iteratorClose = __webpack_require__(9539);\n\n// `Set.prototype.isDisjointFrom` method\n// https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom\nmodule.exports = function isDisjointFrom(other) {\n var O = aSet(this);\n var otherRec = getSetRecord(other);\n if (size(O) <= otherRec.size) return iterateSet(O, function (e) {\n if (otherRec.includes(e)) return false;\n }, true) !== false;\n var iterator = otherRec.getIterator();\n return iterateSimple(iterator, function (e) {\n if (has(O, e)) return iteratorClose(iterator, \'normal\', false);\n }) !== false;\n};\n\n\n/***/ },\n\n/***/ 3838\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar aSet = __webpack_require__(7080);\nvar size = __webpack_require__(5170);\nvar iterate = __webpack_require__(8469);\nvar getSetRecord = __webpack_require__(3789);\n\n// `Set.prototype.isSubsetOf` method\n// https://tc39.es/ecma262/#sec-set.prototype.issubsetof\nmodule.exports = function isSubsetOf(other) {\n var O = aSet(this);\n var otherRec = getSetRecord(other);\n if (size(O) > otherRec.size) return false;\n return iterate(O, function (e) {\n if (!otherRec.includes(e)) return false;\n }, true) !== false;\n};\n\n\n/***/ },\n\n/***/ 8527\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar aSet = __webpack_require__(7080);\nvar has = (__webpack_require__(4402).has);\nvar size = __webpack_require__(5170);\nvar getSetRecord = __webpack_require__(3789);\nvar iterateSimple = __webpack_require__(507);\nvar iteratorClose = __webpack_require__(9539);\n\n// `Set.prototype.isSupersetOf` method\n// https://tc39.es/ecma262/#sec-set.prototype.issupersetof\nmodule.exports = function isSupersetOf(other) {\n var O = aSet(this);\n var otherRec = getSetRecord(other);\n if (size(O) < otherRec.size) return false;\n var iterator = otherRec.getIterator();\n return iterateSimple(iterator, function (e) {\n if (!has(O, e)) return iteratorClose(iterator, \'normal\', false);\n }) !== false;\n};\n\n\n/***/ },\n\n/***/ 8469\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\nvar iterateSimple = __webpack_require__(507);\nvar SetHelpers = __webpack_require__(4402);\n\nvar Set = SetHelpers.Set;\nvar SetPrototype = SetHelpers.proto;\nvar forEach = uncurryThis(SetPrototype.forEach);\nvar keys = uncurryThis(SetPrototype.keys);\nvar next = keys(new Set()).next;\n\nmodule.exports = function (set, fn, interruptible) {\n return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn);\n};\n\n\n/***/ },\n\n/***/ 4916\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar getBuiltIn = __webpack_require__(7751);\n\nvar createSetLike = function (size) {\n return {\n size: size,\n has: function () {\n return false;\n },\n keys: function () {\n return {\n next: function () {\n return { done: true };\n }\n };\n }\n };\n};\n\nvar createSetLikeWithInfinitySize = function (size) {\n return {\n size: size,\n has: function () {\n return true;\n },\n keys: function () {\n throw new Error(\'e\');\n }\n };\n};\n\nmodule.exports = function (name, callback) {\n var Set = getBuiltIn(\'Set\');\n try {\n new Set()[name](createSetLike(0));\n try {\n // late spec change, early WebKit ~ Safari 17 implementation does not pass it\n // https://github.com/tc39/proposal-set-methods/pull/88\n // also covered engines with\n // https://bugs.webkit.org/show_bug.cgi?id=272679\n new Set()[name](createSetLike(-1));\n return false;\n } catch (error2) {\n if (!callback) return true;\n // early V8 implementation bug\n // https://issues.chromium.org/issues/351332634\n try {\n new Set()[name](createSetLikeWithInfinitySize(-Infinity));\n return false;\n } catch (error) {\n var set = new Set([1, 2]);\n return callback(set[name](createSetLikeWithInfinitySize(Infinity)));\n }\n }\n } catch (error) {\n return false;\n }\n};\n\n\n/***/ },\n\n/***/ 9835\n(module) {\n\n\n// Should get iterator record of a set-like object before cloning this\n// https://bugs.webkit.org/show_bug.cgi?id=289430\nmodule.exports = function (METHOD_NAME) {\n try {\n // eslint-disable-next-line es/no-set -- needed for test\n var baseSet = new Set();\n var setLike = {\n size: 0,\n has: function () { return true; },\n keys: function () {\n // eslint-disable-next-line es/no-object-defineproperty -- needed for test\n return Object.defineProperty({}, \'next\', {\n get: function () {\n baseSet.clear();\n baseSet.add(4);\n return function () {\n return { done: true };\n };\n }\n });\n }\n };\n var result = baseSet[METHOD_NAME](setLike);\n\n return result.size === 1 && result.values().next().value === 4;\n } catch (error) {\n return false;\n }\n};\n\n\n/***/ },\n\n/***/ 5170\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThisAccessor = __webpack_require__(6706);\nvar SetHelpers = __webpack_require__(4402);\n\nmodule.exports = uncurryThisAccessor(SetHelpers.proto, \'size\', \'get\') || function (set) {\n return set.size;\n};\n\n\n/***/ },\n\n/***/ 3650\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar aSet = __webpack_require__(7080);\nvar SetHelpers = __webpack_require__(4402);\nvar clone = __webpack_require__(9286);\nvar getSetRecord = __webpack_require__(3789);\nvar iterateSimple = __webpack_require__(507);\n\nvar add = SetHelpers.add;\nvar has = SetHelpers.has;\nvar remove = SetHelpers.remove;\n\n// `Set.prototype.symmetricDifference` method\n// https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference\nmodule.exports = function symmetricDifference(other) {\n var O = aSet(this);\n var keysIter = getSetRecord(other).getIterator();\n var result = clone(O);\n iterateSimple(keysIter, function (e) {\n if (has(O, e)) remove(result, e);\n else add(result, e);\n });\n return result;\n};\n\n\n/***/ },\n\n/***/ 4204\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar aSet = __webpack_require__(7080);\nvar add = (__webpack_require__(4402).add);\nvar clone = __webpack_require__(9286);\nvar getSetRecord = __webpack_require__(3789);\nvar iterateSimple = __webpack_require__(507);\n\n// `Set.prototype.union` method\n// https://tc39.es/ecma262/#sec-set.prototype.union\nmodule.exports = function union(other) {\n var O = aSet(this);\n var keysIter = getSetRecord(other).getIterator();\n var result = clone(O);\n iterateSimple(keysIter, function (it) {\n add(result, it);\n });\n return result;\n};\n\n\n/***/ },\n\n/***/ 6119\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar shared = __webpack_require__(5745);\nvar uid = __webpack_require__(3392);\n\nvar keys = shared(\'keys\');\n\nmodule.exports = function (key) {\n return keys[key] || (keys[key] = uid(key));\n};\n\n\n/***/ },\n\n/***/ 7629\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar IS_PURE = __webpack_require__(6395);\nvar globalThis = __webpack_require__(4576);\nvar defineGlobalProperty = __webpack_require__(9433);\n\nvar SHARED = \'__core-js_shared__\';\nvar store = module.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});\n\n(store.versions || (store.versions = [])).push({\n version: \'3.48.0\',\n mode: IS_PURE ? \'pure\' : \'global\',\n copyright: \'© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.\',\n license: \'https://github.com/zloirock/core-js/blob/v3.48.0/LICENSE\',\n source: \'https://github.com/zloirock/core-js\'\n});\n\n\n/***/ },\n\n/***/ 5745\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar store = __webpack_require__(7629);\n\nmodule.exports = function (key, value) {\n return store[key] || (store[key] = value || {});\n};\n\n\n/***/ },\n\n/***/ 1548\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar fails = __webpack_require__(9039);\nvar V8 = __webpack_require__(9519);\nvar ENVIRONMENT = __webpack_require__(4215);\n\nvar structuredClone = globalThis.structuredClone;\n\nmodule.exports = !!structuredClone && !fails(function () {\n // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation\n // https://github.com/zloirock/core-js/issues/679\n if ((ENVIRONMENT === \'DENO\' && V8 > 92) || (ENVIRONMENT === \'NODE\' && V8 > 94) || (ENVIRONMENT === \'BROWSER\' && V8 > 97)) return false;\n var buffer = new ArrayBuffer(8);\n var clone = structuredClone(buffer, { transfer: [buffer] });\n return buffer.byteLength !== 0 || clone.byteLength !== 8;\n});\n\n\n/***/ },\n\n/***/ 4495\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\n/* eslint-disable es/no-symbol -- required for testing */\nvar V8_VERSION = __webpack_require__(9519);\nvar fails = __webpack_require__(9039);\nvar globalThis = __webpack_require__(4576);\n\nvar $String = globalThis.String;\n\n// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing\nmodule.exports = !!Object.getOwnPropertySymbols && !fails(function () {\n var symbol = Symbol(\'symbol detection\');\n // Chrome 38 Symbol has incorrect toString conversion\n // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances\n // nb: Do not call `String` directly to avoid this being optimized out to `symbol+\'\'` which will,\n // of course, fail.\n return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||\n // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances\n !Symbol.sham && V8_VERSION && V8_VERSION < 41;\n});\n\n\n/***/ },\n\n/***/ 5610\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar toIntegerOrInfinity = __webpack_require__(1291);\n\nvar max = Math.max;\nvar min = Math.min;\n\n// Helper for a popular repeating case of the spec:\n// Let integer be ? ToInteger(index).\n// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).\nmodule.exports = function (index, length) {\n var integer = toIntegerOrInfinity(index);\n return integer < 0 ? max(integer + length, 0) : min(integer, length);\n};\n\n\n/***/ },\n\n/***/ 5854\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar toPrimitive = __webpack_require__(2777);\n\nvar $TypeError = TypeError;\n\n// `ToBigInt` abstract operation\n// https://tc39.es/ecma262/#sec-tobigint\nmodule.exports = function (argument) {\n var prim = toPrimitive(argument, \'number\');\n if (typeof prim == \'number\') throw new $TypeError("Can\'t convert number to bigint");\n // eslint-disable-next-line es/no-bigint -- safe\n return BigInt(prim);\n};\n\n\n/***/ },\n\n/***/ 7696\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar toIntegerOrInfinity = __webpack_require__(1291);\nvar toLength = __webpack_require__(8014);\n\nvar $RangeError = RangeError;\n\n// `ToIndex` abstract operation\n// https://tc39.es/ecma262/#sec-toindex\nmodule.exports = function (it) {\n if (it === undefined) return 0;\n var number = toIntegerOrInfinity(it);\n var length = toLength(number);\n if (number !== length) throw new $RangeError(\'Wrong length or index\');\n return length;\n};\n\n\n/***/ },\n\n/***/ 5397\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\n// toObject with fallback for non-array-like ES3 strings\nvar IndexedObject = __webpack_require__(7055);\nvar requireObjectCoercible = __webpack_require__(7750);\n\nmodule.exports = function (it) {\n return IndexedObject(requireObjectCoercible(it));\n};\n\n\n/***/ },\n\n/***/ 1291\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar trunc = __webpack_require__(741);\n\n// `ToIntegerOrInfinity` abstract operation\n// https://tc39.es/ecma262/#sec-tointegerorinfinity\nmodule.exports = function (argument) {\n var number = +argument;\n // eslint-disable-next-line no-self-compare -- NaN check\n return number !== number || number === 0 ? 0 : trunc(number);\n};\n\n\n/***/ },\n\n/***/ 8014\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar toIntegerOrInfinity = __webpack_require__(1291);\n\nvar min = Math.min;\n\n// `ToLength` abstract operation\n// https://tc39.es/ecma262/#sec-tolength\nmodule.exports = function (argument) {\n var len = toIntegerOrInfinity(argument);\n return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991\n};\n\n\n/***/ },\n\n/***/ 8981\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar requireObjectCoercible = __webpack_require__(7750);\n\nvar $Object = Object;\n\n// `ToObject` abstract operation\n// https://tc39.es/ecma262/#sec-toobject\nmodule.exports = function (argument) {\n return $Object(requireObjectCoercible(argument));\n};\n\n\n/***/ },\n\n/***/ 9590\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar toIntegerOrInfinity = __webpack_require__(1291);\n\nvar $RangeError = RangeError;\n\nmodule.exports = function (it) {\n var result = toIntegerOrInfinity(it);\n if (result < 0) throw new $RangeError("The argument can\'t be less than 0");\n return result;\n};\n\n\n/***/ },\n\n/***/ 2777\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar call = __webpack_require__(9565);\nvar isObject = __webpack_require__(34);\nvar isSymbol = __webpack_require__(757);\nvar getMethod = __webpack_require__(5966);\nvar ordinaryToPrimitive = __webpack_require__(4270);\nvar wellKnownSymbol = __webpack_require__(8227);\n\nvar $TypeError = TypeError;\nvar TO_PRIMITIVE = wellKnownSymbol(\'toPrimitive\');\n\n// `ToPrimitive` abstract operation\n// https://tc39.es/ecma262/#sec-toprimitive\nmodule.exports = function (input, pref) {\n if (!isObject(input) || isSymbol(input)) return input;\n var exoticToPrim = getMethod(input, TO_PRIMITIVE);\n var result;\n if (exoticToPrim) {\n if (pref === undefined) pref = \'default\';\n result = call(exoticToPrim, input, pref);\n if (!isObject(result) || isSymbol(result)) return result;\n throw new $TypeError("Can\'t convert object to primitive value");\n }\n if (pref === undefined) pref = \'number\';\n return ordinaryToPrimitive(input, pref);\n};\n\n\n/***/ },\n\n/***/ 6969\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar toPrimitive = __webpack_require__(2777);\nvar isSymbol = __webpack_require__(757);\n\n// `ToPropertyKey` abstract operation\n// https://tc39.es/ecma262/#sec-topropertykey\nmodule.exports = function (argument) {\n var key = toPrimitive(argument, \'string\');\n return isSymbol(key) ? key : key + \'\';\n};\n\n\n/***/ },\n\n/***/ 2140\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar wellKnownSymbol = __webpack_require__(8227);\n\nvar TO_STRING_TAG = wellKnownSymbol(\'toStringTag\');\nvar test = {};\n// eslint-disable-next-line unicorn/no-immediate-mutation -- ES3 syntax limitation\ntest[TO_STRING_TAG] = \'z\';\n\nmodule.exports = String(test) === \'[object z]\';\n\n\n/***/ },\n\n/***/ 655\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar classof = __webpack_require__(6955);\n\nvar $String = String;\n\nmodule.exports = function (argument) {\n if (classof(argument) === \'Symbol\') throw new TypeError(\'Cannot convert a Symbol value to a string\');\n return $String(argument);\n};\n\n\n/***/ },\n\n/***/ 6823\n(module) {\n\n\nvar $String = String;\n\nmodule.exports = function (argument) {\n try {\n return $String(argument);\n } catch (error) {\n return \'Object\';\n }\n};\n\n\n/***/ },\n\n/***/ 3392\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\n\nvar id = 0;\nvar postfix = Math.random();\nvar toString = uncurryThis(1.1.toString);\n\nmodule.exports = function (key) {\n return \'Symbol(\' + (key === undefined ? \'\' : key) + \')_\' + toString(++id + postfix, 36);\n};\n\n\n/***/ },\n\n/***/ 9143\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar uncurryThis = __webpack_require__(9504);\nvar anObjectOrUndefined = __webpack_require__(3972);\nvar aString = __webpack_require__(3463);\nvar hasOwn = __webpack_require__(9297);\nvar base64Map = __webpack_require__(2804);\nvar getAlphabetOption = __webpack_require__(944);\nvar notDetached = __webpack_require__(5169);\n\nvar base64Alphabet = base64Map.c2i;\nvar base64UrlAlphabet = base64Map.c2iUrl;\n\nvar SyntaxError = globalThis.SyntaxError;\nvar TypeError = globalThis.TypeError;\nvar at = uncurryThis(\'\'.charAt);\n\nvar skipAsciiWhitespace = function (string, index) {\n var length = string.length;\n for (;index < length; index++) {\n var chr = at(string, index);\n if (chr !== \' \' && chr !== \'\\t\' && chr !== \'\\n\' && chr !== \'\\f\' && chr !== \'\\r\') break;\n } return index;\n};\n\nvar decodeBase64Chunk = function (chunk, alphabet, throwOnExtraBits) {\n var chunkLength = chunk.length;\n\n if (chunkLength < 4) {\n chunk += chunkLength === 2 ? \'AA\' : \'A\';\n }\n\n var triplet = (alphabet[at(chunk, 0)] << 18)\n + (alphabet[at(chunk, 1)] << 12)\n + (alphabet[at(chunk, 2)] << 6)\n + alphabet[at(chunk, 3)];\n\n var chunkBytes = [\n (triplet >> 16) & 255,\n (triplet >> 8) & 255,\n triplet & 255\n ];\n\n if (chunkLength === 2) {\n if (throwOnExtraBits && chunkBytes[1] !== 0) {\n throw new SyntaxError(\'Extra bits\');\n }\n return [chunkBytes[0]];\n }\n\n if (chunkLength === 3) {\n if (throwOnExtraBits && chunkBytes[2] !== 0) {\n throw new SyntaxError(\'Extra bits\');\n }\n return [chunkBytes[0], chunkBytes[1]];\n }\n\n return chunkBytes;\n};\n\nvar writeBytes = function (bytes, elements, written) {\n var elementsLength = elements.length;\n for (var index = 0; index < elementsLength; index++) {\n bytes[written + index] = elements[index];\n }\n return written + elementsLength;\n};\n\n/* eslint-disable max-statements, max-depth -- TODO */\nmodule.exports = function (string, options, into, maxLength) {\n aString(string);\n anObjectOrUndefined(options);\n var alphabet = getAlphabetOption(options) === \'base64\' ? base64Alphabet : base64UrlAlphabet;\n var lastChunkHandling = options ? options.lastChunkHandling : undefined;\n\n if (lastChunkHandling === undefined) lastChunkHandling = \'loose\';\n\n if (lastChunkHandling !== \'loose\' && lastChunkHandling !== \'strict\' && lastChunkHandling !== \'stop-before-partial\') {\n throw new TypeError(\'Incorrect `lastChunkHandling` option\');\n }\n\n if (into) notDetached(into.buffer);\n\n var stringLength = string.length;\n var bytes = into || [];\n var written = 0;\n var read = 0;\n var chunk = \'\';\n var index = 0;\n\n if (maxLength) while (true) {\n index = skipAsciiWhitespace(string, index);\n if (index === stringLength) {\n if (chunk.length > 0) {\n if (lastChunkHandling === \'stop-before-partial\') {\n break;\n }\n if (lastChunkHandling === \'loose\') {\n if (chunk.length === 1) {\n throw new SyntaxError(\'Malformed padding: exactly one additional character\');\n }\n written = writeBytes(bytes, decodeBase64Chunk(chunk, alphabet, false), written);\n } else {\n throw new SyntaxError(\'Missing padding\');\n }\n }\n read = stringLength;\n break;\n }\n var chr = at(string, index);\n ++index;\n if (chr === \'=\') {\n if (chunk.length < 2) {\n throw new SyntaxError(\'Padding is too early\');\n }\n index = skipAsciiWhitespace(string, index);\n if (chunk.length === 2) {\n if (index === stringLength) {\n if (lastChunkHandling === \'stop-before-partial\') {\n break;\n }\n throw new SyntaxError(\'Malformed padding: only one =\');\n }\n if (at(string, index) === \'=\') {\n ++index;\n index = skipAsciiWhitespace(string, index);\n }\n }\n if (index < stringLength) {\n throw new SyntaxError(\'Unexpected character after padding\');\n }\n written = writeBytes(bytes, decodeBase64Chunk(chunk, alphabet, lastChunkHandling === \'strict\'), written);\n read = stringLength;\n break;\n }\n if (!hasOwn(alphabet, chr)) {\n throw new SyntaxError(\'Unexpected character\');\n }\n var remainingBytes = maxLength - written;\n if (remainingBytes === 1 && chunk.length === 2 || remainingBytes === 2 && chunk.length === 3) {\n // special case: we can fit exactly the number of bytes currently represented by chunk, so we were just checking for `=`\n break;\n }\n\n chunk += chr;\n if (chunk.length === 4) {\n written = writeBytes(bytes, decodeBase64Chunk(chunk, alphabet, false), written);\n chunk = \'\';\n read = index;\n if (written === maxLength) {\n break;\n }\n }\n }\n\n return { bytes: bytes, read: read, written: written };\n};\n\n\n/***/ },\n\n/***/ 2303\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar uncurryThis = __webpack_require__(9504);\n\nvar Uint8Array = globalThis.Uint8Array;\nvar SyntaxError = globalThis.SyntaxError;\nvar parseInt = globalThis.parseInt;\nvar min = Math.min;\nvar NOT_HEX = /[^\\da-f]/i;\nvar exec = uncurryThis(NOT_HEX.exec);\nvar stringSlice = uncurryThis(\'\'.slice);\n\nmodule.exports = function (string, into) {\n var stringLength = string.length;\n if (stringLength % 2 !== 0) throw new SyntaxError(\'String should be an even number of characters\');\n var maxLength = into ? min(into.length, stringLength / 2) : stringLength / 2;\n var bytes = into || new Uint8Array(maxLength);\n var read = 0;\n var written = 0;\n while (written < maxLength) {\n var hexits = stringSlice(string, read, read += 2);\n if (exec(NOT_HEX, hexits)) throw new SyntaxError(\'String should only contain hex characters\');\n bytes[written++] = parseInt(hexits, 16);\n }\n return { bytes: bytes, read: read };\n};\n\n\n/***/ },\n\n/***/ 7416\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar fails = __webpack_require__(9039);\nvar wellKnownSymbol = __webpack_require__(8227);\nvar DESCRIPTORS = __webpack_require__(3724);\nvar IS_PURE = __webpack_require__(6395);\n\nvar ITERATOR = wellKnownSymbol(\'iterator\');\n\nmodule.exports = !fails(function () {\n // eslint-disable-next-line unicorn/relative-url-style -- required for testing\n var url = new URL(\'b?a=1&b=2&c=3\', \'https://a\');\n var params = url.searchParams;\n var params2 = new URLSearchParams(\'a=1&a=2&b=3\');\n var result = \'\';\n url.pathname = \'c%20d\';\n params.forEach(function (value, key) {\n params[\'delete\'](\'b\');\n result += key + value;\n });\n params2[\'delete\'](\'a\', 2);\n // `undefined` case is a Chromium 117 bug\n // https://bugs.chromium.org/p/v8/issues/detail?id=14222\n params2[\'delete\'](\'b\', undefined);\n return (IS_PURE && (!url.toJSON || !params2.has(\'a\', 1) || params2.has(\'a\', 2) || !params2.has(\'a\', undefined) || params2.has(\'b\')))\n || (!params.size && (IS_PURE || !DESCRIPTORS))\n || !params.sort\n || url.href !== \'https://a/c%20d?a=1&c=3\'\n || params.get(\'c\') !== \'3\'\n || String(new URLSearchParams(\'?a=1\')) !== \'a=1\'\n || !params[ITERATOR]\n // throws in Edge\n || new URL(\'https://a@b\').username !== \'a\'\n || new URLSearchParams(new URLSearchParams(\'a=b\')).get(\'a\') !== \'b\'\n // not punycoded in Edge\n || new URL(\'https://тест\').host !== \'xn--e1aybc\'\n // not escaped in Chrome 62-\n || new URL(\'https://a#б\').hash !== \'#%D0%B1\'\n // fails in Chrome 66-\n || result !== \'a1c3\'\n // throws in Safari\n || new URL(\'https://x\', undefined).host !== \'x\';\n});\n\n\n/***/ },\n\n/***/ 7040\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\n/* eslint-disable es/no-symbol -- required for testing */\nvar NATIVE_SYMBOL = __webpack_require__(4495);\n\nmodule.exports = NATIVE_SYMBOL &&\n !Symbol.sham &&\n typeof Symbol.iterator == \'symbol\';\n\n\n/***/ },\n\n/***/ 8686\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar fails = __webpack_require__(9039);\n\n// V8 ~ Chrome 36-\n// https://bugs.chromium.org/p/v8/issues/detail?id=3334\nmodule.exports = DESCRIPTORS && fails(function () {\n // eslint-disable-next-line es/no-object-defineproperty -- required for testing\n return Object.defineProperty(function () { /* empty */ }, \'prototype\', {\n value: 42,\n writable: false\n }).prototype !== 42;\n});\n\n\n/***/ },\n\n/***/ 2812\n(module) {\n\n\nvar $TypeError = TypeError;\n\nmodule.exports = function (passed, required) {\n if (passed < required) throw new $TypeError(\'Not enough arguments\');\n return passed;\n};\n\n\n/***/ },\n\n/***/ 8622\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar isCallable = __webpack_require__(4901);\n\nvar WeakMap = globalThis.WeakMap;\n\nmodule.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap));\n\n\n/***/ },\n\n/***/ 4995\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar uncurryThis = __webpack_require__(9504);\n\n// eslint-disable-next-line es/no-weak-map -- safe\nvar WeakMapPrototype = WeakMap.prototype;\n\nmodule.exports = {\n // eslint-disable-next-line es/no-weak-map -- safe\n WeakMap: WeakMap,\n set: uncurryThis(WeakMapPrototype.set),\n get: uncurryThis(WeakMapPrototype.get),\n has: uncurryThis(WeakMapPrototype.has),\n remove: uncurryThis(WeakMapPrototype[\'delete\'])\n};\n\n\n/***/ },\n\n/***/ 8227\n(module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar globalThis = __webpack_require__(4576);\nvar shared = __webpack_require__(5745);\nvar hasOwn = __webpack_require__(9297);\nvar uid = __webpack_require__(3392);\nvar NATIVE_SYMBOL = __webpack_require__(4495);\nvar USE_SYMBOL_AS_UID = __webpack_require__(7040);\n\nvar Symbol = globalThis.Symbol;\nvar WellKnownSymbolsStore = shared(\'wks\');\nvar createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol[\'for\'] || Symbol : Symbol && Symbol.withoutSetter || uid;\n\nmodule.exports = function (name) {\n if (!hasOwn(WellKnownSymbolsStore, name)) {\n WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)\n ? Symbol[name]\n : createWellKnownSymbol(\'Symbol.\' + name);\n } return WellKnownSymbolsStore[name];\n};\n\n\n/***/ },\n\n/***/ 6573\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar defineBuiltInAccessor = __webpack_require__(2106);\nvar isDetached = __webpack_require__(3238);\n\nvar ArrayBufferPrototype = ArrayBuffer.prototype;\n\n// `ArrayBuffer.prototype.detached` getter\n// https://tc39.es/ecma262/#sec-get-arraybuffer.prototype.detached\nif (DESCRIPTORS && !(\'detached\' in ArrayBufferPrototype)) {\n defineBuiltInAccessor(ArrayBufferPrototype, \'detached\', {\n configurable: true,\n get: function detached() {\n return isDetached(this);\n }\n });\n}\n\n\n/***/ },\n\n/***/ 7936\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar $transfer = __webpack_require__(5636);\n\n// `ArrayBuffer.prototype.transferToFixedLength` method\n// https://tc39.es/ecma262/#sec-arraybuffer.prototype.transfertofixedlength\nif ($transfer) $({ target: \'ArrayBuffer\', proto: true }, {\n transferToFixedLength: function transferToFixedLength() {\n return $transfer(this, arguments.length ? arguments[0] : undefined, false);\n }\n});\n\n\n/***/ },\n\n/***/ 8100\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar $transfer = __webpack_require__(5636);\n\n// `ArrayBuffer.prototype.transfer` method\n// https://tc39.es/ecma262/#sec-arraybuffer.prototype.transfer\nif ($transfer) $({ target: \'ArrayBuffer\', proto: true }, {\n transfer: function transfer() {\n return $transfer(this, arguments.length ? arguments[0] : undefined, true);\n }\n});\n\n\n/***/ },\n\n/***/ 4114\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar toObject = __webpack_require__(8981);\nvar lengthOfArrayLike = __webpack_require__(6198);\nvar setArrayLength = __webpack_require__(4527);\nvar doesNotExceedSafeInteger = __webpack_require__(6837);\nvar fails = __webpack_require__(9039);\n\nvar INCORRECT_TO_LENGTH = fails(function () {\n return [].push.call({ length: 0x100000000 }, 1) !== 4294967297;\n});\n\n// V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError\n// https://bugs.chromium.org/p/v8/issues/detail?id=12681\nvar properErrorOnNonWritableLength = function () {\n try {\n // eslint-disable-next-line es/no-object-defineproperty -- safe\n Object.defineProperty([], \'length\', { writable: false }).push();\n } catch (error) {\n return error instanceof TypeError;\n }\n};\n\nvar FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength();\n\n// `Array.prototype.push` method\n// https://tc39.es/ecma262/#sec-array.prototype.push\n$({ target: \'Array\', proto: true, arity: 1, forced: FORCED }, {\n // eslint-disable-next-line no-unused-vars -- required for `.length`\n push: function push(item) {\n var O = toObject(this);\n var len = lengthOfArrayLike(O);\n var argCount = arguments.length;\n doesNotExceedSafeInteger(len + argCount);\n for (var i = 0; i < argCount; i++) {\n O[len] = arguments[i];\n len++;\n }\n setArrayLength(O, len);\n return len;\n }\n});\n\n\n/***/ },\n\n/***/ 8111\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar globalThis = __webpack_require__(4576);\nvar anInstance = __webpack_require__(679);\nvar anObject = __webpack_require__(8551);\nvar isCallable = __webpack_require__(4901);\nvar getPrototypeOf = __webpack_require__(2787);\nvar defineBuiltInAccessor = __webpack_require__(2106);\nvar createProperty = __webpack_require__(4659);\nvar fails = __webpack_require__(9039);\nvar hasOwn = __webpack_require__(9297);\nvar wellKnownSymbol = __webpack_require__(8227);\nvar IteratorPrototype = (__webpack_require__(7657).IteratorPrototype);\nvar DESCRIPTORS = __webpack_require__(3724);\nvar IS_PURE = __webpack_require__(6395);\n\nvar CONSTRUCTOR = \'constructor\';\nvar ITERATOR = \'Iterator\';\nvar TO_STRING_TAG = wellKnownSymbol(\'toStringTag\');\n\nvar $TypeError = TypeError;\nvar NativeIterator = globalThis[ITERATOR];\n\n// FF56- have non-standard global helper `Iterator`\nvar FORCED = IS_PURE\n || !isCallable(NativeIterator)\n || NativeIterator.prototype !== IteratorPrototype\n // FF44- non-standard `Iterator` passes previous tests\n || !fails(function () { NativeIterator({}); });\n\nvar IteratorConstructor = function Iterator() {\n anInstance(this, IteratorPrototype);\n if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError(\'Abstract class Iterator not directly constructable\');\n};\n\nvar defineIteratorPrototypeAccessor = function (key, value) {\n if (DESCRIPTORS) {\n defineBuiltInAccessor(IteratorPrototype, key, {\n configurable: true,\n get: function () {\n return value;\n },\n set: function (replacement) {\n anObject(this);\n if (this === IteratorPrototype) throw new $TypeError("You can\'t redefine this property");\n if (hasOwn(this, key)) this[key] = replacement;\n else createProperty(this, key, replacement);\n }\n });\n } else IteratorPrototype[key] = value;\n};\n\nif (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR);\n\nif (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) {\n defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor);\n}\n\nIteratorConstructor.prototype = IteratorPrototype;\n\n// `Iterator` constructor\n// https://tc39.es/ecma262/#sec-iterator\n$({ global: true, constructor: true, forced: FORCED }, {\n Iterator: IteratorConstructor\n});\n\n\n/***/ },\n\n/***/ 9314\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar call = __webpack_require__(9565);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar notANaN = __webpack_require__(4149);\nvar toPositiveInteger = __webpack_require__(9590);\nvar iteratorClose = __webpack_require__(9539);\nvar createIteratorProxy = __webpack_require__(9462);\nvar iteratorHelperThrowsOnInvalidIterator = __webpack_require__(684);\nvar iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);\nvar IS_PURE = __webpack_require__(6395);\n\nvar DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator(\'drop\', 0);\nvar dropWithoutClosingOnEarlyError = !IS_PURE && !DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR\n && iteratorHelperWithoutClosingOnEarlyError(\'drop\', RangeError);\n\nvar FORCED = IS_PURE || DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR || dropWithoutClosingOnEarlyError;\n\nvar IteratorProxy = createIteratorProxy(function () {\n var iterator = this.iterator;\n var next = this.next;\n var result, done;\n while (this.remaining) {\n this.remaining--;\n result = anObject(call(next, iterator));\n done = this.done = !!result.done;\n if (done) return;\n }\n result = anObject(call(next, iterator));\n done = this.done = !!result.done;\n if (!done) return result.value;\n});\n\n// `Iterator.prototype.drop` method\n// https://tc39.es/ecma262/#sec-iterator.prototype.drop\n$({ target: \'Iterator\', proto: true, real: true, forced: FORCED }, {\n drop: function drop(limit) {\n anObject(this);\n var remaining;\n try {\n remaining = toPositiveInteger(notANaN(+limit));\n } catch (error) {\n iteratorClose(this, \'throw\', error);\n }\n\n if (dropWithoutClosingOnEarlyError) return call(dropWithoutClosingOnEarlyError, this, remaining);\n\n return new IteratorProxy(getIteratorDirect(this), {\n remaining: remaining\n });\n }\n});\n\n\n/***/ },\n\n/***/ 1148\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar call = __webpack_require__(9565);\nvar iterate = __webpack_require__(2652);\nvar aCallable = __webpack_require__(9306);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar iteratorClose = __webpack_require__(9539);\nvar iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);\n\nvar everyWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError(\'every\', TypeError);\n\n// `Iterator.prototype.every` method\n// https://tc39.es/ecma262/#sec-iterator.prototype.every\n$({ target: \'Iterator\', proto: true, real: true, forced: everyWithoutClosingOnEarlyError }, {\n every: function every(predicate) {\n anObject(this);\n try {\n aCallable(predicate);\n } catch (error) {\n iteratorClose(this, \'throw\', error);\n }\n\n if (everyWithoutClosingOnEarlyError) return call(everyWithoutClosingOnEarlyError, this, predicate);\n\n var record = getIteratorDirect(this);\n var counter = 0;\n return !iterate(record, function (value, stop) {\n if (!predicate(value, counter++)) return stop();\n }, { IS_RECORD: true, INTERRUPTED: true }).stopped;\n }\n});\n\n\n/***/ },\n\n/***/ 2489\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar call = __webpack_require__(9565);\nvar aCallable = __webpack_require__(9306);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar createIteratorProxy = __webpack_require__(9462);\nvar callWithSafeIterationClosing = __webpack_require__(6319);\nvar IS_PURE = __webpack_require__(6395);\nvar iteratorClose = __webpack_require__(9539);\nvar iteratorHelperThrowsOnInvalidIterator = __webpack_require__(684);\nvar iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);\n\nvar FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator(\'filter\', function () { /* empty */ });\nvar filterWithoutClosingOnEarlyError = !IS_PURE && !FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR\n && iteratorHelperWithoutClosingOnEarlyError(\'filter\', TypeError);\n\nvar FORCED = IS_PURE || FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR || filterWithoutClosingOnEarlyError;\n\nvar IteratorProxy = createIteratorProxy(function () {\n var iterator = this.iterator;\n var predicate = this.predicate;\n var next = this.next;\n var result, done, value;\n while (true) {\n result = anObject(call(next, iterator));\n done = this.done = !!result.done;\n if (done) return;\n value = result.value;\n if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value;\n }\n});\n\n// `Iterator.prototype.filter` method\n// https://tc39.es/ecma262/#sec-iterator.prototype.filter\n$({ target: \'Iterator\', proto: true, real: true, forced: FORCED }, {\n filter: function filter(predicate) {\n anObject(this);\n try {\n aCallable(predicate);\n } catch (error) {\n iteratorClose(this, \'throw\', error);\n }\n\n if (filterWithoutClosingOnEarlyError) return call(filterWithoutClosingOnEarlyError, this, predicate);\n\n return new IteratorProxy(getIteratorDirect(this), {\n predicate: predicate\n });\n }\n});\n\n\n/***/ },\n\n/***/ 116\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar call = __webpack_require__(9565);\nvar iterate = __webpack_require__(2652);\nvar aCallable = __webpack_require__(9306);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar iteratorClose = __webpack_require__(9539);\nvar iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);\n\nvar findWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError(\'find\', TypeError);\n\n// `Iterator.prototype.find` method\n// https://tc39.es/ecma262/#sec-iterator.prototype.find\n$({ target: \'Iterator\', proto: true, real: true, forced: findWithoutClosingOnEarlyError }, {\n find: function find(predicate) {\n anObject(this);\n try {\n aCallable(predicate);\n } catch (error) {\n iteratorClose(this, \'throw\', error);\n }\n\n if (findWithoutClosingOnEarlyError) return call(findWithoutClosingOnEarlyError, this, predicate);\n\n var record = getIteratorDirect(this);\n var counter = 0;\n return iterate(record, function (value, stop) {\n if (predicate(value, counter++)) return stop(value);\n }, { IS_RECORD: true, INTERRUPTED: true }).result;\n }\n});\n\n\n/***/ },\n\n/***/ 531\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar call = __webpack_require__(9565);\nvar aCallable = __webpack_require__(9306);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar getIteratorFlattenable = __webpack_require__(8646);\nvar createIteratorProxy = __webpack_require__(9462);\nvar iteratorClose = __webpack_require__(9539);\nvar IS_PURE = __webpack_require__(6395);\nvar iteratorHelperThrowsOnInvalidIterator = __webpack_require__(684);\nvar iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);\n\n// Should not throw an error for an iterator without `return` method. Fixed in Safari 26.2\n// https://bugs.webkit.org/show_bug.cgi?id=297532\nfunction throwsOnIteratorWithoutReturn() {\n try {\n // eslint-disable-next-line es/no-map, es/no-iterator, es/no-iterator-prototype-flatmap -- required for testing\n var it = Iterator.prototype.flatMap.call(new Map([[4, 5]]).entries(), function (v) { return v; });\n it.next();\n it[\'return\']();\n } catch (error) {\n return true;\n }\n}\n\nvar FLAT_MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE\n && !iteratorHelperThrowsOnInvalidIterator(\'flatMap\', function () { /* empty */ });\nvar flatMapWithoutClosingOnEarlyError = !IS_PURE && !FLAT_MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR\n && iteratorHelperWithoutClosingOnEarlyError(\'flatMap\', TypeError);\n\nvar FORCED = IS_PURE || FLAT_MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR || flatMapWithoutClosingOnEarlyError\n || throwsOnIteratorWithoutReturn();\n\nvar IteratorProxy = createIteratorProxy(function () {\n var iterator = this.iterator;\n var mapper = this.mapper;\n var result, inner;\n\n while (true) {\n if (inner = this.inner) try {\n result = anObject(call(inner.next, inner.iterator));\n if (!result.done) return result.value;\n this.inner = null;\n } catch (error) { iteratorClose(iterator, \'throw\', error); }\n\n result = anObject(call(this.next, iterator));\n\n if (this.done = !!result.done) return;\n\n try {\n this.inner = getIteratorFlattenable(mapper(result.value, this.counter++), false);\n } catch (error) { iteratorClose(iterator, \'throw\', error); }\n }\n});\n\n// `Iterator.prototype.flatMap` method\n// https://tc39.es/ecma262/#sec-iterator.prototype.flatmap\n$({ target: \'Iterator\', proto: true, real: true, forced: FORCED }, {\n flatMap: function flatMap(mapper) {\n anObject(this);\n try {\n aCallable(mapper);\n } catch (error) {\n iteratorClose(this, \'throw\', error);\n }\n\n if (flatMapWithoutClosingOnEarlyError) return call(flatMapWithoutClosingOnEarlyError, this, mapper);\n\n return new IteratorProxy(getIteratorDirect(this), {\n mapper: mapper,\n inner: null\n });\n }\n});\n\n\n/***/ },\n\n/***/ 7588\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar call = __webpack_require__(9565);\nvar iterate = __webpack_require__(2652);\nvar aCallable = __webpack_require__(9306);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar iteratorClose = __webpack_require__(9539);\nvar iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);\n\nvar forEachWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError(\'forEach\', TypeError);\n\n// `Iterator.prototype.forEach` method\n// https://tc39.es/ecma262/#sec-iterator.prototype.foreach\n$({ target: \'Iterator\', proto: true, real: true, forced: forEachWithoutClosingOnEarlyError }, {\n forEach: function forEach(fn) {\n anObject(this);\n try {\n aCallable(fn);\n } catch (error) {\n iteratorClose(this, \'throw\', error);\n }\n\n if (forEachWithoutClosingOnEarlyError) return call(forEachWithoutClosingOnEarlyError, this, fn);\n\n var record = getIteratorDirect(this);\n var counter = 0;\n iterate(record, function (value) {\n fn(value, counter++);\n }, { IS_RECORD: true });\n }\n});\n\n\n/***/ },\n\n/***/ 1701\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar call = __webpack_require__(9565);\nvar aCallable = __webpack_require__(9306);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar createIteratorProxy = __webpack_require__(9462);\nvar callWithSafeIterationClosing = __webpack_require__(6319);\nvar iteratorClose = __webpack_require__(9539);\nvar iteratorHelperThrowsOnInvalidIterator = __webpack_require__(684);\nvar iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);\nvar IS_PURE = __webpack_require__(6395);\n\nvar MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator(\'map\', function () { /* empty */ });\nvar mapWithoutClosingOnEarlyError = !IS_PURE && !MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR\n && iteratorHelperWithoutClosingOnEarlyError(\'map\', TypeError);\n\nvar FORCED = IS_PURE || MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR || mapWithoutClosingOnEarlyError;\n\nvar IteratorProxy = createIteratorProxy(function () {\n var iterator = this.iterator;\n var result = anObject(call(this.next, iterator));\n var done = this.done = !!result.done;\n if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true);\n});\n\n// `Iterator.prototype.map` method\n// https://tc39.es/ecma262/#sec-iterator.prototype.map\n$({ target: \'Iterator\', proto: true, real: true, forced: FORCED }, {\n map: function map(mapper) {\n anObject(this);\n try {\n aCallable(mapper);\n } catch (error) {\n iteratorClose(this, \'throw\', error);\n }\n\n if (mapWithoutClosingOnEarlyError) return call(mapWithoutClosingOnEarlyError, this, mapper);\n\n return new IteratorProxy(getIteratorDirect(this), {\n mapper: mapper\n });\n }\n});\n\n\n/***/ },\n\n/***/ 8237\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar iterate = __webpack_require__(2652);\nvar aCallable = __webpack_require__(9306);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar iteratorClose = __webpack_require__(9539);\nvar iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);\nvar apply = __webpack_require__(8745);\nvar fails = __webpack_require__(9039);\n\nvar $TypeError = TypeError;\n\n// https://bugs.webkit.org/show_bug.cgi?id=291651\nvar FAILS_ON_INITIAL_UNDEFINED = fails(function () {\n // eslint-disable-next-line es/no-iterator-prototype-reduce, es/no-array-prototype-keys, array-callback-return -- required for testing\n [].keys().reduce(function () { /* empty */ }, undefined);\n});\n\nvar reduceWithoutClosingOnEarlyError = !FAILS_ON_INITIAL_UNDEFINED && iteratorHelperWithoutClosingOnEarlyError(\'reduce\', $TypeError);\n\n// `Iterator.prototype.reduce` method\n// https://tc39.es/ecma262/#sec-iterator.prototype.reduce\n$({ target: \'Iterator\', proto: true, real: true, forced: FAILS_ON_INITIAL_UNDEFINED || reduceWithoutClosingOnEarlyError }, {\n reduce: function reduce(reducer /* , initialValue */) {\n anObject(this);\n try {\n aCallable(reducer);\n } catch (error) {\n iteratorClose(this, \'throw\', error);\n }\n\n var noInitial = arguments.length < 2;\n var accumulator = noInitial ? undefined : arguments[1];\n if (reduceWithoutClosingOnEarlyError) {\n return apply(reduceWithoutClosingOnEarlyError, this, noInitial ? [reducer] : [reducer, accumulator]);\n }\n var record = getIteratorDirect(this);\n var counter = 0;\n iterate(record, function (value) {\n if (noInitial) {\n noInitial = false;\n accumulator = value;\n } else {\n accumulator = reducer(accumulator, value, counter);\n }\n counter++;\n }, { IS_RECORD: true });\n if (noInitial) throw new $TypeError(\'Reduce of empty iterator with no initial value\');\n return accumulator;\n }\n});\n\n\n/***/ },\n\n/***/ 3579\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar call = __webpack_require__(9565);\nvar iterate = __webpack_require__(2652);\nvar aCallable = __webpack_require__(9306);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar iteratorClose = __webpack_require__(9539);\nvar iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);\n\nvar someWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError(\'some\', TypeError);\n\n// `Iterator.prototype.some` method\n// https://tc39.es/ecma262/#sec-iterator.prototype.some\n$({ target: \'Iterator\', proto: true, real: true, forced: someWithoutClosingOnEarlyError }, {\n some: function some(predicate) {\n anObject(this);\n try {\n aCallable(predicate);\n } catch (error) {\n iteratorClose(this, \'throw\', error);\n }\n\n if (someWithoutClosingOnEarlyError) return call(someWithoutClosingOnEarlyError, this, predicate);\n\n var record = getIteratorDirect(this);\n var counter = 0;\n return iterate(record, function (value, stop) {\n if (predicate(value, counter++)) return stop();\n }, { IS_RECORD: true, INTERRUPTED: true }).stopped;\n }\n});\n\n\n/***/ },\n\n/***/ 4972\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar call = __webpack_require__(9565);\nvar anObject = __webpack_require__(8551);\nvar getIteratorDirect = __webpack_require__(1767);\nvar notANaN = __webpack_require__(4149);\nvar toPositiveInteger = __webpack_require__(9590);\nvar createIteratorProxy = __webpack_require__(9462);\nvar iteratorClose = __webpack_require__(9539);\nvar iteratorHelperWithoutClosingOnEarlyError = __webpack_require__(4549);\nvar IS_PURE = __webpack_require__(6395);\n\nvar takeWithoutClosingOnEarlyError = !IS_PURE && iteratorHelperWithoutClosingOnEarlyError(\'take\', RangeError);\n\nvar IteratorProxy = createIteratorProxy(function () {\n var iterator = this.iterator;\n if (!this.remaining--) {\n this.done = true;\n return iteratorClose(iterator, \'normal\', undefined);\n }\n var result = anObject(call(this.next, iterator));\n var done = this.done = !!result.done;\n if (!done) return result.value;\n});\n\n// `Iterator.prototype.take` method\n// https://tc39.es/ecma262/#sec-iterator.prototype.take\n$({ target: \'Iterator\', proto: true, real: true, forced: IS_PURE || takeWithoutClosingOnEarlyError }, {\n take: function take(limit) {\n anObject(this);\n var remaining;\n try {\n remaining = toPositiveInteger(notANaN(+limit));\n } catch (error) {\n iteratorClose(this, \'throw\', error);\n }\n\n if (takeWithoutClosingOnEarlyError) return call(takeWithoutClosingOnEarlyError, this, remaining);\n\n return new IteratorProxy(getIteratorDirect(this), {\n remaining: remaining\n });\n }\n});\n\n\n/***/ },\n\n/***/ 9112\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar DESCRIPTORS = __webpack_require__(3724);\nvar globalThis = __webpack_require__(4576);\nvar getBuiltIn = __webpack_require__(7751);\nvar uncurryThis = __webpack_require__(9504);\nvar call = __webpack_require__(9565);\nvar isCallable = __webpack_require__(4901);\nvar isObject = __webpack_require__(34);\nvar isArray = __webpack_require__(4376);\nvar hasOwn = __webpack_require__(9297);\nvar toString = __webpack_require__(655);\nvar lengthOfArrayLike = __webpack_require__(6198);\nvar createProperty = __webpack_require__(4659);\nvar fails = __webpack_require__(9039);\nvar parseJSONString = __webpack_require__(8235);\nvar NATIVE_SYMBOL = __webpack_require__(4495);\n\nvar JSON = globalThis.JSON;\nvar Number = globalThis.Number;\nvar SyntaxError = globalThis.SyntaxError;\nvar nativeParse = JSON && JSON.parse;\nvar enumerableOwnProperties = getBuiltIn(\'Object\', \'keys\');\n// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar at = uncurryThis(\'\'.charAt);\nvar slice = uncurryThis(\'\'.slice);\nvar exec = uncurryThis(/./.exec);\nvar push = uncurryThis([].push);\n\nvar IS_DIGIT = /^\\d$/;\nvar IS_NON_ZERO_DIGIT = /^[1-9]$/;\nvar IS_NUMBER_START = /^[\\d-]$/;\nvar IS_WHITESPACE = /^[\\t\\n\\r ]$/;\n\nvar PRIMITIVE = 0;\nvar OBJECT = 1;\n\nvar $parse = function (source, reviver) {\n source = toString(source);\n var context = new Context(source, 0, \'\');\n var root = context.parse();\n var value = root.value;\n var endIndex = context.skip(IS_WHITESPACE, root.end);\n if (endIndex < source.length) {\n throw new SyntaxError(\'Unexpected extra character: "\' + at(source, endIndex) + \'" after the parsed data at: \' + endIndex);\n }\n return isCallable(reviver) ? internalize({ \'\': value }, \'\', reviver, root) : value;\n};\n\nvar internalize = function (holder, name, reviver, node) {\n var val = holder[name];\n var unmodified = node && val === node.value;\n var context = unmodified && typeof node.source == \'string\' ? { source: node.source } : {};\n var elementRecordsLen, keys, len, i, P;\n if (isObject(val)) {\n var nodeIsArray = isArray(val);\n var nodes = unmodified ? node.nodes : nodeIsArray ? [] : {};\n if (nodeIsArray) {\n elementRecordsLen = nodes.length;\n len = lengthOfArrayLike(val);\n for (i = 0; i < len; i++) {\n internalizeProperty(val, i, internalize(val, \'\' + i, reviver, i < elementRecordsLen ? nodes[i] : undefined));\n }\n } else {\n keys = enumerableOwnProperties(val);\n len = lengthOfArrayLike(keys);\n for (i = 0; i < len; i++) {\n P = keys[i];\n internalizeProperty(val, P, internalize(val, P, reviver, hasOwn(nodes, P) ? nodes[P] : undefined));\n }\n }\n }\n return call(reviver, holder, name, val, context);\n};\n\nvar internalizeProperty = function (object, key, value) {\n if (DESCRIPTORS) {\n var descriptor = getOwnPropertyDescriptor(object, key);\n if (descriptor && !descriptor.configurable) return;\n }\n if (value === undefined) delete object[key];\n else createProperty(object, key, value);\n};\n\nvar Node = function (value, end, source, nodes) {\n this.value = value;\n this.end = end;\n this.source = source;\n this.nodes = nodes;\n};\n\nvar Context = function (source, index) {\n this.source = source;\n this.index = index;\n};\n\n// https://www.json.org/json-en.html\nContext.prototype = {\n fork: function (nextIndex) {\n return new Context(this.source, nextIndex);\n },\n parse: function () {\n var source = this.source;\n var i = this.skip(IS_WHITESPACE, this.index);\n var fork = this.fork(i);\n var chr = at(source, i);\n if (exec(IS_NUMBER_START, chr)) return fork.number();\n switch (chr) {\n case \'{\':\n return fork.object();\n case \'[\':\n return fork.array();\n case \'"\':\n return fork.string();\n case \'t\':\n return fork.keyword(true);\n case \'f\':\n return fork.keyword(false);\n case \'n\':\n return fork.keyword(null);\n } throw new SyntaxError(\'Unexpected character: "\' + chr + \'" at: \' + i);\n },\n node: function (type, value, start, end, nodes) {\n return new Node(value, end, type ? null : slice(this.source, start, end), nodes);\n },\n object: function () {\n var source = this.source;\n var i = this.index + 1;\n var expectKeypair = false;\n var object = {};\n var nodes = {};\n while (i < source.length) {\n i = this.until([\'"\', \'}\'], i);\n if (at(source, i) === \'}\' && !expectKeypair) {\n i++;\n break;\n }\n // Parsing the key\n var result = this.fork(i).string();\n var key = result.value;\n i = result.end;\n i = this.until([\':\'], i) + 1;\n // Parsing value\n i = this.skip(IS_WHITESPACE, i);\n result = this.fork(i).parse();\n createProperty(nodes, key, result);\n createProperty(object, key, result.value);\n i = this.until([\',\', \'}\'], result.end);\n var chr = at(source, i);\n if (chr === \',\') {\n expectKeypair = true;\n i++;\n } else if (chr === \'}\') {\n i++;\n break;\n }\n }\n return this.node(OBJECT, object, this.index, i, nodes);\n },\n array: function () {\n var source = this.source;\n var i = this.index + 1;\n var expectElement = false;\n var array = [];\n var nodes = [];\n while (i < source.length) {\n i = this.skip(IS_WHITESPACE, i);\n if (at(source, i) === \']\' && !expectElement) {\n i++;\n break;\n }\n var result = this.fork(i).parse();\n push(nodes, result);\n push(array, result.value);\n i = this.until([\',\', \']\'], result.end);\n if (at(source, i) === \',\') {\n expectElement = true;\n i++;\n } else if (at(source, i) === \']\') {\n i++;\n break;\n }\n }\n return this.node(OBJECT, array, this.index, i, nodes);\n },\n string: function () {\n var index = this.index;\n var parsed = parseJSONString(this.source, this.index + 1);\n return this.node(PRIMITIVE, parsed.value, index, parsed.end);\n },\n number: function () {\n var source = this.source;\n var startIndex = this.index;\n var i = startIndex;\n if (at(source, i) === \'-\') i++;\n if (at(source, i) === \'0\') i++;\n else if (exec(IS_NON_ZERO_DIGIT, at(source, i))) i = this.skip(IS_DIGIT, i + 1);\n else throw new SyntaxError(\'Failed to parse number at: \' + i);\n if (at(source, i) === \'.\') i = this.skip(IS_DIGIT, i + 1);\n if (at(source, i) === \'e\' || at(source, i) === \'E\') {\n i++;\n if (at(source, i) === \'+\' || at(source, i) === \'-\') i++;\n var exponentStartIndex = i;\n i = this.skip(IS_DIGIT, i);\n if (exponentStartIndex === i) throw new SyntaxError("Failed to parse number\'s exponent value at: " + i);\n }\n return this.node(PRIMITIVE, Number(slice(source, startIndex, i)), startIndex, i);\n },\n keyword: function (value) {\n var keyword = \'\' + value;\n var index = this.index;\n var endIndex = index + keyword.length;\n if (slice(this.source, index, endIndex) !== keyword) throw new SyntaxError(\'Failed to parse value at: \' + index);\n return this.node(PRIMITIVE, value, index, endIndex);\n },\n skip: function (regex, i) {\n var source = this.source;\n for (; i < source.length; i++) if (!exec(regex, at(source, i))) break;\n return i;\n },\n until: function (array, i) {\n i = this.skip(IS_WHITESPACE, i);\n var chr = at(this.source, i);\n for (var j = 0; j < array.length; j++) if (array[j] === chr) return i;\n throw new SyntaxError(\'Unexpected character: "\' + chr + \'" at: \' + i);\n }\n};\n\nvar NO_SOURCE_SUPPORT = fails(function () {\n var unsafeInt = \'9007199254740993\';\n var source;\n nativeParse(unsafeInt, function (key, value, context) {\n source = context.source;\n });\n return source !== unsafeInt;\n});\n\nvar PROPER_BASE_PARSE = NATIVE_SYMBOL && !fails(function () {\n // Safari 9 bug\n return 1 / nativeParse(\'-0 \\t\') !== -Infinity;\n});\n\n// `JSON.parse` method\n// https://tc39.es/ecma262/#sec-json.parse\n// https://github.com/tc39/proposal-json-parse-with-source\n$({ target: \'JSON\', stat: true, forced: NO_SOURCE_SUPPORT }, {\n parse: function parse(text, reviver) {\n return PROPER_BASE_PARSE && !isCallable(reviver) ? nativeParse(text) : $parse(text, reviver);\n }\n});\n\n\n/***/ },\n\n/***/ 3110\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar getBuiltIn = __webpack_require__(7751);\nvar apply = __webpack_require__(8745);\nvar call = __webpack_require__(9565);\nvar uncurryThis = __webpack_require__(9504);\nvar fails = __webpack_require__(9039);\nvar isArray = __webpack_require__(4376);\nvar isCallable = __webpack_require__(4901);\nvar isRawJSON = __webpack_require__(5810);\nvar isSymbol = __webpack_require__(757);\nvar classof = __webpack_require__(2195);\nvar toString = __webpack_require__(655);\nvar arraySlice = __webpack_require__(7680);\nvar parseJSONString = __webpack_require__(8235);\nvar uid = __webpack_require__(3392);\nvar NATIVE_SYMBOL = __webpack_require__(4495);\nvar NATIVE_RAW_JSON = __webpack_require__(7819);\n\nvar $String = String;\nvar $stringify = getBuiltIn(\'JSON\', \'stringify\');\nvar exec = uncurryThis(/./.exec);\nvar charAt = uncurryThis(\'\'.charAt);\nvar charCodeAt = uncurryThis(\'\'.charCodeAt);\nvar replace = uncurryThis(\'\'.replace);\nvar slice = uncurryThis(\'\'.slice);\nvar push = uncurryThis([].push);\nvar numberToString = uncurryThis(1.1.toString);\n\nvar surrogates = /[\\uD800-\\uDFFF]/g;\nvar lowSurrogates = /^[\\uD800-\\uDBFF]$/;\nvar hiSurrogates = /^[\\uDC00-\\uDFFF]$/;\n\nvar MARK = uid();\nvar MARK_LENGTH = MARK.length;\n\nvar WRONG_SYMBOLS_CONVERSION = !NATIVE_SYMBOL || fails(function () {\n var symbol = getBuiltIn(\'Symbol\')(\'stringify detection\');\n // MS Edge converts symbol values to JSON as {}\n return $stringify([symbol]) !== \'[null]\'\n // WebKit converts symbol values to JSON as null\n || $stringify({ a: symbol }) !== \'{}\'\n // V8 throws on boxed symbols\n || $stringify(Object(symbol)) !== \'{}\';\n});\n\n// https://github.com/tc39/proposal-well-formed-stringify\nvar ILL_FORMED_UNICODE = fails(function () {\n return $stringify(\'\\uDF06\\uD834\') !== \'"\\\\udf06\\\\ud834"\'\n || $stringify(\'\\uDEAD\') !== \'"\\\\udead"\';\n});\n\nvar stringifyWithProperSymbolsConversion = WRONG_SYMBOLS_CONVERSION ? function (it, replacer) {\n var args = arraySlice(arguments);\n var $replacer = getReplacerFunction(replacer);\n if (!isCallable($replacer) && (it === undefined || isSymbol(it))) return; // IE8 returns string on undefined\n args[1] = function (key, value) {\n // some old implementations (like WebKit) could pass numbers as keys\n if (isCallable($replacer)) value = call($replacer, this, $String(key), value);\n if (!isSymbol(value)) return value;\n };\n return apply($stringify, null, args);\n} : $stringify;\n\nvar fixIllFormedJSON = function (match, offset, string) {\n var prev = charAt(string, offset - 1);\n var next = charAt(string, offset + 1);\n if ((exec(lowSurrogates, match) && !exec(hiSurrogates, next)) || (exec(hiSurrogates, match) && !exec(lowSurrogates, prev))) {\n return \'\\\\u\' + numberToString(charCodeAt(match, 0), 16);\n } return match;\n};\n\nvar getReplacerFunction = function (replacer) {\n if (isCallable(replacer)) return replacer;\n if (!isArray(replacer)) return;\n var rawLength = replacer.length;\n var keys = [];\n for (var i = 0; i < rawLength; i++) {\n var element = replacer[i];\n if (typeof element == \'string\') push(keys, element);\n else if (typeof element == \'number\' || classof(element) === \'Number\' || classof(element) === \'String\') push(keys, toString(element));\n }\n var keysLength = keys.length;\n var root = true;\n return function (key, value) {\n if (root) {\n root = false;\n return value;\n }\n if (isArray(this)) return value;\n for (var j = 0; j < keysLength; j++) if (keys[j] === key) return value;\n };\n};\n\n// `JSON.stringify` method\n// https://tc39.es/ecma262/#sec-json.stringify\n// https://github.com/tc39/proposal-json-parse-with-source\nif ($stringify) $({ target: \'JSON\', stat: true, arity: 3, forced: WRONG_SYMBOLS_CONVERSION || ILL_FORMED_UNICODE || !NATIVE_RAW_JSON }, {\n stringify: function stringify(text, replacer, space) {\n var replacerFunction = getReplacerFunction(replacer);\n var rawStrings = [];\n\n var json = stringifyWithProperSymbolsConversion(text, function (key, value) {\n // some old implementations (like WebKit) could pass numbers as keys\n var v = isCallable(replacerFunction) ? call(replacerFunction, this, $String(key), value) : value;\n return !NATIVE_RAW_JSON && isRawJSON(v) ? MARK + (push(rawStrings, v.rawJSON) - 1) : v;\n }, space);\n\n if (typeof json != \'string\') return json;\n\n if (ILL_FORMED_UNICODE) json = replace(json, surrogates, fixIllFormedJSON);\n\n if (NATIVE_RAW_JSON) return json;\n\n var result = \'\';\n var length = json.length;\n\n for (var i = 0; i < length; i++) {\n var chr = charAt(json, i);\n if (chr === \'"\') {\n var end = parseJSONString(json, ++i).end - 1;\n var string = slice(json, i, end);\n result += slice(string, 0, MARK_LENGTH) === MARK\n ? rawStrings[slice(string, MARK_LENGTH)]\n : \'"\' + string + \'"\';\n i = end;\n } else result += chr;\n }\n\n return result;\n }\n});\n\n\n/***/ },\n\n/***/ 2731\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar aCallable = __webpack_require__(9306);\nvar aMap = __webpack_require__(6194);\nvar MapHelpers = __webpack_require__(2248);\nvar IS_PURE = __webpack_require__(6395);\n\nvar get = MapHelpers.get;\nvar has = MapHelpers.has;\nvar set = MapHelpers.set;\n\n// `Map.prototype.getOrInsertComputed` method\n// https://github.com/tc39/proposal-upsert\n$({ target: \'Map\', proto: true, real: true, forced: IS_PURE }, {\n getOrInsertComputed: function getOrInsertComputed(key, callbackfn) {\n aMap(this);\n aCallable(callbackfn);\n if (has(this, key)) return get(this, key);\n // CanonicalizeKeyedCollectionKey\n if (key === 0 && 1 / key === -Infinity) key = 0;\n var value = callbackfn(key);\n set(this, key, value);\n return value;\n }\n});\n\n\n/***/ },\n\n/***/ 5367\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar aMap = __webpack_require__(6194);\nvar MapHelpers = __webpack_require__(2248);\nvar IS_PURE = __webpack_require__(6395);\n\nvar get = MapHelpers.get;\nvar has = MapHelpers.has;\nvar set = MapHelpers.set;\n\n// `Map.prototype.getOrInsert` method\n// https://github.com/tc39/proposal-upsert\n$({ target: \'Map\', proto: true, real: true, forced: IS_PURE }, {\n getOrInsert: function getOrInsert(key, value) {\n if (has(aMap(this), key)) return get(this, key);\n set(this, key, value);\n return value;\n }\n});\n\n\n/***/ },\n\n/***/ 3068\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\n// based on Shewchuk\'s algorithm for exactly floating point addition\n// adapted from https://github.com/tc39/proposal-math-sum/blob/3513d58323a1ae25560e8700aa5294500c6c9287/polyfill/polyfill.mjs\nvar $ = __webpack_require__(6518);\nvar uncurryThis = __webpack_require__(9504);\nvar iterate = __webpack_require__(2652);\n\nvar $RangeError = RangeError;\nvar $TypeError = TypeError;\nvar $Infinity = Infinity;\nvar $NaN = NaN;\nvar abs = Math.abs;\nvar pow = Math.pow;\nvar push = uncurryThis([].push);\n\nvar POW_2_1023 = pow(2, 1023);\nvar MAX_SAFE_INTEGER = pow(2, 53) - 1; // 2 ** 53 - 1 === 9007199254740992\nvar MAX_DOUBLE = Number.MAX_VALUE; // 2 ** 1024 - 2 ** (1023 - 52) === 1.79769313486231570815e+308\nvar MAX_ULP = pow(2, 971); // 2 ** (1023 - 52) === 1.99584030953471981166e+292\n\nvar NOT_A_NUMBER = {};\nvar MINUS_INFINITY = {};\nvar PLUS_INFINITY = {};\nvar MINUS_ZERO = {};\nvar FINITE = {};\n\n// prerequisite: abs(x) >= abs(y)\nvar twosum = function (x, y) {\n var hi = x + y;\n var lo = y - (hi - x);\n return { hi: hi, lo: lo };\n};\n\n// `Math.sumPrecise` method\n// https://github.com/tc39/proposal-math-sum\n$({ target: \'Math\', stat: true }, {\n // eslint-disable-next-line max-statements -- ok\n sumPrecise: function sumPrecise(items) {\n var numbers = [];\n var count = 0;\n var state = MINUS_ZERO;\n\n iterate(items, function (n) {\n if (++count >= MAX_SAFE_INTEGER) throw new $RangeError(\'Maximum allowed index exceeded\');\n if (typeof n != \'number\') throw new $TypeError(\'Value is not a number\');\n if (state !== NOT_A_NUMBER) {\n // eslint-disable-next-line no-self-compare -- NaN check\n if (n !== n) state = NOT_A_NUMBER;\n else if (n === $Infinity) state = state === MINUS_INFINITY ? NOT_A_NUMBER : PLUS_INFINITY;\n else if (n === -$Infinity) state = state === PLUS_INFINITY ? NOT_A_NUMBER : MINUS_INFINITY;\n else if ((n !== 0 || (1 / n) === $Infinity) && (state === MINUS_ZERO || state === FINITE)) {\n state = FINITE;\n push(numbers, n);\n }\n }\n });\n\n switch (state) {\n case NOT_A_NUMBER: return $NaN;\n case MINUS_INFINITY: return -$Infinity;\n case PLUS_INFINITY: return $Infinity;\n case MINUS_ZERO: return -0;\n }\n\n var partials = [];\n var overflow = 0; // conceptually 2 ** 1024 times this value; the final partial is biased by this amount\n var x, y, sum, hi, lo, tmp;\n\n for (var i = 0; i < numbers.length; i++) {\n x = numbers[i];\n var actuallyUsedPartials = 0;\n for (var j = 0; j < partials.length; j++) {\n y = partials[j];\n if (abs(x) < abs(y)) {\n tmp = x;\n x = y;\n y = tmp;\n }\n sum = twosum(x, y);\n hi = sum.hi;\n lo = sum.lo;\n if (abs(hi) === $Infinity) {\n var sign = hi === $Infinity ? 1 : -1;\n overflow += sign;\n\n x = (x - (sign * POW_2_1023)) - (sign * POW_2_1023);\n if (abs(x) < abs(y)) {\n tmp = x;\n x = y;\n y = tmp;\n }\n sum = twosum(x, y);\n hi = sum.hi;\n lo = sum.lo;\n }\n if (lo !== 0) partials[actuallyUsedPartials++] = lo;\n x = hi;\n }\n partials.length = actuallyUsedPartials;\n if (x !== 0) push(partials, x);\n }\n\n // compute the exact sum of partials, stopping once we lose precision\n var n = partials.length - 1;\n hi = 0;\n lo = 0;\n\n if (overflow !== 0) {\n var next = n >= 0 ? partials[n] : 0;\n n--;\n if (abs(overflow) > 1 || (overflow > 0 && next > 0) || (overflow < 0 && next < 0)) {\n return overflow > 0 ? $Infinity : -$Infinity;\n }\n // here we actually have to do the arithmetic\n // drop a factor of 2 so we can do it without overflow\n // assert(abs(overflow) === 1)\n sum = twosum(overflow * POW_2_1023, next / 2);\n hi = sum.hi;\n lo = sum.lo;\n lo *= 2;\n if (abs(2 * hi) === $Infinity) {\n // rounding to the maximum value\n if (hi > 0) {\n return (hi === POW_2_1023 && lo === -(MAX_ULP / 2) && n >= 0 && partials[n] < 0) ? MAX_DOUBLE : $Infinity;\n } return (hi === -POW_2_1023 && lo === (MAX_ULP / 2) && n >= 0 && partials[n] > 0) ? -MAX_DOUBLE : -$Infinity;\n }\n\n if (lo !== 0) {\n partials[++n] = lo;\n lo = 0;\n }\n\n hi *= 2;\n }\n\n while (n >= 0) {\n sum = twosum(hi, partials[n--]);\n hi = sum.hi;\n lo = sum.lo;\n if (lo !== 0) break;\n }\n\n if (n >= 0 && ((lo < 0 && partials[n] < 0) || (lo > 0 && partials[n] > 0))) {\n y = lo * 2;\n x = hi + y;\n if (y === x - hi) hi = x;\n }\n\n return hi;\n }\n});\n\n\n/***/ },\n\n/***/ 1689\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar globalThis = __webpack_require__(4576);\nvar apply = __webpack_require__(8745);\nvar slice = __webpack_require__(7680);\nvar newPromiseCapabilityModule = __webpack_require__(6043);\nvar aCallable = __webpack_require__(9306);\nvar perform = __webpack_require__(1103);\n\nvar Promise = globalThis.Promise;\n\nvar ACCEPT_ARGUMENTS = false;\n// Avoiding the use of polyfills of the previous iteration of this proposal\n// that does not accept arguments of the callback\nvar FORCED = !Promise || !Promise[\'try\'] || perform(function () {\n Promise[\'try\'](function (argument) {\n ACCEPT_ARGUMENTS = argument === 8;\n }, 8);\n}).error || !ACCEPT_ARGUMENTS;\n\n// `Promise.try` method\n// https://tc39.es/ecma262/#sec-promise.try\n$({ target: \'Promise\', stat: true, forced: FORCED }, {\n \'try\': function (callbackfn /* , ...args */) {\n var args = arguments.length > 1 ? slice(arguments, 1) : [];\n var promiseCapability = newPromiseCapabilityModule.f(this);\n var result = perform(function () {\n return apply(aCallable(callbackfn), undefined, args);\n });\n (result.error ? promiseCapability.reject : promiseCapability.resolve)(result.value);\n return promiseCapability.promise;\n }\n});\n\n\n/***/ },\n\n/***/ 4628\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar newPromiseCapabilityModule = __webpack_require__(6043);\n\n// `Promise.withResolvers` method\n// https://tc39.es/ecma262/#sec-promise.withResolvers\n$({ target: \'Promise\', stat: true }, {\n withResolvers: function withResolvers() {\n var promiseCapability = newPromiseCapabilityModule.f(this);\n return {\n promise: promiseCapability.promise,\n resolve: promiseCapability.resolve,\n reject: promiseCapability.reject\n };\n }\n});\n\n\n/***/ },\n\n/***/ 7642\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar difference = __webpack_require__(3440);\nvar fails = __webpack_require__(9039);\nvar setMethodAcceptSetLike = __webpack_require__(4916);\n\nvar SET_LIKE_INCORRECT_BEHAVIOR = !setMethodAcceptSetLike(\'difference\', function (result) {\n return result.size === 0;\n});\n\nvar FORCED = SET_LIKE_INCORRECT_BEHAVIOR || fails(function () {\n // https://bugs.webkit.org/show_bug.cgi?id=288595\n var setLike = {\n size: 1,\n has: function () { return true; },\n keys: function () {\n var index = 0;\n return {\n next: function () {\n var done = index++ > 1;\n if (baseSet.has(1)) baseSet.clear();\n return { done: done, value: 2 };\n }\n };\n }\n };\n // eslint-disable-next-line es/no-set -- testing\n var baseSet = new Set([1, 2, 3, 4]);\n // eslint-disable-next-line es/no-set-prototype-difference -- testing\n return baseSet.difference(setLike).size !== 3;\n});\n\n// `Set.prototype.difference` method\n// https://tc39.es/ecma262/#sec-set.prototype.difference\n$({ target: \'Set\', proto: true, real: true, forced: FORCED }, {\n difference: difference\n});\n\n\n/***/ },\n\n/***/ 8004\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar fails = __webpack_require__(9039);\nvar intersection = __webpack_require__(8750);\nvar setMethodAcceptSetLike = __webpack_require__(4916);\n\nvar INCORRECT = !setMethodAcceptSetLike(\'intersection\', function (result) {\n return result.size === 2 && result.has(1) && result.has(2);\n}) || fails(function () {\n // eslint-disable-next-line es/no-array-from, es/no-set, es/no-set-prototype-intersection -- testing\n return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== \'3,2\';\n});\n\n// `Set.prototype.intersection` method\n// https://tc39.es/ecma262/#sec-set.prototype.intersection\n$({ target: \'Set\', proto: true, real: true, forced: INCORRECT }, {\n intersection: intersection\n});\n\n\n/***/ },\n\n/***/ 3853\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar isDisjointFrom = __webpack_require__(4449);\nvar setMethodAcceptSetLike = __webpack_require__(4916);\n\nvar INCORRECT = !setMethodAcceptSetLike(\'isDisjointFrom\', function (result) {\n return !result;\n});\n\n// `Set.prototype.isDisjointFrom` method\n// https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom\n$({ target: \'Set\', proto: true, real: true, forced: INCORRECT }, {\n isDisjointFrom: isDisjointFrom\n});\n\n\n/***/ },\n\n/***/ 5876\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar isSubsetOf = __webpack_require__(3838);\nvar setMethodAcceptSetLike = __webpack_require__(4916);\n\nvar INCORRECT = !setMethodAcceptSetLike(\'isSubsetOf\', function (result) {\n return result;\n});\n\n// `Set.prototype.isSubsetOf` method\n// https://tc39.es/ecma262/#sec-set.prototype.issubsetof\n$({ target: \'Set\', proto: true, real: true, forced: INCORRECT }, {\n isSubsetOf: isSubsetOf\n});\n\n\n/***/ },\n\n/***/ 2475\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar isSupersetOf = __webpack_require__(8527);\nvar setMethodAcceptSetLike = __webpack_require__(4916);\n\nvar INCORRECT = !setMethodAcceptSetLike(\'isSupersetOf\', function (result) {\n return !result;\n});\n\n// `Set.prototype.isSupersetOf` method\n// https://tc39.es/ecma262/#sec-set.prototype.issupersetof\n$({ target: \'Set\', proto: true, real: true, forced: INCORRECT }, {\n isSupersetOf: isSupersetOf\n});\n\n\n/***/ },\n\n/***/ 5024\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar symmetricDifference = __webpack_require__(3650);\nvar setMethodGetKeysBeforeCloning = __webpack_require__(9835);\nvar setMethodAcceptSetLike = __webpack_require__(4916);\n\nvar FORCED = !setMethodAcceptSetLike(\'symmetricDifference\') || !setMethodGetKeysBeforeCloning(\'symmetricDifference\');\n\n// `Set.prototype.symmetricDifference` method\n// https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference\n$({ target: \'Set\', proto: true, real: true, forced: FORCED }, {\n symmetricDifference: symmetricDifference\n});\n\n\n/***/ },\n\n/***/ 1698\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar union = __webpack_require__(4204);\nvar setMethodGetKeysBeforeCloning = __webpack_require__(9835);\nvar setMethodAcceptSetLike = __webpack_require__(4916);\n\nvar FORCED = !setMethodAcceptSetLike(\'union\') || !setMethodGetKeysBeforeCloning(\'union\');\n\n// `Set.prototype.union` method\n// https://tc39.es/ecma262/#sec-set.prototype.union\n$({ target: \'Set\', proto: true, real: true, forced: FORCED }, {\n union: union\n});\n\n\n/***/ },\n\n/***/ 9577\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar ArrayBufferViewCore = __webpack_require__(4644);\nvar isBigIntArray = __webpack_require__(1108);\nvar lengthOfArrayLike = __webpack_require__(6198);\nvar toIntegerOrInfinity = __webpack_require__(1291);\nvar toBigInt = __webpack_require__(5854);\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\nvar $RangeError = RangeError;\n\nvar PROPER_ORDER = function () {\n try {\n // eslint-disable-next-line no-throw-literal, es/no-typed-arrays, es/no-array-prototype-with -- required for testing\n new Int8Array(1)[\'with\'](2, { valueOf: function () { throw 8; } });\n } catch (error) {\n // some early implementations, like WebKit, does not follow the final semantic\n // https://github.com/tc39/proposal-change-array-by-copy/pull/86\n return error === 8;\n }\n}();\n\n// Bug in WebKit. It should truncate a negative fractional index to zero, but instead throws an error\nvar THROW_ON_NEGATIVE_FRACTIONAL_INDEX = PROPER_ORDER && function () {\n try {\n // eslint-disable-next-line es/no-typed-arrays, es/no-array-prototype-with -- required for testing\n new Int8Array(1)[\'with\'](-0.5, 1);\n } catch (error) {\n return true;\n }\n}();\n\n// `%TypedArray%.prototype.with` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.with\nexportTypedArrayMethod(\'with\', { \'with\': function (index, value) {\n var O = aTypedArray(this);\n var len = lengthOfArrayLike(O);\n var relativeIndex = toIntegerOrInfinity(index);\n var actualIndex = relativeIndex < 0 ? len + relativeIndex : relativeIndex;\n var numericValue = isBigIntArray(O) ? toBigInt(value) : +value;\n if (actualIndex >= len || actualIndex < 0) throw new $RangeError(\'Incorrect index\');\n var A = new (getTypedArrayConstructor(O))(len);\n var k = 0;\n for (; k < len; k++) A[k] = k === actualIndex ? numericValue : O[k];\n return A;\n} }[\'with\'], !PROPER_ORDER || THROW_ON_NEGATIVE_FRACTIONAL_INDEX);\n\n\n/***/ },\n\n/***/ 5213\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar globalThis = __webpack_require__(4576);\nvar arrayFromConstructorAndList = __webpack_require__(5370);\nvar $fromBase64 = __webpack_require__(9143);\n\nvar Uint8Array = globalThis.Uint8Array;\n\nvar INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS = !Uint8Array || !Uint8Array.fromBase64 || !function () {\n // Webkit not throw an error on odd length string\n try {\n Uint8Array.fromBase64(\'a\');\n return;\n } catch (error) { /* empty */ }\n try {\n Uint8Array.fromBase64(\'\', null);\n } catch (error) {\n return true;\n }\n}();\n\n// `Uint8Array.fromBase64` method\n// https://github.com/tc39/proposal-arraybuffer-base64\nif (Uint8Array) $({ target: \'Uint8Array\', stat: true, forced: INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS }, {\n fromBase64: function fromBase64(string /* , options */) {\n var result = $fromBase64(string, arguments.length > 1 ? arguments[1] : undefined, null, 0x1FFFFFFFFFFFFF);\n return arrayFromConstructorAndList(Uint8Array, result.bytes);\n }\n});\n\n\n/***/ },\n\n/***/ 6632\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar globalThis = __webpack_require__(4576);\nvar $fromBase64 = __webpack_require__(9143);\nvar anUint8Array = __webpack_require__(4154);\n\nvar Uint8Array = globalThis.Uint8Array;\n\nvar INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS = !Uint8Array || !Uint8Array.prototype.setFromBase64 || !function () {\n var target = new Uint8Array([255, 255, 255, 255, 255]);\n try {\n target.setFromBase64(\'\', null);\n return;\n } catch (error) { /* empty */ }\n // Webkit not throw an error on odd length string\n try {\n target.setFromBase64(\'a\');\n return;\n } catch (error) { /* empty */ }\n try {\n target.setFromBase64(\'MjYyZg===\');\n } catch (error) {\n return target[0] === 50 && target[1] === 54 && target[2] === 50 && target[3] === 255 && target[4] === 255;\n }\n}();\n\n// `Uint8Array.prototype.setFromBase64` method\n// https://github.com/tc39/proposal-arraybuffer-base64\nif (Uint8Array) $({ target: \'Uint8Array\', proto: true, forced: INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS }, {\n setFromBase64: function setFromBase64(string /* , options */) {\n anUint8Array(this);\n\n var result = $fromBase64(string, arguments.length > 1 ? arguments[1] : undefined, this, this.length);\n\n return { read: result.read, written: result.written };\n }\n});\n\n\n/***/ },\n\n/***/ 4226\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar globalThis = __webpack_require__(4576);\nvar aString = __webpack_require__(3463);\nvar anUint8Array = __webpack_require__(4154);\nvar notDetached = __webpack_require__(5169);\nvar $fromHex = __webpack_require__(2303);\n\n// Should not throw an error on length-tracking views over ResizableArrayBuffer\n// https://issues.chromium.org/issues/454630441\nfunction throwsOnLengthTrackingView() {\n try {\n // eslint-disable-next-line es/no-resizable-and-growable-arraybuffers -- required for testing\n var rab = new ArrayBuffer(16, { maxByteLength: 1024 });\n // eslint-disable-next-line es/no-uint8array-prototype-setfromhex, es/no-typed-arrays -- required for testing\n new Uint8Array(rab).setFromHex(\'cafed00d\');\n } catch (error) {\n return true;\n }\n}\n\n// `Uint8Array.prototype.setFromHex` method\n// https://github.com/tc39/proposal-arraybuffer-base64\nif (globalThis.Uint8Array) $({ target: \'Uint8Array\', proto: true, forced: throwsOnLengthTrackingView() }, {\n setFromHex: function setFromHex(string) {\n anUint8Array(this);\n aString(string);\n notDetached(this.buffer);\n var read = $fromHex(string, this).read;\n return { read: read, written: read / 2 };\n }\n});\n\n\n/***/ },\n\n/***/ 9486\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar globalThis = __webpack_require__(4576);\nvar uncurryThis = __webpack_require__(9504);\nvar anObjectOrUndefined = __webpack_require__(3972);\nvar anUint8Array = __webpack_require__(4154);\nvar notDetached = __webpack_require__(5169);\nvar base64Map = __webpack_require__(2804);\nvar getAlphabetOption = __webpack_require__(944);\n\nvar base64Alphabet = base64Map.i2c;\nvar base64UrlAlphabet = base64Map.i2cUrl;\n\nvar charAt = uncurryThis(\'\'.charAt);\n\nvar Uint8Array = globalThis.Uint8Array;\n\nvar INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS = !Uint8Array || !Uint8Array.prototype.toBase64 || !function () {\n try {\n var target = new Uint8Array();\n target.toBase64(null);\n } catch (error) {\n return true;\n }\n}();\n\n// `Uint8Array.prototype.toBase64` method\n// https://github.com/tc39/proposal-arraybuffer-base64\nif (Uint8Array) $({ target: \'Uint8Array\', proto: true, forced: INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS }, {\n toBase64: function toBase64(/* options */) {\n var array = anUint8Array(this);\n var options = arguments.length ? anObjectOrUndefined(arguments[0]) : undefined;\n var alphabet = getAlphabetOption(options) === \'base64\' ? base64Alphabet : base64UrlAlphabet;\n var omitPadding = !!options && !!options.omitPadding;\n notDetached(this.buffer);\n\n var result = \'\';\n var i = 0;\n var length = array.length;\n var triplet;\n\n var at = function (shift) {\n return charAt(alphabet, (triplet >> (6 * shift)) & 63);\n };\n\n for (; i + 2 < length; i += 3) {\n triplet = (array[i] << 16) + (array[i + 1] << 8) + array[i + 2];\n result += at(3) + at(2) + at(1) + at(0);\n }\n if (i + 2 === length) {\n triplet = (array[i] << 16) + (array[i + 1] << 8);\n result += at(3) + at(2) + at(1) + (omitPadding ? \'\' : \'=\');\n } else if (i + 1 === length) {\n triplet = array[i] << 16;\n result += at(3) + at(2) + (omitPadding ? \'\' : \'==\');\n }\n\n return result;\n }\n});\n\n\n/***/ },\n\n/***/ 456\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar globalThis = __webpack_require__(4576);\nvar uncurryThis = __webpack_require__(9504);\nvar anUint8Array = __webpack_require__(4154);\nvar notDetached = __webpack_require__(5169);\n\nvar numberToString = uncurryThis(1.1.toString);\n\nvar Uint8Array = globalThis.Uint8Array;\n\nvar INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS = !Uint8Array || !Uint8Array.prototype.toHex || !(function () {\n try {\n var target = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]);\n return target.toHex() === \'ffffffffffffffff\';\n } catch (error) {\n return false;\n }\n})();\n\n// `Uint8Array.prototype.toHex` method\n// https://github.com/tc39/proposal-arraybuffer-base64\nif (Uint8Array) $({ target: \'Uint8Array\', proto: true, forced: INCORRECT_BEHAVIOR_OR_DOESNT_EXISTS }, {\n toHex: function toHex() {\n anUint8Array(this);\n notDetached(this.buffer);\n var result = \'\';\n for (var i = 0, length = this.length; i < length; i++) {\n var hex = numberToString(this[i], 16);\n result += hex.length === 1 ? \'0\' + hex : hex;\n }\n return result;\n }\n});\n\n\n/***/ },\n\n/***/ 9452\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar aCallable = __webpack_require__(9306);\nvar aWeakMap = __webpack_require__(6557);\nvar aWeakKey = __webpack_require__(4328);\nvar WeakMapHelpers = __webpack_require__(4995);\nvar IS_PURE = __webpack_require__(6395);\n\nvar get = WeakMapHelpers.get;\nvar has = WeakMapHelpers.has;\nvar set = WeakMapHelpers.set;\n\nvar FORCED = IS_PURE || !function () {\n try {\n // eslint-disable-next-line es/no-weak-map, no-throw-literal -- testing\n if (WeakMap.prototype.getOrInsertComputed) new WeakMap().getOrInsertComputed(1, function () { throw 1; });\n } catch (error) {\n // FF144 Nightly - Beta 3 bug\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1988369\n return error instanceof TypeError;\n }\n}();\n\n// `WeakMap.prototype.getOrInsertComputed` method\n// https://github.com/tc39/proposal-upsert\n$({ target: \'WeakMap\', proto: true, real: true, forced: FORCED }, {\n getOrInsertComputed: function getOrInsertComputed(key, callbackfn) {\n aWeakMap(this);\n aWeakKey(key);\n aCallable(callbackfn);\n if (has(this, key)) return get(this, key);\n var value = callbackfn(key);\n set(this, key, value);\n return value;\n }\n});\n\n\n/***/ },\n\n/***/ 8454\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar aWeakMap = __webpack_require__(6557);\nvar WeakMapHelpers = __webpack_require__(4995);\nvar IS_PURE = __webpack_require__(6395);\n\nvar get = WeakMapHelpers.get;\nvar has = WeakMapHelpers.has;\nvar set = WeakMapHelpers.set;\n\n// `WeakMap.prototype.getOrInsert` method\n// https://github.com/tc39/proposal-upsert\n$({ target: \'WeakMap\', proto: true, real: true, forced: IS_PURE }, {\n getOrInsert: function getOrInsert(key, value) {\n if (has(aWeakMap(this), key)) return get(this, key);\n set(this, key, value);\n return value;\n }\n});\n\n\n/***/ },\n\n/***/ 4979\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar globalThis = __webpack_require__(4576);\nvar getBuiltIn = __webpack_require__(7751);\nvar createPropertyDescriptor = __webpack_require__(6980);\nvar defineProperty = (__webpack_require__(4913).f);\nvar hasOwn = __webpack_require__(9297);\nvar anInstance = __webpack_require__(679);\nvar inheritIfRequired = __webpack_require__(3167);\nvar normalizeStringArgument = __webpack_require__(2603);\nvar DOMExceptionConstants = __webpack_require__(5002);\nvar clearErrorStack = __webpack_require__(8574);\nvar DESCRIPTORS = __webpack_require__(3724);\nvar IS_PURE = __webpack_require__(6395);\n\nvar DOM_EXCEPTION = \'DOMException\';\nvar Error = getBuiltIn(\'Error\');\nvar NativeDOMException = getBuiltIn(DOM_EXCEPTION);\n\nvar $DOMException = function DOMException() {\n anInstance(this, DOMExceptionPrototype);\n var argumentsLength = arguments.length;\n var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);\n var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], \'Error\');\n var that = new NativeDOMException(message, name);\n var error = new Error(message);\n error.name = DOM_EXCEPTION;\n defineProperty(that, \'stack\', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));\n inheritIfRequired(that, this, $DOMException);\n return that;\n};\n\nvar DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype;\n\nvar ERROR_HAS_STACK = \'stack\' in new Error(DOM_EXCEPTION);\nvar DOM_EXCEPTION_HAS_STACK = \'stack\' in new NativeDOMException(1, 2);\n\n// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\nvar descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(globalThis, DOM_EXCEPTION);\n\n// Bun ~ 0.1.1 DOMException have incorrect descriptor and we can\'t redefine it\n// https://github.com/Jarred-Sumner/bun/issues/399\nvar BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable);\n\nvar FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK;\n\n// `DOMException` constructor patch for `.stack` where it\'s required\n// https://webidl.spec.whatwg.org/#es-DOMException-specialness\n$({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }, { // TODO: fix export logic\n DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException\n});\n\nvar PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);\nvar PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;\n\nif (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) {\n if (!IS_PURE) {\n defineProperty(PolyfilledDOMExceptionPrototype, \'constructor\', createPropertyDescriptor(1, PolyfilledDOMException));\n }\n\n for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {\n var constant = DOMExceptionConstants[key];\n var constantName = constant.s;\n if (!hasOwn(PolyfilledDOMException, constantName)) {\n defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c));\n }\n }\n}\n\n\n/***/ },\n\n/***/ 4603\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar defineBuiltIn = __webpack_require__(6840);\nvar uncurryThis = __webpack_require__(9504);\nvar toString = __webpack_require__(655);\nvar validateArgumentsLength = __webpack_require__(2812);\n\nvar $URLSearchParams = URLSearchParams;\nvar URLSearchParamsPrototype = $URLSearchParams.prototype;\nvar append = uncurryThis(URLSearchParamsPrototype.append);\nvar $delete = uncurryThis(URLSearchParamsPrototype[\'delete\']);\nvar forEach = uncurryThis(URLSearchParamsPrototype.forEach);\nvar push = uncurryThis([].push);\nvar params = new $URLSearchParams(\'a=1&a=2&b=3\');\n\nparams[\'delete\'](\'a\', 1);\n// `undefined` case is a Chromium 117 bug\n// https://bugs.chromium.org/p/v8/issues/detail?id=14222\nparams[\'delete\'](\'b\', undefined);\n\nif (params + \'\' !== \'a=2\') {\n defineBuiltIn(URLSearchParamsPrototype, \'delete\', function (name /* , value */) {\n var length = arguments.length;\n var $value = length < 2 ? undefined : arguments[1];\n if (length && $value === undefined) return $delete(this, name);\n var entries = [];\n forEach(this, function (v, k) { // also validates `this`\n push(entries, { key: k, value: v });\n });\n validateArgumentsLength(length, 1);\n var key = toString(name);\n var value = toString($value);\n var index = 0;\n var dindex = 0;\n var found = false;\n var entriesLength = entries.length;\n var entry;\n while (index < entriesLength) {\n entry = entries[index++];\n if (found || entry.key === key) {\n found = true;\n $delete(this, entry.key);\n } else dindex++;\n }\n while (dindex < entriesLength) {\n entry = entries[dindex++];\n if (!(entry.key === key && entry.value === value)) append(this, entry.key, entry.value);\n }\n }, { enumerable: true, unsafe: true });\n}\n\n\n/***/ },\n\n/***/ 7566\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar defineBuiltIn = __webpack_require__(6840);\nvar uncurryThis = __webpack_require__(9504);\nvar toString = __webpack_require__(655);\nvar validateArgumentsLength = __webpack_require__(2812);\n\nvar $URLSearchParams = URLSearchParams;\nvar URLSearchParamsPrototype = $URLSearchParams.prototype;\nvar getAll = uncurryThis(URLSearchParamsPrototype.getAll);\nvar $has = uncurryThis(URLSearchParamsPrototype.has);\nvar params = new $URLSearchParams(\'a=1\');\n\n// `undefined` case is a Chromium 117 bug\n// https://bugs.chromium.org/p/v8/issues/detail?id=14222\nif (params.has(\'a\', 2) || !params.has(\'a\', undefined)) {\n defineBuiltIn(URLSearchParamsPrototype, \'has\', function has(name /* , value */) {\n var length = arguments.length;\n var $value = length < 2 ? undefined : arguments[1];\n if (length && $value === undefined) return $has(this, name);\n var values = getAll(this, name); // also validates `this`\n validateArgumentsLength(length, 1);\n var value = toString($value);\n var index = 0;\n while (index < values.length) {\n if (values[index++] === value) return true;\n } return false;\n }, { enumerable: true, unsafe: true });\n}\n\n\n/***/ },\n\n/***/ 8721\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar DESCRIPTORS = __webpack_require__(3724);\nvar uncurryThis = __webpack_require__(9504);\nvar defineBuiltInAccessor = __webpack_require__(2106);\n\nvar URLSearchParamsPrototype = URLSearchParams.prototype;\nvar forEach = uncurryThis(URLSearchParamsPrototype.forEach);\n\n// `URLSearchParams.prototype.size` getter\n// https://github.com/whatwg/url/pull/734\nif (DESCRIPTORS && !(\'size\' in URLSearchParamsPrototype)) {\n defineBuiltInAccessor(URLSearchParamsPrototype, \'size\', {\n get: function size() {\n var count = 0;\n forEach(this, function () { count++; });\n return count;\n },\n configurable: true,\n enumerable: true\n });\n}\n\n\n/***/ },\n\n/***/ 5781\n(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {\n\n\nvar $ = __webpack_require__(6518);\nvar getBuiltIn = __webpack_require__(7751);\nvar validateArgumentsLength = __webpack_require__(2812);\nvar toString = __webpack_require__(655);\nvar USE_NATIVE_URL = __webpack_require__(7416);\n\nvar URL = getBuiltIn(\'URL\');\n\n// `URL.parse` method\n// https://url.spec.whatwg.org/#dom-url-canparse\n$({ target: \'URL\', stat: true, forced: !USE_NATIVE_URL }, {\n parse: function parse(url) {\n var length = validateArgumentsLength(arguments.length, 1);\n var urlString = toString(url);\n var base = length < 2 || arguments[1] === undefined ? undefined : toString(arguments[1]);\n try {\n return new URL(urlString, base);\n } catch (error) {\n return null;\n }\n }\n});\n\n\n/***/ }\n\n/******/ });\n/************************************************************************/\n/******/ // The module cache\n/******/ var __webpack_module_cache__ = {};\n/******/ \n/******/ // The require function\n/******/ function __webpack_require__(moduleId) {\n/******/ \t// Check if module is in cache\n/******/ \tvar cachedModule = __webpack_module_cache__[moduleId];\n/******/ \tif (cachedModule !== undefined) {\n/******/ \t\treturn cachedModule.exports;\n/******/ \t}\n/******/ \t// Create a new module (and put it into the cache)\n/******/ \tvar module = __webpack_module_cache__[moduleId] = {\n/******/ \t\t// no module.id needed\n/******/ \t\t// no module.loaded needed\n/******/ \t\texports: {}\n/******/ \t};\n/******/ \n/******/ \t// Execute the module function\n/******/ \t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/ \n/******/ \t// Return the exports of the module\n/******/ \treturn module.exports;\n/******/ }\n/******/ \n/************************************************************************/\n/******/ /* webpack/runtime/define property getters */\n/******/ (() => {\n/******/ \t// define getter functions for harmony exports\n/******/ \t__webpack_require__.d = (exports, definition) => {\n/******/ \t\tfor(var key in definition) {\n/******/ \t\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n/******/ \t\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n/******/ \t\t\t}\n/******/ \t\t}\n/******/ \t};\n/******/ })();\n/******/ \n/******/ /* webpack/runtime/hasOwnProperty shorthand */\n/******/ (() => {\n/******/ \t__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))\n/******/ })();\n/******/ \n/************************************************************************/\nvar __webpack_exports__ = {};\n\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.array.push.js\nvar es_array_push = __webpack_require__(4114);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.detached.js\nvar es_array_buffer_detached = __webpack_require__(6573);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.transfer.js\nvar es_array_buffer_transfer = __webpack_require__(8100);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.array-buffer.transfer-to-fixed-length.js\nvar es_array_buffer_transfer_to_fixed_length = __webpack_require__(7936);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.constructor.js\nvar es_iterator_constructor = __webpack_require__(8111);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.reduce.js\nvar es_iterator_reduce = __webpack_require__(8237);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.map.get-or-insert.js\nvar es_map_get_or_insert = __webpack_require__(5367);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.map.get-or-insert-computed.js\nvar es_map_get_or_insert_computed = __webpack_require__(2731);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.math.sum-precise.js\nvar es_math_sum_precise = __webpack_require__(3068);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.typed-array.with.js\nvar es_typed_array_with = __webpack_require__(9577);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.uint8-array.set-from-base64.js\nvar es_uint8_array_set_from_base64 = __webpack_require__(6632);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.uint8-array.set-from-hex.js\nvar es_uint8_array_set_from_hex = __webpack_require__(4226);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.uint8-array.to-base64.js\nvar es_uint8_array_to_base64 = __webpack_require__(9486);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.uint8-array.to-hex.js\nvar es_uint8_array_to_hex = __webpack_require__(456);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/web.url.parse.js\nvar web_url_parse = __webpack_require__(5781);\n;// ./src/shared/util.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");\nconst FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];\nconst LINE_FACTOR = 1.35;\nconst LINE_DESCENT_FACTOR = 0.35;\nconst BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;\nconst RenderingIntentFlag = {\n ANY: 0x01,\n DISPLAY: 0x02,\n PRINT: 0x04,\n SAVE: 0x08,\n ANNOTATIONS_FORMS: 0x10,\n ANNOTATIONS_STORAGE: 0x20,\n ANNOTATIONS_DISABLE: 0x40,\n IS_EDITING: 0x80,\n OPLIST: 0x100\n};\nconst AnnotationMode = {\n DISABLE: 0,\n ENABLE: 1,\n ENABLE_FORMS: 2,\n ENABLE_STORAGE: 3\n};\nconst AnnotationEditorPrefix = "pdfjs_internal_editor_";\nconst AnnotationEditorType = {\n DISABLE: -1,\n NONE: 0,\n FREETEXT: 3,\n HIGHLIGHT: 9,\n STAMP: 13,\n INK: 15,\n POPUP: 16,\n SIGNATURE: 101,\n COMMENT: 102\n};\nconst AnnotationEditorParamsType = {\n RESIZE: 1,\n CREATE: 2,\n FREETEXT_SIZE: 11,\n FREETEXT_COLOR: 12,\n FREETEXT_OPACITY: 13,\n INK_COLOR: 21,\n INK_THICKNESS: 22,\n INK_OPACITY: 23,\n HIGHLIGHT_COLOR: 31,\n HIGHLIGHT_THICKNESS: 32,\n HIGHLIGHT_FREE: 33,\n HIGHLIGHT_SHOW_ALL: 34,\n DRAW_STEP: 41\n};\nconst PermissionFlag = {\n PRINT: 0x04,\n MODIFY_CONTENTS: 0x08,\n COPY: 0x10,\n MODIFY_ANNOTATIONS: 0x20,\n FILL_INTERACTIVE_FORMS: 0x100,\n COPY_FOR_ACCESSIBILITY: 0x200,\n ASSEMBLE: 0x400,\n PRINT_HIGH_QUALITY: 0x800\n};\nconst MeshFigureType = {\n TRIANGLES: 1,\n LATTICE: 2,\n PATCH: 3\n};\nconst TextRenderingMode = {\n FILL: 0,\n STROKE: 1,\n FILL_STROKE: 2,\n INVISIBLE: 3,\n FILL_ADD_TO_PATH: 4,\n STROKE_ADD_TO_PATH: 5,\n FILL_STROKE_ADD_TO_PATH: 6,\n ADD_TO_PATH: 7,\n FILL_STROKE_MASK: 3,\n ADD_TO_PATH_FLAG: 4\n};\nconst ImageKind = {\n GRAYSCALE_1BPP: 1,\n RGB_24BPP: 2,\n RGBA_32BPP: 3\n};\nconst AnnotationType = {\n TEXT: 1,\n LINK: 2,\n FREETEXT: 3,\n LINE: 4,\n SQUARE: 5,\n CIRCLE: 6,\n POLYGON: 7,\n POLYLINE: 8,\n HIGHLIGHT: 9,\n UNDERLINE: 10,\n SQUIGGLY: 11,\n STRIKEOUT: 12,\n STAMP: 13,\n CARET: 14,\n INK: 15,\n POPUP: 16,\n FILEATTACHMENT: 17,\n SOUND: 18,\n MOVIE: 19,\n WIDGET: 20,\n SCREEN: 21,\n PRINTERMARK: 22,\n TRAPNET: 23,\n WATERMARK: 24,\n THREED: 25,\n REDACT: 26\n};\nconst AnnotationReplyType = {\n GROUP: "Group",\n REPLY: "R"\n};\nconst AnnotationFlag = {\n INVISIBLE: 0x01,\n HIDDEN: 0x02,\n PRINT: 0x04,\n NOZOOM: 0x08,\n NOROTATE: 0x10,\n NOVIEW: 0x20,\n READONLY: 0x40,\n LOCKED: 0x80,\n TOGGLENOVIEW: 0x100,\n LOCKEDCONTENTS: 0x200\n};\nconst AnnotationFieldFlag = {\n READONLY: 0x0000001,\n REQUIRED: 0x0000002,\n NOEXPORT: 0x0000004,\n MULTILINE: 0x0001000,\n PASSWORD: 0x0002000,\n NOTOGGLETOOFF: 0x0004000,\n RADIO: 0x0008000,\n PUSHBUTTON: 0x0010000,\n COMBO: 0x0020000,\n EDIT: 0x0040000,\n SORT: 0x0080000,\n FILESELECT: 0x0100000,\n MULTISELECT: 0x0200000,\n DONOTSPELLCHECK: 0x0400000,\n DONOTSCROLL: 0x0800000,\n COMB: 0x1000000,\n RICHTEXT: 0x2000000,\n RADIOSINUNISON: 0x2000000,\n COMMITONSELCHANGE: 0x4000000\n};\nconst AnnotationBorderStyleType = {\n SOLID: 1,\n DASHED: 2,\n BEVELED: 3,\n INSET: 4,\n UNDERLINE: 5\n};\nconst AnnotationActionEventType = {\n E: "Mouse Enter",\n X: "Mouse Exit",\n D: "Mouse Down",\n U: "Mouse Up",\n Fo: "Focus",\n Bl: "Blur",\n PO: "PageOpen",\n PC: "PageClose",\n PV: "PageVisible",\n PI: "PageInvisible",\n K: "Keystroke",\n F: "Format",\n V: "Validate",\n C: "Calculate"\n};\nconst DocumentActionEventType = {\n WC: "WillClose",\n WS: "WillSave",\n DS: "DidSave",\n WP: "WillPrint",\n DP: "DidPrint"\n};\nconst PageActionEventType = {\n O: "PageOpen",\n C: "PageClose"\n};\nconst VerbosityLevel = {\n ERRORS: 0,\n WARNINGS: 1,\n INFOS: 5\n};\nconst OPS = {\n dependency: 1,\n setLineWidth: 2,\n setLineCap: 3,\n setLineJoin: 4,\n setMiterLimit: 5,\n setDash: 6,\n setRenderingIntent: 7,\n setFlatness: 8,\n setGState: 9,\n save: 10,\n restore: 11,\n transform: 12,\n moveTo: 13,\n lineTo: 14,\n curveTo: 15,\n curveTo2: 16,\n curveTo3: 17,\n closePath: 18,\n rectangle: 19,\n stroke: 20,\n closeStroke: 21,\n fill: 22,\n eoFill: 23,\n fillStroke: 24,\n eoFillStroke: 25,\n closeFillStroke: 26,\n closeEOFillStroke: 27,\n endPath: 28,\n clip: 29,\n eoClip: 30,\n beginText: 31,\n endText: 32,\n setCharSpacing: 33,\n setWordSpacing: 34,\n setHScale: 35,\n setLeading: 36,\n setFont: 37,\n setTextRenderingMode: 38,\n setTextRise: 39,\n moveText: 40,\n setLeadingMoveText: 41,\n setTextMatrix: 42,\n nextLine: 43,\n showText: 44,\n showSpacedText: 45,\n nextLineShowText: 46,\n nextLineSetSpacingShowText: 47,\n setCharWidth: 48,\n setCharWidthAndBounds: 49,\n setStrokeColorSpace: 50,\n setFillColorSpace: 51,\n setStrokeColor: 52,\n setStrokeColorN: 53,\n setFillColor: 54,\n setFillColorN: 55,\n setStrokeGray: 56,\n setFillGray: 57,\n setStrokeRGBColor: 58,\n setFillRGBColor: 59,\n setStrokeCMYKColor: 60,\n setFillCMYKColor: 61,\n shadingFill: 62,\n beginInlineImage: 63,\n beginImageData: 64,\n endInlineImage: 65,\n paintXObject: 66,\n markPoint: 67,\n markPointProps: 68,\n beginMarkedContent: 69,\n beginMarkedContentProps: 70,\n endMarkedContent: 71,\n beginCompat: 72,\n endCompat: 73,\n paintFormXObjectBegin: 74,\n paintFormXObjectEnd: 75,\n beginGroup: 76,\n endGroup: 77,\n beginAnnotation: 80,\n endAnnotation: 81,\n paintImageMaskXObject: 83,\n paintImageMaskXObjectGroup: 84,\n paintImageXObject: 85,\n paintInlineImageXObject: 86,\n paintInlineImageXObjectGroup: 87,\n paintImageXObjectRepeat: 88,\n paintImageMaskXObjectRepeat: 89,\n paintSolidColorImageMask: 90,\n constructPath: 91,\n setStrokeTransparent: 92,\n setFillTransparent: 93,\n rawFillPath: 94\n};\nconst DrawOPS = {\n moveTo: 0,\n lineTo: 1,\n curveTo: 2,\n quadraticCurveTo: 3,\n closePath: 4\n};\nconst PasswordResponses = {\n NEED_PASSWORD: 1,\n INCORRECT_PASSWORD: 2\n};\nlet verbosity = VerbosityLevel.WARNINGS;\nfunction setVerbosityLevel(level) {\n if (Number.isInteger(level)) {\n verbosity = level;\n }\n}\nfunction getVerbosityLevel() {\n return verbosity;\n}\nfunction info(msg) {\n if (verbosity >= VerbosityLevel.INFOS) {\n console.info(`Info: ${msg}`);\n }\n}\nfunction warn(msg) {\n if (verbosity >= VerbosityLevel.WARNINGS) {\n console.warn(`Warning: ${msg}`);\n }\n}\nfunction unreachable(msg) {\n throw new Error(msg);\n}\nfunction assert(cond, msg) {\n if (!cond) {\n unreachable(msg);\n }\n}\nfunction _isValidProtocol(url) {\n switch (url?.protocol) {\n case "http:":\n case "https:":\n case "ftp:":\n case "mailto:":\n case "tel:":\n return true;\n default:\n return false;\n }\n}\nfunction createValidAbsoluteUrl(url, baseUrl = null, options = null) {\n if (!url) {\n return null;\n }\n if (options && typeof url === "string") {\n if (options.addDefaultProtocol && url.startsWith("www.")) {\n const dots = url.match(/\\./g);\n if (dots?.length >= 2) {\n url = `http://${url}`;\n }\n }\n if (options.tryConvertEncoding) {\n try {\n url = stringToUTF8String(url);\n } catch {}\n }\n }\n const absoluteUrl = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);\n return _isValidProtocol(absoluteUrl) ? absoluteUrl : null;\n}\nfunction updateUrlHash(url, hash, allowRel = false) {\n const res = URL.parse(url);\n if (res) {\n res.hash = hash;\n return res.href;\n }\n if (allowRel && createValidAbsoluteUrl(url, "http://example.com")) {\n return url.split("#", 1)[0] + `${hash ? `#${hash}` : ""}`;\n }\n return "";\n}\nfunction stripPath(str) {\n return str.substring(str.lastIndexOf("/") + 1);\n}\nfunction shadow(obj, prop, value, nonSerializable = false) {\n Object.defineProperty(obj, prop, {\n value,\n enumerable: !nonSerializable,\n configurable: true,\n writable: false\n });\n return value;\n}\nconst BaseException = function BaseExceptionClosure() {\n function BaseException(message, name) {\n this.message = message;\n this.name = name;\n }\n BaseException.prototype = new Error();\n BaseException.constructor = BaseException;\n return BaseException;\n}();\nclass PasswordException extends BaseException {\n constructor(msg, code) {\n super(msg, "PasswordException");\n this.code = code;\n }\n}\nclass UnknownErrorException extends BaseException {\n constructor(msg, details) {\n super(msg, "UnknownErrorException");\n this.details = details;\n }\n}\nclass InvalidPDFException extends BaseException {\n constructor(msg) {\n super(msg, "InvalidPDFException");\n }\n}\nclass ResponseException extends BaseException {\n constructor(msg, status, missing) {\n super(msg, "ResponseException");\n this.status = status;\n this.missing = missing;\n }\n}\nclass FormatError extends BaseException {\n constructor(msg) {\n super(msg, "FormatError");\n }\n}\nclass AbortException extends BaseException {\n constructor(msg) {\n super(msg, "AbortException");\n }\n}\nfunction bytesToString(bytes) {\n if (typeof bytes !== "object" || bytes?.length === undefined) {\n unreachable("Invalid argument for bytesToString");\n }\n const length = bytes.length;\n const MAX_ARGUMENT_COUNT = 8192;\n if (length < MAX_ARGUMENT_COUNT) {\n return String.fromCharCode.apply(null, bytes);\n }\n const strBuf = [];\n for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {\n const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);\n const chunk = bytes.subarray(i, chunkEnd);\n strBuf.push(String.fromCharCode.apply(null, chunk));\n }\n return strBuf.join("");\n}\nfunction stringToBytes(str) {\n if (typeof str !== "string") {\n unreachable("Invalid argument for stringToBytes");\n }\n const length = str.length;\n const bytes = new Uint8Array(length);\n for (let i = 0; i < length; ++i) {\n bytes[i] = str.charCodeAt(i) & 0xff;\n }\n return bytes;\n}\nfunction string32(value) {\n return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);\n}\nfunction objectSize(obj) {\n return Object.keys(obj).length;\n}\nfunction isLittleEndian() {\n const buffer8 = new Uint8Array(4);\n buffer8[0] = 1;\n const view32 = new Uint32Array(buffer8.buffer, 0, 1);\n return view32[0] === 1;\n}\nfunction isEvalSupported() {\n try {\n new Function("");\n return true;\n } catch {\n return false;\n }\n}\nclass FeatureTest {\n static get isLittleEndian() {\n return shadow(this, "isLittleEndian", isLittleEndian());\n }\n static get isEvalSupported() {\n return shadow(this, "isEvalSupported", isEvalSupported());\n }\n static get isOffscreenCanvasSupported() {\n return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");\n }\n static get isImageDecoderSupported() {\n return shadow(this, "isImageDecoderSupported", typeof ImageDecoder !== "undefined");\n }\n static get isFloat16ArraySupported() {\n return shadow(this, "isFloat16ArraySupported", typeof Float16Array !== "undefined");\n }\n static get isSanitizerSupported() {\n return shadow(this, "isSanitizerSupported", typeof Sanitizer !== "undefined");\n }\n static get platform() {\n const {\n platform,\n userAgent\n } = navigator;\n return shadow(this, "platform", {\n isAndroid: userAgent.includes("Android"),\n isLinux: platform.includes("Linux"),\n isMac: platform.includes("Mac"),\n isWindows: platform.includes("Win"),\n isFirefox: userAgent.includes("Firefox")\n });\n }\n static get isCSSRoundSupported() {\n return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));\n }\n}\nconst hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0"));\nclass Util {\n static makeHexColor(r, g, b) {\n return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;\n }\n static domMatrixToTransform(dm) {\n return [dm.a, dm.b, dm.c, dm.d, dm.e, dm.f];\n }\n static scaleMinMax(transform, minMax) {\n let temp;\n if (transform[0]) {\n if (transform[0] < 0) {\n temp = minMax[0];\n minMax[0] = minMax[2];\n minMax[2] = temp;\n }\n minMax[0] *= transform[0];\n minMax[2] *= transform[0];\n if (transform[3] < 0) {\n temp = minMax[1];\n minMax[1] = minMax[3];\n minMax[3] = temp;\n }\n minMax[1] *= transform[3];\n minMax[3] *= transform[3];\n } else {\n temp = minMax[0];\n minMax[0] = minMax[1];\n minMax[1] = temp;\n temp = minMax[2];\n minMax[2] = minMax[3];\n minMax[3] = temp;\n if (transform[1] < 0) {\n temp = minMax[1];\n minMax[1] = minMax[3];\n minMax[3] = temp;\n }\n minMax[1] *= transform[1];\n minMax[3] *= transform[1];\n if (transform[2] < 0) {\n temp = minMax[0];\n minMax[0] = minMax[2];\n minMax[2] = temp;\n }\n minMax[0] *= transform[2];\n minMax[2] *= transform[2];\n }\n minMax[0] += transform[4];\n minMax[1] += transform[5];\n minMax[2] += transform[4];\n minMax[3] += transform[5];\n }\n static transform(m1, m2) {\n return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];\n }\n static multiplyByDOMMatrix(m, md) {\n return [m[0] * md.a + m[2] * md.b, m[1] * md.a + m[3] * md.b, m[0] * md.c + m[2] * md.d, m[1] * md.c + m[3] * md.d, m[0] * md.e + m[2] * md.f + m[4], m[1] * md.e + m[3] * md.f + m[5]];\n }\n static applyTransform(p, m, pos = 0) {\n const p0 = p[pos];\n const p1 = p[pos + 1];\n p[pos] = p0 * m[0] + p1 * m[2] + m[4];\n p[pos + 1] = p0 * m[1] + p1 * m[3] + m[5];\n }\n static applyTransformToBezier(p, transform, pos = 0) {\n const m0 = transform[0];\n const m1 = transform[1];\n const m2 = transform[2];\n const m3 = transform[3];\n const m4 = transform[4];\n const m5 = transform[5];\n for (let i = 0; i < 6; i += 2) {\n const pI = p[pos + i];\n const pI1 = p[pos + i + 1];\n p[pos + i] = pI * m0 + pI1 * m2 + m4;\n p[pos + i + 1] = pI * m1 + pI1 * m3 + m5;\n }\n }\n static applyInverseTransform(p, m) {\n const p0 = p[0];\n const p1 = p[1];\n const d = m[0] * m[3] - m[1] * m[2];\n p[0] = (p0 * m[3] - p1 * m[2] + m[2] * m[5] - m[4] * m[3]) / d;\n p[1] = (-p0 * m[1] + p1 * m[0] + m[4] * m[1] - m[5] * m[0]) / d;\n }\n static axialAlignedBoundingBox(rect, transform, output) {\n const m0 = transform[0];\n const m1 = transform[1];\n const m2 = transform[2];\n const m3 = transform[3];\n const m4 = transform[4];\n const m5 = transform[5];\n const r0 = rect[0];\n const r1 = rect[1];\n const r2 = rect[2];\n const r3 = rect[3];\n let a0 = m0 * r0 + m4;\n let a2 = a0;\n let a1 = m0 * r2 + m4;\n let a3 = a1;\n let b0 = m3 * r1 + m5;\n let b2 = b0;\n let b1 = m3 * r3 + m5;\n let b3 = b1;\n if (m1 !== 0 || m2 !== 0) {\n const m1r0 = m1 * r0;\n const m1r2 = m1 * r2;\n const m2r1 = m2 * r1;\n const m2r3 = m2 * r3;\n a0 += m2r1;\n a3 += m2r1;\n a1 += m2r3;\n a2 += m2r3;\n b0 += m1r0;\n b3 += m1r0;\n b1 += m1r2;\n b2 += m1r2;\n }\n output[0] = Math.min(output[0], a0, a1, a2, a3);\n output[1] = Math.min(output[1], b0, b1, b2, b3);\n output[2] = Math.max(output[2], a0, a1, a2, a3);\n output[3] = Math.max(output[3], b0, b1, b2, b3);\n }\n static inverseTransform(m) {\n const d = m[0] * m[3] - m[1] * m[2];\n return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];\n }\n static singularValueDecompose2dScale(matrix, output) {\n const m0 = matrix[0];\n const m1 = matrix[1];\n const m2 = matrix[2];\n const m3 = matrix[3];\n const a = m0 ** 2 + m1 ** 2;\n const b = m0 * m2 + m1 * m3;\n const c = m2 ** 2 + m3 ** 2;\n const first = (a + c) / 2;\n const second = Math.sqrt(first ** 2 - (a * c - b ** 2));\n output[0] = Math.sqrt(first + second || 1);\n output[1] = Math.sqrt(first - second || 1);\n }\n static normalizeRect(rect) {\n const r = rect.slice(0);\n if (rect[0] > rect[2]) {\n r[0] = rect[2];\n r[2] = rect[0];\n }\n if (rect[1] > rect[3]) {\n r[1] = rect[3];\n r[3] = rect[1];\n }\n return r;\n }\n static intersect(rect1, rect2) {\n const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));\n const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));\n if (xLow > xHigh) {\n return null;\n }\n const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));\n const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));\n if (yLow > yHigh) {\n return null;\n }\n return [xLow, yLow, xHigh, yHigh];\n }\n static pointBoundingBox(x, y, minMax) {\n minMax[0] = Math.min(minMax[0], x);\n minMax[1] = Math.min(minMax[1], y);\n minMax[2] = Math.max(minMax[2], x);\n minMax[3] = Math.max(minMax[3], y);\n }\n static rectBoundingBox(x0, y0, x1, y1, minMax) {\n minMax[0] = Math.min(minMax[0], x0, x1);\n minMax[1] = Math.min(minMax[1], y0, y1);\n minMax[2] = Math.max(minMax[2], x0, x1);\n minMax[3] = Math.max(minMax[3], y0, y1);\n }\n static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) {\n if (t <= 0 || t >= 1) {\n return;\n }\n const mt = 1 - t;\n const tt = t * t;\n const ttt = tt * t;\n const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3;\n const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3;\n minMax[0] = Math.min(minMax[0], x);\n minMax[1] = Math.min(minMax[1], y);\n minMax[2] = Math.max(minMax[2], x);\n minMax[3] = Math.max(minMax[3], y);\n }\n static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) {\n if (Math.abs(a) < 1e-12) {\n if (Math.abs(b) >= 1e-12) {\n this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax);\n }\n return;\n }\n const delta = b ** 2 - 4 * c * a;\n if (delta < 0) {\n return;\n }\n const sqrtDelta = Math.sqrt(delta);\n const a2 = 2 * a;\n this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax);\n this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax);\n }\n static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) {\n minMax[0] = Math.min(minMax[0], x0, x3);\n minMax[1] = Math.min(minMax[1], y0, y3);\n minMax[2] = Math.max(minMax[2], x0, x3);\n minMax[3] = Math.max(minMax[3], y0, y3);\n this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax);\n this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-y0 + 3 * (y1 - y2) + y3), 6 * (y0 - 2 * y1 + y2), 3 * (y1 - y0), minMax);\n }\n}\nconst PDFStringTranslateTable = (/* unused pure expression or super */ null && ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac]));\nfunction stringToPDFString(str, keepEscapeSequence = false) {\n if (str[0] >= "\\xEF") {\n let encoding;\n if (str[0] === "\\xFE" && str[1] === "\\xFF") {\n encoding = "utf-16be";\n if (str.length % 2 === 1) {\n str = str.slice(0, -1);\n }\n } else if (str[0] === "\\xFF" && str[1] === "\\xFE") {\n encoding = "utf-16le";\n if (str.length % 2 === 1) {\n str = str.slice(0, -1);\n }\n } else if (str[0] === "\\xEF" && str[1] === "\\xBB" && str[2] === "\\xBF") {\n encoding = "utf-8";\n }\n if (encoding) {\n try {\n const decoder = new TextDecoder(encoding, {\n fatal: true\n });\n const buffer = stringToBytes(str);\n const decoded = decoder.decode(buffer);\n if (keepEscapeSequence || !decoded.includes("\\x1b")) {\n return decoded;\n }\n return decoded.replaceAll(/\\x1b[^\\x1b]*(?:\\x1b|$)/g, "");\n } catch (ex) {\n warn(`stringToPDFString: "${ex}".`);\n }\n }\n }\n const strBuf = [];\n for (let i = 0, ii = str.length; i < ii; i++) {\n const charCode = str.charCodeAt(i);\n if (!keepEscapeSequence && charCode === 0x1b) {\n while (++i < ii && str.charCodeAt(i) !== 0x1b) {}\n continue;\n }\n const code = PDFStringTranslateTable[charCode];\n strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));\n }\n return strBuf.join("");\n}\nfunction stringToUTF8String(str) {\n return decodeURIComponent(escape(str));\n}\nfunction utf8StringToString(str) {\n return unescape(encodeURIComponent(str));\n}\nfunction isArrayEqual(arr1, arr2) {\n if (arr1.length !== arr2.length) {\n return false;\n }\n for (let i = 0, ii = arr1.length; i < ii; i++) {\n if (arr1[i] !== arr2[i]) {\n return false;\n }\n }\n return true;\n}\nfunction getModificationDate(date = new Date()) {\n if (!(date instanceof Date)) {\n date = new Date(date);\n }\n const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];\n return buffer.join("");\n}\nlet NormalizeRegex = null;\nlet NormalizationMap = null;\nfunction normalizeUnicode(str) {\n if (!NormalizeRegex) {\n NormalizeRegex = /([\\u00a0\\u00b5\\u037e\\u0eb3\\u2000-\\u200a\\u202f\\u2126\\ufb00-\\ufb04\\ufb06\\ufb20-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40-\\ufb41\\ufb43-\\ufb44\\ufb46-\\ufba1\\ufba4-\\ufba9\\ufbae-\\ufbb1\\ufbd3-\\ufbdc\\ufbde-\\ufbe7\\ufbea-\\ufbf8\\ufbfc-\\ufbfd\\ufc00-\\ufc5d\\ufc64-\\ufcf1\\ufcf5-\\ufd3d\\ufd88\\ufdf4\\ufdfa-\\ufdfb\\ufe71\\ufe77\\ufe79\\ufe7b\\ufe7d]+)|(\\ufb05+)/gu;\n NormalizationMap = new Map([["ſt", "ſt"]]);\n }\n return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2));\n}\nfunction getUuid() {\n if (typeof crypto.randomUUID === "function") {\n return crypto.randomUUID();\n }\n const buf = new Uint8Array(32);\n crypto.getRandomValues(buf);\n return bytesToString(buf);\n}\nconst AnnotationPrefix = "pdfjs_internal_id_";\nfunction _isValidExplicitDest(validRef, validName, dest) {\n if (!Array.isArray(dest) || dest.length < 2) {\n return false;\n }\n const [page, zoom, ...args] = dest;\n if (!validRef(page) && !Number.isInteger(page)) {\n return false;\n }\n if (!validName(zoom)) {\n return false;\n }\n const argsLen = args.length;\n let allowNull = true;\n switch (zoom.name) {\n case "XYZ":\n if (argsLen < 2 || argsLen > 3) {\n return false;\n }\n break;\n case "Fit":\n case "FitB":\n return argsLen === 0;\n case "FitH":\n case "FitBH":\n case "FitV":\n case "FitBV":\n if (argsLen > 1) {\n return false;\n }\n break;\n case "FitR":\n if (argsLen !== 4) {\n return false;\n }\n allowNull = false;\n break;\n default:\n return false;\n }\n for (const arg of args) {\n if (typeof arg === "number" || allowNull && arg === null) {\n continue;\n }\n return false;\n }\n return true;\n}\nconst makeArr = () => [];\nconst makeMap = () => new Map();\nconst makeObj = () => Object.create(null);\nfunction MathClamp(v, min, max) {\n return Math.min(Math.max(v, min), max);\n}\nif (typeof Response.prototype.bytes !== "function") {\n Response.prototype.bytes = async function () {\n return new Uint8Array(await this.arrayBuffer());\n };\n}\nif (typeof AbortSignal.any !== "function") {\n AbortSignal.any = function (iterable) {\n const ac = new AbortController();\n const {\n signal\n } = ac;\n for (const s of iterable) {\n if (s.aborted) {\n ac.abort(s.reason);\n return signal;\n }\n }\n for (const s of iterable) {\n s.addEventListener("abort", () => {\n ac.abort(s.reason);\n }, {\n signal\n });\n }\n return signal;\n };\n}\n\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.every.js\nvar es_iterator_every = __webpack_require__(1148);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.map.js\nvar es_iterator_map = __webpack_require__(1701);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.delete.js\nvar web_url_search_params_delete = __webpack_require__(4603);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.has.js\nvar web_url_search_params_has = __webpack_require__(7566);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/web.url-search-params.size.js\nvar web_url_search_params_size = __webpack_require__(8721);\n;// ./src/display/xfa_text.js\n\nclass XfaText {\n static textContent(xfa) {\n const items = [];\n const output = {\n items,\n styles: Object.create(null)\n };\n function walk(node) {\n if (!node) {\n return;\n }\n let str = null;\n const name = node.name;\n if (name === "#text") {\n str = node.value;\n } else if (!XfaText.shouldBuildText(name)) {\n return;\n } else if (node?.attributes?.textContent) {\n str = node.attributes.textContent;\n } else if (node.value) {\n str = node.value;\n }\n if (str !== null) {\n items.push({\n str\n });\n }\n if (!node.children) {\n return;\n }\n for (const child of node.children) {\n walk(child);\n }\n }\n walk(xfa);\n return output;\n }\n static shouldBuildText(name) {\n return !(name === "textarea" || name === "input" || name === "option" || name === "select");\n }\n}\n\n;// ./src/display/xfa_layer.js\n\n\nclass XfaLayer {\n static setupStorage(html, id, element, storage, intent) {\n const storedData = storage.getValue(id, {\n value: null\n });\n switch (element.name) {\n case "textarea":\n if (storedData.value !== null) {\n html.textContent = storedData.value;\n }\n if (intent === "print") {\n break;\n }\n html.addEventListener("input", event => {\n storage.setValue(id, {\n value: event.target.value\n });\n });\n break;\n case "input":\n if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {\n if (storedData.value === element.attributes.xfaOn) {\n html.setAttribute("checked", true);\n } else if (storedData.value === element.attributes.xfaOff) {\n html.removeAttribute("checked");\n }\n if (intent === "print") {\n break;\n }\n html.addEventListener("change", event => {\n storage.setValue(id, {\n value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")\n });\n });\n } else {\n if (storedData.value !== null) {\n html.setAttribute("value", storedData.value);\n }\n if (intent === "print") {\n break;\n }\n html.addEventListener("input", event => {\n storage.setValue(id, {\n value: event.target.value\n });\n });\n }\n break;\n case "select":\n if (storedData.value !== null) {\n html.setAttribute("value", storedData.value);\n for (const option of element.children) {\n if (option.attributes.value === storedData.value) {\n option.attributes.selected = true;\n } else if (option.attributes.hasOwnProperty("selected")) {\n delete option.attributes.selected;\n }\n }\n }\n html.addEventListener("input", event => {\n const options = event.target.options;\n const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;\n storage.setValue(id, {\n value\n });\n });\n break;\n }\n }\n static setAttributes({\n html,\n element,\n storage = null,\n intent,\n linkService\n }) {\n const {\n attributes\n } = element;\n const isHTMLAnchorElement = html instanceof HTMLAnchorElement;\n if (attributes.type === "radio") {\n attributes.name = `${attributes.name}-${intent}`;\n }\n for (const [key, value] of Object.entries(attributes)) {\n if (value === null || value === undefined) {\n continue;\n }\n switch (key) {\n case "class":\n if (value.length) {\n html.setAttribute(key, value.join(" "));\n }\n break;\n case "dataId":\n break;\n case "id":\n html.setAttribute("data-element-id", value);\n break;\n case "style":\n Object.assign(html.style, value);\n break;\n case "textContent":\n html.textContent = value;\n break;\n default:\n if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {\n html.setAttribute(key, value);\n }\n }\n }\n if (isHTMLAnchorElement) {\n linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);\n }\n if (storage && attributes.dataId) {\n this.setupStorage(html, attributes.dataId, element, storage);\n }\n }\n static render(parameters) {\n const storage = parameters.annotationStorage;\n const linkService = parameters.linkService;\n const root = parameters.xfaHtml;\n const intent = parameters.intent || "display";\n const rootHtml = document.createElement(root.name);\n if (root.attributes) {\n this.setAttributes({\n html: rootHtml,\n element: root,\n intent,\n linkService\n });\n }\n const isNotForRichText = intent !== "richText";\n const rootDiv = parameters.div;\n rootDiv.append(rootHtml);\n if (parameters.viewport) {\n const transform = `matrix(${parameters.viewport.transform.join(",")})`;\n rootDiv.style.transform = transform;\n }\n if (isNotForRichText) {\n rootDiv.setAttribute("class", "xfaLayer xfaFont");\n }\n const textDivs = [];\n if (root.children.length === 0) {\n if (root.value) {\n const node = document.createTextNode(root.value);\n rootHtml.append(node);\n if (isNotForRichText && XfaText.shouldBuildText(root.name)) {\n textDivs.push(node);\n }\n }\n return {\n textDivs\n };\n }\n const stack = [[root, -1, rootHtml]];\n while (stack.length > 0) {\n const [parent, i, html] = stack.at(-1);\n if (i + 1 === parent.children.length) {\n stack.pop();\n continue;\n }\n const child = parent.children[++stack.at(-1)[1]];\n if (child === null) {\n continue;\n }\n const {\n name\n } = child;\n if (name === "#text") {\n const node = document.createTextNode(child.value);\n textDivs.push(node);\n html.append(node);\n continue;\n }\n const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);\n html.append(childHtml);\n if (child.attributes) {\n this.setAttributes({\n html: childHtml,\n element: child,\n storage,\n intent,\n linkService\n });\n }\n if (child.children?.length > 0) {\n stack.push([child, -1, childHtml]);\n } else if (child.value) {\n const node = document.createTextNode(child.value);\n if (isNotForRichText && XfaText.shouldBuildText(name)) {\n textDivs.push(node);\n }\n childHtml.append(node);\n }\n }\n for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {\n el.setAttribute("readOnly", true);\n }\n return {\n textDivs\n };\n }\n static update(parameters) {\n const transform = `matrix(${parameters.viewport.transform.join(",")})`;\n parameters.div.style.transform = transform;\n parameters.div.hidden = false;\n }\n}\n\n;// ./src/display/display_utils.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst SVG_NS = "http://www.w3.org/2000/svg";\nclass PixelsPerInch {\n static CSS = 96.0;\n static PDF = 72.0;\n static PDF_TO_CSS_UNITS = this.CSS / this.PDF;\n}\nasync function fetchData(url, type = "text") {\n if (isValidFetchUrl(url, document.baseURI)) {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n switch (type) {\n case "blob":\n return response.blob();\n case "bytes":\n return response.bytes();\n case "json":\n return response.json();\n }\n return response.text();\n }\n return new Promise((resolve, reject) => {\n const request = new XMLHttpRequest();\n request.open("GET", url, true);\n request.responseType = type === "bytes" ? "arraybuffer" : type;\n request.onreadystatechange = () => {\n if (request.readyState !== XMLHttpRequest.DONE) {\n return;\n }\n if (request.status === 200 || request.status === 0) {\n switch (type) {\n case "bytes":\n resolve(new Uint8Array(request.response));\n return;\n case "blob":\n case "json":\n resolve(request.response);\n return;\n }\n resolve(request.responseText);\n return;\n }\n reject(new Error(request.statusText));\n };\n request.send(null);\n });\n}\nclass PageViewport {\n constructor({\n viewBox,\n userUnit,\n scale,\n rotation,\n offsetX = 0,\n offsetY = 0,\n dontFlip = false\n }) {\n this.viewBox = viewBox;\n this.userUnit = userUnit;\n this.scale = scale;\n this.rotation = rotation;\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n scale *= userUnit;\n const centerX = (viewBox[2] + viewBox[0]) / 2;\n const centerY = (viewBox[3] + viewBox[1]) / 2;\n let rotateA, rotateB, rotateC, rotateD;\n rotation %= 360;\n if (rotation < 0) {\n rotation += 360;\n }\n switch (rotation) {\n case 180:\n rotateA = -1;\n rotateB = 0;\n rotateC = 0;\n rotateD = 1;\n break;\n case 90:\n rotateA = 0;\n rotateB = 1;\n rotateC = 1;\n rotateD = 0;\n break;\n case 270:\n rotateA = 0;\n rotateB = -1;\n rotateC = -1;\n rotateD = 0;\n break;\n case 0:\n rotateA = 1;\n rotateB = 0;\n rotateC = 0;\n rotateD = -1;\n break;\n default:\n throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");\n }\n if (dontFlip) {\n rotateC = -rotateC;\n rotateD = -rotateD;\n }\n let offsetCanvasX, offsetCanvasY;\n let width, height;\n if (rotateA === 0) {\n offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;\n offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;\n width = (viewBox[3] - viewBox[1]) * scale;\n height = (viewBox[2] - viewBox[0]) * scale;\n } else {\n offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;\n offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;\n width = (viewBox[2] - viewBox[0]) * scale;\n height = (viewBox[3] - viewBox[1]) * scale;\n }\n this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];\n this.width = width;\n this.height = height;\n }\n get rawDims() {\n const dims = this.viewBox;\n return shadow(this, "rawDims", {\n pageWidth: dims[2] - dims[0],\n pageHeight: dims[3] - dims[1],\n pageX: dims[0],\n pageY: dims[1]\n });\n }\n clone({\n scale = this.scale,\n rotation = this.rotation,\n offsetX = this.offsetX,\n offsetY = this.offsetY,\n dontFlip = false\n } = {}) {\n return new PageViewport({\n viewBox: this.viewBox.slice(),\n userUnit: this.userUnit,\n scale,\n rotation,\n offsetX,\n offsetY,\n dontFlip\n });\n }\n convertToViewportPoint(x, y) {\n const p = [x, y];\n Util.applyTransform(p, this.transform);\n return p;\n }\n convertToViewportRectangle(rect) {\n const topLeft = [rect[0], rect[1]];\n Util.applyTransform(topLeft, this.transform);\n const bottomRight = [rect[2], rect[3]];\n Util.applyTransform(bottomRight, this.transform);\n return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];\n }\n convertToPdfPoint(x, y) {\n const p = [x, y];\n Util.applyInverseTransform(p, this.transform);\n return p;\n }\n}\nclass RenderingCancelledException extends BaseException {\n constructor(msg, extraDelay = 0) {\n super(msg, "RenderingCancelledException");\n this.extraDelay = extraDelay;\n }\n}\nfunction isDataScheme(url) {\n const ii = url.length;\n let i = 0;\n while (i < ii && url[i].trim() === "") {\n i++;\n }\n return url.substring(i, i + 5).toLowerCase() === "data:";\n}\nfunction isPdfFile(filename) {\n return typeof filename === "string" && /\\.pdf$/i.test(filename);\n}\nfunction getFilenameFromUrl(url) {\n [url] = url.split(/[#?]/, 1);\n return stripPath(url);\n}\nfunction getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {\n if (typeof url !== "string") {\n return defaultFilename;\n }\n if (isDataScheme(url)) {\n warn(\'getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.\');\n return defaultFilename;\n }\n const getURL = urlString => {\n try {\n return new URL(urlString);\n } catch {\n try {\n return new URL(decodeURIComponent(urlString));\n } catch {\n try {\n return new URL(urlString, "https://foo.bar");\n } catch {\n try {\n return new URL(decodeURIComponent(urlString), "https://foo.bar");\n } catch {\n return null;\n }\n }\n }\n }\n };\n const newURL = getURL(url);\n if (!newURL) {\n return defaultFilename;\n }\n const decode = name => {\n try {\n let decoded = decodeURIComponent(name);\n if (decoded.includes("/")) {\n decoded = stripPath(decoded);\n if (/^\\.pdf$/i.test(decoded)) {\n return name;\n }\n }\n return decoded;\n } catch {\n return name;\n }\n };\n const pdfRegex = /\\.pdf$/i;\n const filename = stripPath(newURL.pathname);\n if (pdfRegex.test(filename)) {\n return decode(filename);\n }\n if (newURL.searchParams.size > 0) {\n const getLast = iterator => [...iterator].findLast(v => pdfRegex.test(v));\n const name = getLast(newURL.searchParams.values()) ?? getLast(newURL.searchParams.keys());\n if (name) {\n return decode(name);\n }\n }\n if (newURL.hash) {\n const reFilename = /[^/?#=]+\\.pdf\\b(?!.*\\.pdf\\b)/i;\n const hashFilename = reFilename.exec(newURL.hash);\n if (hashFilename) {\n return decode(hashFilename[0]);\n }\n }\n return defaultFilename;\n}\nclass StatTimer {\n started = Object.create(null);\n times = [];\n time(name) {\n if (name in this.started) {\n warn(`Timer is already running for ${name}`);\n }\n this.started[name] = Date.now();\n }\n timeEnd(name) {\n if (!(name in this.started)) {\n warn(`Timer has not been started for ${name}`);\n }\n this.times.push({\n name,\n start: this.started[name],\n end: Date.now()\n });\n delete this.started[name];\n }\n toString() {\n const outBuf = [];\n let longest = 0;\n for (const {\n name\n } of this.times) {\n longest = Math.max(name.length, longest);\n }\n for (const {\n name,\n start,\n end\n } of this.times) {\n outBuf.push(`${name.padEnd(longest)} ${end - start}ms\\n`);\n }\n return outBuf.join("");\n }\n}\nfunction isValidFetchUrl(url, baseUrl) {\n const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);\n return /https?:/.test(res?.protocol ?? "");\n}\nfunction noContextMenu(e) {\n e.preventDefault();\n}\nfunction stopEvent(e) {\n e.preventDefault();\n e.stopPropagation();\n}\nfunction deprecated(details) {\n console.log("Deprecated API usage: " + details);\n}\nclass PDFDateString {\n static #regex;\n static toDateObject(input) {\n if (input instanceof Date) {\n return input;\n }\n if (!input || typeof input !== "string") {\n return null;\n }\n this.#regex ||= new RegExp("^D:" + "(\\\\d{4})" + "(\\\\d{2})?" + "(\\\\d{2})?" + "(\\\\d{2})?" + "(\\\\d{2})?" + "(\\\\d{2})?" + "([Z|+|-])?" + "(\\\\d{2})?" + "\'?" + "(\\\\d{2})?" + "\'?");\n const matches = this.#regex.exec(input);\n if (!matches) {\n return null;\n }\n const year = parseInt(matches[1], 10);\n let month = parseInt(matches[2], 10);\n month = month >= 1 && month <= 12 ? month - 1 : 0;\n let day = parseInt(matches[3], 10);\n day = day >= 1 && day <= 31 ? day : 1;\n let hour = parseInt(matches[4], 10);\n hour = hour >= 0 && hour <= 23 ? hour : 0;\n let minute = parseInt(matches[5], 10);\n minute = minute >= 0 && minute <= 59 ? minute : 0;\n let second = parseInt(matches[6], 10);\n second = second >= 0 && second <= 59 ? second : 0;\n const universalTimeRelation = matches[7] || "Z";\n let offsetHour = parseInt(matches[8], 10);\n offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;\n let offsetMinute = parseInt(matches[9], 10) || 0;\n offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;\n if (universalTimeRelation === "-") {\n hour += offsetHour;\n minute += offsetMinute;\n } else if (universalTimeRelation === "+") {\n hour -= offsetHour;\n minute -= offsetMinute;\n }\n return new Date(Date.UTC(year, month, day, hour, minute, second));\n }\n}\nfunction getXfaPageViewport(xfaPage, {\n scale = 1,\n rotation = 0\n}) {\n const {\n width,\n height\n } = xfaPage.attributes.style;\n const viewBox = [0, 0, parseInt(width), parseInt(height)];\n return new PageViewport({\n viewBox,\n userUnit: 1,\n scale,\n rotation\n });\n}\nfunction getRGB(color) {\n if (color.startsWith("#")) {\n const colorRGB = parseInt(color.slice(1), 16);\n return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];\n }\n if (color.startsWith("rgb(")) {\n return color.slice(4, -1).split(",").map(x => parseInt(x));\n }\n if (color.startsWith("rgba(")) {\n return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);\n }\n warn(`Not a valid color format: "${color}"`);\n return [0, 0, 0];\n}\nfunction getColorValues(colors) {\n const span = document.createElement("span");\n span.style.visibility = "hidden";\n span.style.colorScheme = "only light";\n document.body.append(span);\n for (const name of colors.keys()) {\n span.style.color = name;\n const computedColor = window.getComputedStyle(span).color;\n colors.set(name, getRGB(computedColor));\n }\n span.remove();\n}\nfunction getCurrentTransform(ctx) {\n const {\n a,\n b,\n c,\n d,\n e,\n f\n } = ctx.getTransform();\n return [a, b, c, d, e, f];\n}\nfunction getCurrentTransformInverse(ctx) {\n const {\n a,\n b,\n c,\n d,\n e,\n f\n } = ctx.getTransform().invertSelf();\n return [a, b, c, d, e, f];\n}\nfunction setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {\n if (viewport instanceof PageViewport) {\n const {\n pageWidth,\n pageHeight\n } = viewport.rawDims;\n const {\n style\n } = div;\n const useRound = FeatureTest.isCSSRoundSupported;\n const w = `var(--total-scale-factor) * ${pageWidth}px`,\n h = `var(--total-scale-factor) * ${pageHeight}px`;\n const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x))` : `calc(${w})`,\n heightStr = useRound ? `round(down, ${h}, var(--scale-round-y))` : `calc(${h})`;\n if (!mustFlip || viewport.rotation % 180 === 0) {\n style.width = widthStr;\n style.height = heightStr;\n } else {\n style.width = heightStr;\n style.height = widthStr;\n }\n }\n if (mustRotate) {\n div.setAttribute("data-main-rotation", viewport.rotation);\n }\n}\nclass OutputScale {\n constructor() {\n const {\n pixelRatio\n } = OutputScale;\n this.sx = pixelRatio;\n this.sy = pixelRatio;\n }\n get scaled() {\n return this.sx !== 1 || this.sy !== 1;\n }\n get symmetric() {\n return this.sx === this.sy;\n }\n limitCanvas(width, height, maxPixels, maxDim, capAreaFactor = -1) {\n let maxAreaScale = Infinity,\n maxWidthScale = Infinity,\n maxHeightScale = Infinity;\n maxPixels = OutputScale.capPixels(maxPixels, capAreaFactor);\n if (maxPixels > 0) {\n maxAreaScale = Math.sqrt(maxPixels / (width * height));\n }\n if (maxDim !== -1) {\n maxWidthScale = maxDim / width;\n maxHeightScale = maxDim / height;\n }\n const maxScale = Math.min(maxAreaScale, maxWidthScale, maxHeightScale);\n if (this.sx > maxScale || this.sy > maxScale) {\n this.sx = maxScale;\n this.sy = maxScale;\n return true;\n }\n return false;\n }\n static get pixelRatio() {\n return globalThis.devicePixelRatio || 1;\n }\n static capPixels(maxPixels, capAreaFactor) {\n if (capAreaFactor >= 0) {\n const winPixels = Math.ceil(window.screen.availWidth * window.screen.availHeight * this.pixelRatio ** 2 * (1 + capAreaFactor / 100));\n return maxPixels > 0 ? Math.min(maxPixels, winPixels) : winPixels;\n }\n return maxPixels;\n }\n}\nconst SupportedImageMimeTypes = ["image/apng", "image/avif", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/svg+xml", "image/webp", "image/x-icon"];\nclass ColorScheme {\n static get isDarkMode() {\n return shadow(this, "isDarkMode", !!window?.matchMedia?.("(prefers-color-scheme: dark)").matches);\n }\n}\nclass CSSConstants {\n static get commentForegroundColor() {\n const element = document.createElement("span");\n element.classList.add("comment", "sidebar");\n const {\n style\n } = element;\n style.width = style.height = "0";\n style.display = "none";\n style.color = "var(--comment-fg-color)";\n document.body.append(element);\n const {\n color\n } = window.getComputedStyle(element);\n element.remove();\n return shadow(this, "commentForegroundColor", getRGB(color));\n }\n}\nfunction applyOpacity(r, g, b, opacity) {\n opacity = MathClamp(opacity ?? 1, 0, 1);\n const white = 255 * (1 - opacity);\n r = Math.round(r * opacity + white);\n g = Math.round(g * opacity + white);\n b = Math.round(b * opacity + white);\n return [r, g, b];\n}\nfunction RGBToHSL(rgb, output) {\n const r = rgb[0] / 255;\n const g = rgb[1] / 255;\n const b = rgb[2] / 255;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n if (max === min) {\n output[0] = output[1] = 0;\n } else {\n const d = max - min;\n output[1] = l < 0.5 ? d / (max + min) : d / (2 - max - min);\n switch (max) {\n case r:\n output[0] = ((g - b) / d + (g < b ? 6 : 0)) * 60;\n break;\n case g:\n output[0] = ((b - r) / d + 2) * 60;\n break;\n case b:\n output[0] = ((r - g) / d + 4) * 60;\n break;\n }\n }\n output[2] = l;\n}\nfunction HSLToRGB(hsl, output) {\n const h = hsl[0];\n const s = hsl[1];\n const l = hsl[2];\n const c = (1 - Math.abs(2 * l - 1)) * s;\n const x = c * (1 - Math.abs(h / 60 % 2 - 1));\n const m = l - c / 2;\n switch (Math.floor(h / 60)) {\n case 0:\n output[0] = c + m;\n output[1] = x + m;\n output[2] = m;\n break;\n case 1:\n output[0] = x + m;\n output[1] = c + m;\n output[2] = m;\n break;\n case 2:\n output[0] = m;\n output[1] = c + m;\n output[2] = x + m;\n break;\n case 3:\n output[0] = m;\n output[1] = x + m;\n output[2] = c + m;\n break;\n case 4:\n output[0] = x + m;\n output[1] = m;\n output[2] = c + m;\n break;\n case 5:\n case 6:\n output[0] = c + m;\n output[1] = m;\n output[2] = x + m;\n break;\n }\n}\nfunction computeLuminance(x) {\n return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;\n}\nfunction contrastRatio(hsl1, hsl2, output) {\n HSLToRGB(hsl1, output);\n output.map(computeLuminance);\n const lum1 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2];\n HSLToRGB(hsl2, output);\n output.map(computeLuminance);\n const lum2 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2];\n return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);\n}\nconst contrastCache = new Map();\nfunction findContrastColor(baseColor, fixedColor) {\n const key = baseColor[0] + baseColor[1] * 0x100 + baseColor[2] * 0x10000 + fixedColor[0] * 0x1000000 + fixedColor[1] * 0x100000000 + fixedColor[2] * 0x10000000000;\n let cachedValue = contrastCache.get(key);\n if (cachedValue) {\n return cachedValue;\n }\n const array = new Float32Array(9);\n const output = array.subarray(0, 3);\n const baseHSL = array.subarray(3, 6);\n RGBToHSL(baseColor, baseHSL);\n const fixedHSL = array.subarray(6, 9);\n RGBToHSL(fixedColor, fixedHSL);\n const isFixedColorDark = fixedHSL[2] < 0.5;\n const minContrast = isFixedColorDark ? 12 : 4.5;\n baseHSL[2] = isFixedColorDark ? Math.sqrt(baseHSL[2]) : 1 - Math.sqrt(1 - baseHSL[2]);\n if (contrastRatio(baseHSL, fixedHSL, output) < minContrast) {\n let start, end;\n if (isFixedColorDark) {\n start = baseHSL[2];\n end = 1;\n } else {\n start = 0;\n end = baseHSL[2];\n }\n const PRECISION = 0.005;\n while (end - start > PRECISION) {\n const mid = baseHSL[2] = (start + end) / 2;\n if (isFixedColorDark === contrastRatio(baseHSL, fixedHSL, output) < minContrast) {\n start = mid;\n } else {\n end = mid;\n }\n }\n baseHSL[2] = isFixedColorDark ? end : start;\n }\n HSLToRGB(baseHSL, output);\n cachedValue = Util.makeHexColor(Math.round(output[0] * 255), Math.round(output[1] * 255), Math.round(output[2] * 255));\n contrastCache.set(key, cachedValue);\n return cachedValue;\n}\nfunction renderRichText({\n html,\n dir,\n className\n}, container) {\n const fragment = document.createDocumentFragment();\n if (typeof html === "string") {\n const p = document.createElement("p");\n p.dir = dir || "auto";\n const lines = html.split(/(?:\\r\\n?|\\n)/);\n for (let i = 0, ii = lines.length; i < ii; ++i) {\n const line = lines[i];\n p.append(document.createTextNode(line));\n if (i < ii - 1) {\n p.append(document.createElement("br"));\n }\n }\n fragment.append(p);\n } else {\n XfaLayer.render({\n xfaHtml: html,\n div: fragment,\n intent: "richText"\n });\n }\n fragment.firstElementChild.classList.add("richText", className);\n container.append(fragment);\n}\nfunction makePathFromDrawOPS(data) {\n const path = new Path2D();\n if (!data) {\n return path;\n }\n for (let i = 0, ii = data.length; i < ii;) {\n switch (data[i++]) {\n case DrawOPS.moveTo:\n path.moveTo(data[i++], data[i++]);\n break;\n case DrawOPS.lineTo:\n path.lineTo(data[i++], data[i++]);\n break;\n case DrawOPS.curveTo:\n path.bezierCurveTo(data[i++], data[i++], data[i++], data[i++], data[i++], data[i++]);\n break;\n case DrawOPS.quadraticCurveTo:\n path.quadraticCurveTo(data[i++], data[i++], data[i++], data[i++]);\n break;\n case DrawOPS.closePath:\n path.closePath();\n break;\n default:\n warn(`Unrecognized drawing path operator: ${data[i - 1]}`);\n break;\n }\n }\n return path;\n}\nclass PagesMapper {\n #idToPageNumber = null;\n #pageNumberToId = null;\n #prevPageNumbers = null;\n #pagesNumber = 0;\n #listeners = [];\n #copiedPageIds = null;\n #copiedPageNumbers = null;\n get pagesNumber() {\n return this.#pagesNumber;\n }\n set pagesNumber(n) {\n if (this.#pagesNumber === n) {\n return;\n }\n this.#pagesNumber = n;\n this.#reset();\n }\n #reset() {\n this.#pageNumberToId = null;\n this.#idToPageNumber = null;\n }\n addListener(listener) {\n this.#listeners.push(listener);\n }\n removeListener(listener) {\n const index = this.#listeners.indexOf(listener);\n if (index >= 0) {\n this.#listeners.splice(index, 1);\n }\n }\n #updateListeners(data) {\n for (const listener of this.#listeners) {\n listener(data);\n }\n }\n #init(mustInit) {\n if (this.#pageNumberToId) {\n return;\n }\n const n = this.#pagesNumber;\n const pageNumberToId = this.#pageNumberToId = new Uint32Array(n);\n this.#prevPageNumbers = new Int32Array(pageNumberToId);\n const idToPageNumber = this.#idToPageNumber = new Map();\n if (mustInit) {\n for (let i = 1; i <= n; i++) {\n pageNumberToId[i - 1] = i;\n idToPageNumber.set(i, [i]);\n }\n }\n }\n #updateIdToPageNumber() {\n const idToPageNumber = this.#idToPageNumber;\n const pageNumberToId = this.#pageNumberToId;\n idToPageNumber.clear();\n for (let i = 0, ii = this.#pagesNumber; i < ii; i++) {\n const id = pageNumberToId[i];\n const pageNumbers = idToPageNumber.get(id);\n if (pageNumbers) {\n pageNumbers.push(i + 1);\n } else {\n idToPageNumber.set(id, [i + 1]);\n }\n }\n }\n movePages(selectedPages, pagesToMove, index) {\n this.#init(true);\n const pageNumberToId = this.#pageNumberToId;\n const idToPageNumber = this.#idToPageNumber;\n const movedCount = pagesToMove.length;\n const mappedPagesToMove = new Uint32Array(movedCount);\n let removedBeforeTarget = 0;\n for (let i = 0; i < movedCount; i++) {\n const pageIndex = pagesToMove[i] - 1;\n mappedPagesToMove[i] = pageNumberToId[pageIndex];\n if (pageIndex < index) {\n removedBeforeTarget += 1;\n }\n }\n const pagesNumber = this.#pagesNumber;\n let adjustedTarget = index - removedBeforeTarget;\n const remainingLen = pagesNumber - movedCount;\n adjustedTarget = MathClamp(adjustedTarget, 0, remainingLen);\n for (let i = 0, r = 0; i < pagesNumber; i++) {\n if (!selectedPages.has(i + 1)) {\n pageNumberToId[r++] = pageNumberToId[i];\n }\n }\n pageNumberToId.copyWithin(adjustedTarget + movedCount, adjustedTarget, remainingLen);\n pageNumberToId.set(mappedPagesToMove, adjustedTarget);\n this.#setPrevPageNumbers(idToPageNumber, null);\n this.#updateIdToPageNumber();\n this.#updateListeners({\n type: "move"\n });\n if (pageNumberToId.every((id, i) => id === i + 1)) {\n this.#reset();\n }\n }\n deletePages(pagesToDelete) {\n this.#init(true);\n const pageNumberToId = this.#pageNumberToId;\n const prevIdToPageNumber = this.#idToPageNumber;\n this.pagesNumber -= pagesToDelete.length;\n this.#init(false);\n const newPageNumberToId = this.#pageNumberToId;\n let sourceIndex = 0;\n let destIndex = 0;\n for (const pageNumber of pagesToDelete) {\n const pageIndex = pageNumber - 1;\n if (pageIndex !== sourceIndex) {\n newPageNumberToId.set(pageNumberToId.subarray(sourceIndex, pageIndex), destIndex);\n destIndex += pageIndex - sourceIndex;\n }\n sourceIndex = pageIndex + 1;\n }\n if (sourceIndex < pageNumberToId.length) {\n newPageNumberToId.set(pageNumberToId.subarray(sourceIndex), destIndex);\n }\n this.#setPrevPageNumbers(prevIdToPageNumber, null);\n this.#updateIdToPageNumber();\n this.#updateListeners({\n type: "delete",\n pageNumbers: pagesToDelete\n });\n }\n copyPages(pagesToCopy) {\n this.#init(true);\n this.#copiedPageNumbers = pagesToCopy;\n this.#copiedPageIds = pagesToCopy.map(pageNumber => this.#pageNumberToId[pageNumber - 1]);\n this.#updateListeners({\n type: "copy",\n pageNumbers: pagesToCopy\n });\n }\n pastePages(index) {\n this.#init(true);\n const pageNumberToId = this.#pageNumberToId;\n const prevIdToPageNumber = this.#idToPageNumber;\n const copiedPageNumbers = this.#copiedPageNumbers;\n const copiedPageMapping = new Map();\n let base = index;\n for (const pageNumber of copiedPageNumbers) {\n copiedPageMapping.set(++base, pageNumber);\n }\n this.pagesNumber += copiedPageNumbers.length;\n this.#init(false);\n const newPageNumberToId = this.#pageNumberToId;\n newPageNumberToId.set(pageNumberToId.subarray(0, index), 0);\n newPageNumberToId.set(this.#copiedPageIds, index);\n newPageNumberToId.set(pageNumberToId.subarray(index), index + copiedPageNumbers.length);\n this.#setPrevPageNumbers(prevIdToPageNumber, copiedPageMapping);\n this.#updateIdToPageNumber();\n this.#updateListeners({\n type: "paste"\n });\n this.#copiedPageIds = null;\n }\n #setPrevPageNumbers(prevIdToPageNumber, copiedPageMapping) {\n const prevPageNumbers = this.#prevPageNumbers;\n const newPageNumberToId = this.#pageNumberToId;\n const idsIndices = new Map();\n for (let i = 0, ii = this.#pagesNumber; i < ii; i++) {\n const oldPageNumber = copiedPageMapping?.get(i + 1);\n if (oldPageNumber) {\n prevPageNumbers[i] = -oldPageNumber;\n continue;\n }\n const id = newPageNumberToId[i];\n const j = idsIndices.get(id) || 0;\n prevPageNumbers[i] = prevIdToPageNumber.get(id)?.[j];\n idsIndices.set(id, j + 1);\n }\n }\n hasBeenAltered() {\n return this.#pageNumberToId !== null;\n }\n getPageMappingForSaving() {\n const idToPageNumber = this.#idToPageNumber;\n let nCopy = 0;\n for (const pageNumbers of idToPageNumber.values()) {\n nCopy = Math.max(nCopy, pageNumbers.length);\n }\n const extractParams = new Array(nCopy);\n for (let i = 0; i < nCopy; i++) {\n extractParams[i] = {\n document: null,\n pageIndices: [],\n includePages: []\n };\n }\n for (const [id, pageNumbers] of idToPageNumber) {\n for (let i = 0, ii = pageNumbers.length; i < ii; i++) {\n extractParams[i].includePages.push([id - 1, pageNumbers[i] - 1]);\n }\n }\n for (const {\n includePages,\n pageIndices\n } of extractParams) {\n includePages.sort((a, b) => a[0] - b[0]);\n for (let i = 0, ii = includePages.length; i < ii; i++) {\n pageIndices.push(includePages[i][1]);\n includePages[i] = includePages[i][0];\n }\n }\n return extractParams;\n }\n getPrevPageNumber(pageNumber) {\n return this.#prevPageNumbers[pageNumber - 1] ?? 0;\n }\n getPageNumber(id) {\n return this.#idToPageNumber ? this.#idToPageNumber.get(id)?.[0] ?? 0 : id;\n }\n getPageId(pageNumber) {\n return this.#pageNumberToId?.[pageNumber - 1] ?? pageNumber;\n }\n getMapping() {\n return this.#pageNumberToId.subarray(0, this.pagesNumber);\n }\n}\n\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.take.js\nvar es_iterator_take = __webpack_require__(4972);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.promise.with-resolvers.js\nvar es_promise_with_resolvers = __webpack_require__(4628);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.difference.v2.js\nvar es_set_difference_v2 = __webpack_require__(7642);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.intersection.v2.js\nvar es_set_intersection_v2 = __webpack_require__(8004);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-disjoint-from.v2.js\nvar es_set_is_disjoint_from_v2 = __webpack_require__(3853);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-subset-of.v2.js\nvar es_set_is_subset_of_v2 = __webpack_require__(5876);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.is-superset-of.v2.js\nvar es_set_is_superset_of_v2 = __webpack_require__(2475);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.symmetric-difference.v2.js\nvar es_set_symmetric_difference_v2 = __webpack_require__(5024);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.set.union.v2.js\nvar es_set_union_v2 = __webpack_require__(1698);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.weak-map.get-or-insert.js\nvar es_weak_map_get_or_insert = __webpack_require__(8454);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.weak-map.get-or-insert-computed.js\nvar es_weak_map_get_or_insert_computed = __webpack_require__(9452);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/web.dom-exception.stack.js\nvar web_dom_exception_stack = __webpack_require__(4979);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.json.stringify.js\nvar es_json_stringify = __webpack_require__(3110);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.drop.js\nvar es_iterator_drop = __webpack_require__(9314);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.some.js\nvar es_iterator_some = __webpack_require__(3579);\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.json.parse.js\nvar es_json_parse = __webpack_require__(9112);\n;// ./src/display/editor/toolbar.js\n\nclass EditorToolbar {\n #toolbar = null;\n #colorPicker = null;\n #editor;\n #buttons = null;\n #altText = null;\n #comment = null;\n #commentButtonDivider = null;\n #signatureDescriptionButton = null;\n static #l10nRemove = null;\n constructor(editor) {\n this.#editor = editor;\n EditorToolbar.#l10nRemove ||= Object.freeze({\n freetext: "pdfjs-editor-remove-freetext-button",\n highlight: "pdfjs-editor-remove-highlight-button",\n ink: "pdfjs-editor-remove-ink-button",\n stamp: "pdfjs-editor-remove-stamp-button",\n signature: "pdfjs-editor-remove-signature-button"\n });\n }\n render() {\n const editToolbar = this.#toolbar = document.createElement("div");\n editToolbar.classList.add("editToolbar", "hidden");\n editToolbar.setAttribute("role", "toolbar");\n const signal = this.#editor._uiManager._signal;\n if (signal instanceof AbortSignal && !signal.aborted) {\n editToolbar.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown, {\n signal\n });\n }\n const buttons = this.#buttons = document.createElement("div");\n buttons.className = "buttons";\n editToolbar.append(buttons);\n const position = this.#editor.toolbarPosition;\n if (position) {\n const {\n style\n } = editToolbar;\n const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0];\n style.insetInlineEnd = `${100 * x}%`;\n style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`;\n }\n return editToolbar;\n }\n get div() {\n return this.#toolbar;\n }\n static #pointerDown(e) {\n e.stopPropagation();\n }\n #focusIn(e) {\n this.#editor._focusEventsAllowed = false;\n stopEvent(e);\n }\n #focusOut(e) {\n this.#editor._focusEventsAllowed = true;\n stopEvent(e);\n }\n #addListenersToElement(element) {\n const signal = this.#editor._uiManager._signal;\n if (!(signal instanceof AbortSignal) || signal.aborted) {\n return false;\n }\n element.addEventListener("focusin", this.#focusIn.bind(this), {\n capture: true,\n signal\n });\n element.addEventListener("focusout", this.#focusOut.bind(this), {\n capture: true,\n signal\n });\n element.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n return true;\n }\n hide() {\n this.#toolbar.classList.add("hidden");\n this.#colorPicker?.hideDropdown();\n }\n show() {\n this.#toolbar.classList.remove("hidden");\n this.#altText?.shown();\n this.#comment?.shown();\n }\n addDeleteButton() {\n const {\n editorType,\n _uiManager\n } = this.#editor;\n const button = document.createElement("button");\n button.classList.add("basic", "deleteButton");\n button.tabIndex = 0;\n button.setAttribute("data-l10n-id", EditorToolbar.#l10nRemove[editorType]);\n if (this.#addListenersToElement(button)) {\n button.addEventListener("click", e => {\n _uiManager.delete();\n }, {\n signal: _uiManager._signal\n });\n }\n this.#buttons.append(button);\n }\n get #divider() {\n const divider = document.createElement("div");\n divider.className = "divider";\n return divider;\n }\n async addAltText(altText) {\n const button = await altText.render();\n this.#addListenersToElement(button);\n this.#buttons.append(button, this.#divider);\n this.#altText = altText;\n }\n addComment(comment, beforeElement = null) {\n if (this.#comment) {\n return;\n }\n const button = comment.renderForToolbar();\n if (!button) {\n return;\n }\n this.#addListenersToElement(button);\n const divider = this.#commentButtonDivider = this.#divider;\n if (!beforeElement) {\n this.#buttons.append(button, divider);\n } else {\n this.#buttons.insertBefore(button, beforeElement);\n this.#buttons.insertBefore(divider, beforeElement);\n }\n this.#comment = comment;\n comment.toolbar = this;\n }\n addColorPicker(colorPicker) {\n if (this.#colorPicker) {\n return;\n }\n this.#colorPicker = colorPicker;\n const button = colorPicker.renderButton();\n this.#addListenersToElement(button);\n this.#buttons.append(button, this.#divider);\n }\n async addEditSignatureButton(signatureManager) {\n const button = this.#signatureDescriptionButton = await signatureManager.renderEditButton(this.#editor);\n this.#addListenersToElement(button);\n this.#buttons.append(button, this.#divider);\n }\n removeButton(name) {\n switch (name) {\n case "comment":\n this.#comment?.removeToolbarCommentButton();\n this.#comment = null;\n this.#commentButtonDivider?.remove();\n this.#commentButtonDivider = null;\n break;\n }\n }\n async addButton(name, tool) {\n switch (name) {\n case "colorPicker":\n if (tool) {\n this.addColorPicker(tool);\n }\n break;\n case "altText":\n if (tool) {\n await this.addAltText(tool);\n }\n break;\n case "editSignature":\n if (tool) {\n await this.addEditSignatureButton(tool);\n }\n break;\n case "delete":\n this.addDeleteButton();\n break;\n case "comment":\n if (tool) {\n this.addComment(tool);\n }\n break;\n }\n }\n async addButtonBefore(name, tool, beforeSelector) {\n if (!tool && name === "comment") {\n return;\n }\n const beforeElement = this.#buttons.querySelector(beforeSelector);\n if (!beforeElement) {\n return;\n }\n if (name === "comment") {\n this.addComment(tool, beforeElement);\n }\n }\n updateEditSignatureButton(description) {\n if (this.#signatureDescriptionButton) {\n this.#signatureDescriptionButton.title = description;\n }\n }\n remove() {\n this.#toolbar.remove();\n this.#colorPicker?.destroy();\n this.#colorPicker = null;\n }\n}\nclass FloatingToolbar {\n #buttons = null;\n #toolbar = null;\n #uiManager;\n constructor(uiManager) {\n this.#uiManager = uiManager;\n }\n #render() {\n const editToolbar = this.#toolbar = document.createElement("div");\n editToolbar.className = "editToolbar";\n editToolbar.setAttribute("role", "toolbar");\n const signal = this.#uiManager._signal;\n if (signal instanceof AbortSignal && !signal.aborted) {\n editToolbar.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n }\n const buttons = this.#buttons = document.createElement("div");\n buttons.className = "buttons";\n editToolbar.append(buttons);\n if (this.#uiManager.hasCommentManager()) {\n this.#makeButton("commentButton", `pdfjs-comment-floating-button`, "pdfjs-comment-floating-button-label", () => {\n this.#uiManager.commentSelection("floating_button");\n });\n }\n this.#makeButton("highlightButton", `pdfjs-highlight-floating-button1`, "pdfjs-highlight-floating-button-label", () => {\n this.#uiManager.highlightSelection("floating_button");\n });\n return editToolbar;\n }\n #getLastPoint(boxes, isLTR) {\n let lastY = 0;\n let lastX = 0;\n for (const box of boxes) {\n const y = box.y + box.height;\n if (y < lastY) {\n continue;\n }\n const x = box.x + (isLTR ? box.width : 0);\n if (y > lastY) {\n lastX = x;\n lastY = y;\n continue;\n }\n if (isLTR) {\n if (x > lastX) {\n lastX = x;\n }\n } else if (x < lastX) {\n lastX = x;\n }\n }\n return [isLTR ? 1 - lastX : lastX, lastY];\n }\n show(parent, boxes, isLTR) {\n const [x, y] = this.#getLastPoint(boxes, isLTR);\n const {\n style\n } = this.#toolbar ||= this.#render();\n parent.append(this.#toolbar);\n style.insetInlineEnd = `${100 * x}%`;\n style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`;\n }\n hide() {\n this.#toolbar.remove();\n }\n #makeButton(buttonClass, l10nId, labelL10nId, clickHandler) {\n const button = document.createElement("button");\n button.classList.add("basic", buttonClass);\n button.tabIndex = 0;\n button.setAttribute("data-l10n-id", l10nId);\n const span = document.createElement("span");\n button.append(span);\n span.className = "visuallyHidden";\n span.setAttribute("data-l10n-id", labelL10nId);\n const signal = this.#uiManager._signal;\n if (signal instanceof AbortSignal && !signal.aborted) {\n button.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n button.addEventListener("click", clickHandler, {\n signal\n });\n }\n this.#buttons.append(button);\n }\n}\n\n;// ./src/display/editor/tools.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction bindEvents(obj, element, names) {\n for (const name of names) {\n element.addEventListener(name, obj[name].bind(obj));\n }\n}\nclass CurrentPointers {\n static #pointerId = NaN;\n static #pointerIds = null;\n static #moveTimestamp = NaN;\n static #pointerType = null;\n static initializeAndAddPointerId(pointerId) {\n (CurrentPointers.#pointerIds ||= new Set()).add(pointerId);\n }\n static setPointer(pointerType, pointerId) {\n CurrentPointers.#pointerId ||= pointerId;\n CurrentPointers.#pointerType ??= pointerType;\n }\n static setTimeStamp(timeStamp) {\n CurrentPointers.#moveTimestamp = timeStamp;\n }\n static isSamePointerId(pointerId) {\n return CurrentPointers.#pointerId === pointerId;\n }\n static isSamePointerIdOrRemove(pointerId) {\n if (CurrentPointers.#pointerId === pointerId) {\n return true;\n }\n CurrentPointers.#pointerIds?.delete(pointerId);\n return false;\n }\n static isSamePointerType(pointerType) {\n return CurrentPointers.#pointerType === pointerType;\n }\n static isInitializedAndDifferentPointerType(pointerType) {\n return CurrentPointers.#pointerType !== null && !CurrentPointers.isSamePointerType(pointerType);\n }\n static isSameTimeStamp(timeStamp) {\n return CurrentPointers.#moveTimestamp === timeStamp;\n }\n static isUsingMultiplePointers() {\n return CurrentPointers.#pointerIds?.size >= 1;\n }\n static clearPointerType() {\n CurrentPointers.#pointerType = null;\n }\n static clearPointerIds() {\n CurrentPointers.#pointerId = NaN;\n CurrentPointers.#pointerIds = null;\n }\n static clearTimeStamp() {\n CurrentPointers.#moveTimestamp = NaN;\n }\n}\nclass IdManager {\n #id = 0;\n get id() {\n return `${AnnotationEditorPrefix}${this.#id++}`;\n }\n}\nclass ImageManager {\n #baseId = getUuid();\n #id = 0;\n #cache = null;\n static get _isSVGFittingCanvas() {\n const svg = `data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>`;\n const canvas = new OffscreenCanvas(1, 3);\n const ctx = canvas.getContext("2d", {\n willReadFrequently: true\n });\n const image = new Image();\n image.src = svg;\n const promise = image.decode().then(() => {\n ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);\n return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;\n });\n return shadow(this, "_isSVGFittingCanvas", promise);\n }\n async #get(key, rawData) {\n this.#cache ||= new Map();\n let data = this.#cache.get(key);\n if (data === null) {\n return null;\n }\n if (data?.bitmap) {\n data.refCounter += 1;\n return data;\n }\n try {\n data ||= {\n bitmap: null,\n id: `image_${this.#baseId}_${this.#id++}`,\n refCounter: 0,\n isSvg: false\n };\n let image;\n if (typeof rawData === "string") {\n data.url = rawData;\n image = await fetchData(rawData, "blob");\n } else if (rawData instanceof File) {\n image = data.file = rawData;\n } else if (rawData instanceof Blob) {\n image = rawData;\n }\n if (image.type === "image/svg+xml") {\n const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas;\n const fileReader = new FileReader();\n const imageElement = new Image();\n const imagePromise = new Promise((resolve, reject) => {\n imageElement.onload = () => {\n data.bitmap = imageElement;\n data.isSvg = true;\n resolve();\n };\n fileReader.onload = async () => {\n const url = data.svgUrl = fileReader.result;\n imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url;\n };\n imageElement.onerror = fileReader.onerror = reject;\n });\n fileReader.readAsDataURL(image);\n await imagePromise;\n } else {\n data.bitmap = await createImageBitmap(image);\n }\n data.refCounter = 1;\n } catch (e) {\n warn(e);\n data = null;\n }\n this.#cache.set(key, data);\n if (data) {\n this.#cache.set(data.id, data);\n }\n return data;\n }\n async getFromFile(file) {\n const {\n lastModified,\n name,\n size,\n type\n } = file;\n return this.#get(`${lastModified}_${name}_${size}_${type}`, file);\n }\n async getFromUrl(url) {\n return this.#get(url, url);\n }\n async getFromBlob(id, blobPromise) {\n const blob = await blobPromise;\n return this.#get(id, blob);\n }\n async getFromId(id) {\n this.#cache ||= new Map();\n const data = this.#cache.get(id);\n if (!data) {\n return null;\n }\n if (data.bitmap) {\n data.refCounter += 1;\n return data;\n }\n if (data.file) {\n return this.getFromFile(data.file);\n }\n if (data.blobPromise) {\n const {\n blobPromise\n } = data;\n delete data.blobPromise;\n return this.getFromBlob(data.id, blobPromise);\n }\n return this.getFromUrl(data.url);\n }\n getFromCanvas(id, canvas) {\n this.#cache ||= new Map();\n let data = this.#cache.get(id);\n if (data?.bitmap) {\n data.refCounter += 1;\n return data;\n }\n const offscreen = new OffscreenCanvas(canvas.width, canvas.height);\n const ctx = offscreen.getContext("2d");\n ctx.drawImage(canvas, 0, 0);\n data = {\n bitmap: offscreen.transferToImageBitmap(),\n id: `image_${this.#baseId}_${this.#id++}`,\n refCounter: 1,\n isSvg: false\n };\n this.#cache.set(id, data);\n this.#cache.set(data.id, data);\n return data;\n }\n getSvgUrl(id) {\n const data = this.#cache.get(id);\n if (!data?.isSvg) {\n return null;\n }\n return data.svgUrl;\n }\n deleteId(id) {\n this.#cache ||= new Map();\n const data = this.#cache.get(id);\n if (!data) {\n return;\n }\n data.refCounter -= 1;\n if (data.refCounter !== 0) {\n return;\n }\n const {\n bitmap\n } = data;\n if (!data.url && !data.file) {\n const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);\n const ctx = canvas.getContext("bitmaprenderer");\n ctx.transferFromImageBitmap(bitmap);\n data.blobPromise = canvas.convertToBlob();\n }\n bitmap.close?.();\n data.bitmap = null;\n }\n isValidId(id) {\n return id.startsWith(`image_${this.#baseId}_`);\n }\n}\nclass CommandManager {\n #commands = [];\n #locked = false;\n #maxSize;\n #position = -1;\n constructor(maxSize = 128) {\n this.#maxSize = maxSize;\n }\n add({\n cmd,\n undo,\n post,\n mustExec,\n type = NaN,\n overwriteIfSameType = false,\n keepUndo = false\n }) {\n if (mustExec) {\n cmd();\n }\n if (this.#locked) {\n return;\n }\n const save = {\n cmd,\n undo,\n post,\n type\n };\n if (this.#position === -1) {\n if (this.#commands.length > 0) {\n this.#commands.length = 0;\n }\n this.#position = 0;\n this.#commands.push(save);\n return;\n }\n if (overwriteIfSameType && this.#commands[this.#position].type === type) {\n if (keepUndo) {\n save.undo = this.#commands[this.#position].undo;\n }\n this.#commands[this.#position] = save;\n return;\n }\n const next = this.#position + 1;\n if (next === this.#maxSize) {\n this.#commands.splice(0, 1);\n } else {\n this.#position = next;\n if (next < this.#commands.length) {\n this.#commands.splice(next);\n }\n }\n this.#commands.push(save);\n }\n undo() {\n if (this.#position === -1) {\n return;\n }\n this.#locked = true;\n const {\n undo,\n post\n } = this.#commands[this.#position];\n undo();\n post?.();\n this.#locked = false;\n this.#position -= 1;\n }\n redo() {\n if (this.#position < this.#commands.length - 1) {\n this.#position += 1;\n this.#locked = true;\n const {\n cmd,\n post\n } = this.#commands[this.#position];\n cmd();\n post?.();\n this.#locked = false;\n }\n }\n hasSomethingToUndo() {\n return this.#position !== -1;\n }\n hasSomethingToRedo() {\n return this.#position < this.#commands.length - 1;\n }\n cleanType(type) {\n if (this.#position === -1) {\n return;\n }\n for (let i = this.#position; i >= 0; i--) {\n if (this.#commands[i].type !== type) {\n this.#commands.splice(i + 1, this.#position - i);\n this.#position = i;\n return;\n }\n }\n this.#commands.length = 0;\n this.#position = -1;\n }\n destroy() {\n this.#commands = null;\n }\n}\nclass KeyboardManager {\n constructor(callbacks) {\n this.buffer = [];\n this.callbacks = new Map();\n this.allKeys = new Set();\n const {\n isMac\n } = FeatureTest.platform;\n for (const [keys, callback, options = {}] of callbacks) {\n for (const key of keys) {\n const isMacKey = key.startsWith("mac+");\n if (isMac && isMacKey) {\n this.callbacks.set(key.slice(4), {\n callback,\n options\n });\n this.allKeys.add(key.split("+").at(-1));\n } else if (!isMac && !isMacKey) {\n this.callbacks.set(key, {\n callback,\n options\n });\n this.allKeys.add(key.split("+").at(-1));\n }\n }\n }\n }\n #serialize(event) {\n if (event.altKey) {\n this.buffer.push("alt");\n }\n if (event.ctrlKey) {\n this.buffer.push("ctrl");\n }\n if (event.metaKey) {\n this.buffer.push("meta");\n }\n if (event.shiftKey) {\n this.buffer.push("shift");\n }\n this.buffer.push(event.key);\n const str = this.buffer.join("+");\n this.buffer.length = 0;\n return str;\n }\n exec(self, event) {\n if (!this.allKeys.has(event.key)) {\n return;\n }\n const info = this.callbacks.get(this.#serialize(event));\n if (!info) {\n return;\n }\n const {\n callback,\n options: {\n bubbles = false,\n args = [],\n checker = null\n }\n } = info;\n if (checker && !checker(self, event)) {\n return;\n }\n callback.bind(self, ...args, event)();\n if (!bubbles) {\n stopEvent(event);\n }\n }\n}\nclass ColorManager {\n static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);\n get _colors() {\n const colors = new Map([["CanvasText", null], ["Canvas", null]]);\n getColorValues(colors);\n return shadow(this, "_colors", colors);\n }\n convert(color) {\n const rgb = getRGB(color);\n if (!window.matchMedia("(forced-colors: active)").matches) {\n return rgb;\n }\n for (const [name, RGB] of this._colors) {\n if (RGB.every((x, i) => x === rgb[i])) {\n return ColorManager._colorsMapping.get(name);\n }\n }\n return rgb;\n }\n getHexCode(name) {\n const rgb = this._colors.get(name);\n if (!rgb) {\n return name;\n }\n return Util.makeHexColor(...rgb);\n }\n}\nclass AnnotationEditorUIManager {\n #abortController = new AbortController();\n #activeEditor = null;\n #allEditableAnnotations = null;\n #allEditors = new Map();\n #allLayers = new Map();\n #altTextManager = null;\n #annotationStorage = null;\n #changedExistingAnnotations = null;\n #commandManager = new CommandManager();\n #commentManager = null;\n #copyPasteAC = null;\n #currentDrawingSession = null;\n #currentPageIndex = 0;\n #deletedAnnotationsElementIds = new Set();\n #draggingEditors = null;\n #editorTypes = null;\n #editorsToRescale = new Set();\n _editorUndoBar = null;\n #enableHighlightFloatingButton = false;\n #enableUpdatedAddImage = false;\n #enableNewAltTextWhenAddingImage = false;\n #filterFactory = null;\n #focusMainContainerTimeoutId = null;\n #focusManagerAC = null;\n #highlightColors = null;\n #highlightWhenShiftUp = false;\n #floatingToolbar = null;\n #idManager = new IdManager();\n #isEnabled = false;\n #isPointerDown = false;\n #isWaiting = false;\n #keyboardManagerAC = null;\n #lastActiveElement = null;\n #mainHighlightColorPicker = null;\n #missingCanvases = null;\n #mlManager = null;\n #mode = AnnotationEditorType.NONE;\n #selectedEditors = new Set();\n #selectedTextNode = null;\n #signatureManager = null;\n #pageColors = null;\n #showAllStates = null;\n #pdfDocument = null;\n #previousStates = {\n isEditing: false,\n isEmpty: true,\n hasSomethingToUndo: false,\n hasSomethingToRedo: false,\n hasSelectedEditor: false,\n hasSelectedText: false\n };\n #translation = [0, 0];\n #translationTimeoutId = null;\n #container = null;\n #viewer = null;\n #viewerAlert = null;\n #updateModeCapability = null;\n static TRANSLATE_SMALL = 1;\n static TRANSLATE_BIG = 10;\n static get _keyboardManager() {\n const proto = AnnotationEditorUIManager.prototype;\n const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl();\n const textInputChecker = (_self, {\n target: el\n }) => {\n if (el instanceof HTMLInputElement) {\n const {\n type\n } = el;\n return type !== "text" && type !== "number";\n }\n return true;\n };\n const small = this.TRANSLATE_SMALL;\n const big = this.TRANSLATE_BIG;\n return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, {\n checker: textInputChecker\n }], [["ctrl+z", "mac+meta+z"], proto.undo, {\n checker: textInputChecker\n }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, {\n checker: textInputChecker\n }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, {\n checker: textInputChecker\n }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, {\n checker: (self, {\n target: el\n }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled\n }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, {\n checker: (self, {\n target: el\n }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement)\n }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, {\n args: [-small, 0],\n checker: arrowChecker\n }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, {\n args: [-big, 0],\n checker: arrowChecker\n }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, {\n args: [small, 0],\n checker: arrowChecker\n }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, {\n args: [big, 0],\n checker: arrowChecker\n }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, {\n args: [0, -small],\n checker: arrowChecker\n }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, {\n args: [0, -big],\n checker: arrowChecker\n }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, {\n args: [0, small],\n checker: arrowChecker\n }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, {\n args: [0, big],\n checker: arrowChecker\n }]]));\n }\n constructor(container, viewer, viewerAlert, altTextManager, commentManager, signatureManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager, editorUndoBar, supportsPinchToZoom) {\n const signal = this._signal = this.#abortController.signal;\n this.#container = container;\n this.#viewer = viewer;\n this.#viewerAlert = viewerAlert;\n this.#altTextManager = altTextManager;\n this.#commentManager = commentManager;\n this.#signatureManager = signatureManager;\n this.#pdfDocument = pdfDocument;\n this._eventBus = eventBus;\n eventBus._on("editingaction", this.onEditingAction.bind(this), {\n signal\n });\n eventBus._on("pagechanging", this.onPageChanging.bind(this), {\n signal\n });\n eventBus._on("scalechanging", this.onScaleChanging.bind(this), {\n signal\n });\n eventBus._on("rotationchanging", this.onRotationChanging.bind(this), {\n signal\n });\n eventBus._on("setpreference", this.onSetPreference.bind(this), {\n signal\n });\n eventBus._on("switchannotationeditorparams", evt => this.updateParams(evt.type, evt.value), {\n signal\n });\n window.addEventListener("pointerdown", () => {\n this.#isPointerDown = true;\n }, {\n capture: true,\n signal\n });\n window.addEventListener("pointerup", () => {\n this.#isPointerDown = false;\n }, {\n capture: true,\n signal\n });\n window.addEventListener("beforeunload", this.#beforeUnload.bind(this), {\n capture: true,\n signal\n });\n this.#addSelectionListener();\n this.#addDragAndDropListeners();\n this.#addKeyboardManager();\n this.#annotationStorage = pdfDocument.annotationStorage;\n this.#filterFactory = pdfDocument.filterFactory;\n this.#pageColors = pageColors;\n this.#highlightColors = highlightColors || null;\n this.#enableHighlightFloatingButton = enableHighlightFloatingButton;\n this.#enableUpdatedAddImage = enableUpdatedAddImage;\n this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage;\n this.#mlManager = mlManager || null;\n this.viewParameters = {\n realScale: PixelsPerInch.PDF_TO_CSS_UNITS,\n rotation: 0\n };\n this.isShiftKeyDown = false;\n this._editorUndoBar = editorUndoBar || null;\n this._supportsPinchToZoom = supportsPinchToZoom !== false;\n commentManager?.setSidebarUiManager(this);\n }\n destroy() {\n this.#updateModeCapability?.resolve();\n this.#updateModeCapability = null;\n this.#abortController?.abort();\n this.#abortController = null;\n this._signal = null;\n for (const layer of this.#allLayers.values()) {\n layer.destroy();\n }\n this.#allLayers.clear();\n this.#allEditors.clear();\n this.#editorsToRescale.clear();\n this.#missingCanvases?.clear();\n this.#activeEditor = null;\n this.#selectedEditors.clear();\n this.#commandManager.destroy();\n this.#altTextManager?.destroy();\n this.#commentManager?.destroy();\n this.#signatureManager?.destroy();\n this.#floatingToolbar?.hide();\n this.#floatingToolbar = null;\n this.#mainHighlightColorPicker?.destroy();\n this.#mainHighlightColorPicker = null;\n this.#allEditableAnnotations = null;\n if (this.#focusMainContainerTimeoutId) {\n clearTimeout(this.#focusMainContainerTimeoutId);\n this.#focusMainContainerTimeoutId = null;\n }\n if (this.#translationTimeoutId) {\n clearTimeout(this.#translationTimeoutId);\n this.#translationTimeoutId = null;\n }\n this._editorUndoBar?.destroy();\n this.#pdfDocument = null;\n }\n combinedSignal(ac) {\n return AbortSignal.any([this._signal, ac.signal]);\n }\n get mlManager() {\n return this.#mlManager;\n }\n get useNewAltTextFlow() {\n return this.#enableUpdatedAddImage;\n }\n get useNewAltTextWhenAddingImage() {\n return this.#enableNewAltTextWhenAddingImage;\n }\n get hcmFilter() {\n return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none");\n }\n get direction() {\n return shadow(this, "direction", getComputedStyle(this.#container).direction);\n }\n get _highlightColors() {\n return shadow(this, "_highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => {\n pair = pair.split("=").map(x => x.trim());\n pair[1] = pair[1].toUpperCase();\n return pair;\n })) : null);\n }\n get highlightColors() {\n const {\n _highlightColors\n } = this;\n if (!_highlightColors) {\n return shadow(this, "highlightColors", null);\n }\n const map = new Map();\n const hasHCM = !!this.#pageColors;\n for (const [name, color] of _highlightColors) {\n const isNameForHCM = name.endsWith("_HCM");\n if (hasHCM && isNameForHCM) {\n map.set(name.replace("_HCM", ""), color);\n continue;\n }\n if (!hasHCM && !isNameForHCM) {\n map.set(name, color);\n }\n }\n return shadow(this, "highlightColors", map);\n }\n get highlightColorNames() {\n return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null);\n }\n getNonHCMColor(color) {\n if (!this._highlightColors) {\n return color;\n }\n const colorName = this.highlightColorNames.get(color);\n return this._highlightColors.get(colorName) || color;\n }\n getNonHCMColorName(color) {\n return this.highlightColorNames.get(color) || color;\n }\n setCurrentDrawingSession(layer) {\n if (layer) {\n this.unselectAll();\n this.disableUserSelect(true);\n } else {\n this.disableUserSelect(false);\n }\n this.#currentDrawingSession = layer;\n }\n setMainHighlightColorPicker(colorPicker) {\n this.#mainHighlightColorPicker = colorPicker;\n }\n editAltText(editor, firstTime = false) {\n this.#altTextManager?.editAltText(this, editor, firstTime);\n }\n hasCommentManager() {\n return !!this.#commentManager;\n }\n editComment(editor, posX, posY, options) {\n this.#commentManager?.showDialog(this, editor, posX, posY, options);\n }\n selectComment(pageIndex, uid) {\n const layer = this.#allLayers.get(pageIndex);\n const editor = layer?.getEditorByUID(uid);\n editor?.toggleComment(true, true);\n }\n updateComment(editor) {\n this.#commentManager?.updateComment(editor.getData());\n }\n updatePopupColor(editor) {\n this.#commentManager?.updatePopupColor(editor);\n }\n removeComment(editor) {\n this.#commentManager?.removeComments([editor.uid]);\n }\n deleteComment(editor, savedData) {\n const undo = () => {\n editor.comment = savedData;\n };\n const cmd = () => {\n this._editorUndoBar?.show(undo, "comment");\n this.toggleComment(null);\n editor.comment = null;\n };\n this.addCommands({\n cmd,\n undo,\n mustExec: true\n });\n }\n toggleComment(editor, isSelected, visibility = undefined) {\n this.#commentManager?.toggleCommentPopup(editor, isSelected, visibility);\n }\n makeCommentColor(color, opacity) {\n return color && this.#commentManager?.makeCommentColor(color, opacity) || null;\n }\n getCommentDialogElement() {\n return this.#commentManager?.dialogElement || null;\n }\n async waitForEditorsRendered(pageNumber) {\n if (this.#allLayers.has(pageNumber - 1)) {\n return;\n }\n const {\n resolve,\n promise\n } = Promise.withResolvers();\n const onEditorsRendered = evt => {\n if (evt.pageNumber === pageNumber) {\n this._eventBus._off("editorsrendered", onEditorsRendered);\n resolve();\n }\n };\n this._eventBus.on("editorsrendered", onEditorsRendered);\n await promise;\n }\n getSignature(editor) {\n this.#signatureManager?.getSignature({\n uiManager: this,\n editor\n });\n }\n get signatureManager() {\n return this.#signatureManager;\n }\n switchToMode(mode, callback) {\n this._eventBus.on("annotationeditormodechanged", callback, {\n once: true,\n signal: this._signal\n });\n this._eventBus.dispatch("showannotationeditorui", {\n source: this,\n mode\n });\n }\n setPreference(name, value) {\n this._eventBus.dispatch("setpreference", {\n source: this,\n name,\n value\n });\n }\n onSetPreference({\n name,\n value\n }) {\n switch (name) {\n case "enableNewAltTextWhenAddingImage":\n this.#enableNewAltTextWhenAddingImage = value;\n break;\n }\n }\n onPageChanging({\n pageNumber\n }) {\n this.#currentPageIndex = pageNumber - 1;\n }\n deletePage(id) {\n for (const editor of this.getEditors(id)) {\n editor.remove();\n }\n this.#allLayers.delete(id);\n if (this.#currentPageIndex === id) {\n this.#currentPageIndex = 0;\n }\n }\n focusMainContainer() {\n this.#container.focus();\n }\n findParent(x, y) {\n for (const layer of this.#allLayers.values()) {\n const {\n x: layerX,\n y: layerY,\n width,\n height\n } = layer.div.getBoundingClientRect();\n if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) {\n return layer;\n }\n }\n return null;\n }\n disableUserSelect(value = false) {\n this.#viewer.classList.toggle("noUserSelect", value);\n }\n addShouldRescale(editor) {\n this.#editorsToRescale.add(editor);\n }\n removeShouldRescale(editor) {\n this.#editorsToRescale.delete(editor);\n }\n onScaleChanging({\n scale\n }) {\n this.commitOrRemove();\n this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;\n for (const editor of this.#editorsToRescale) {\n editor.onScaleChanging();\n }\n this.#currentDrawingSession?.onScaleChanging();\n }\n onRotationChanging({\n pagesRotation\n }) {\n this.commitOrRemove();\n this.viewParameters.rotation = pagesRotation;\n }\n #getAnchorElementForSelection({\n anchorNode\n }) {\n return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode;\n }\n #getLayerForTextLayer(textLayer) {\n const {\n currentLayer\n } = this;\n if (currentLayer.hasTextLayer(textLayer)) {\n return currentLayer;\n }\n for (const layer of this.#allLayers.values()) {\n if (layer.hasTextLayer(textLayer)) {\n return layer;\n }\n }\n return null;\n }\n highlightSelection(methodOfCreation = "", comment = false) {\n const selection = document.getSelection();\n if (!selection || selection.isCollapsed) {\n return;\n }\n const {\n anchorNode,\n anchorOffset,\n focusNode,\n focusOffset\n } = selection;\n const text = selection.toString();\n const anchorElement = this.#getAnchorElementForSelection(selection);\n const textLayer = anchorElement.closest(".textLayer");\n const boxes = this.getSelectionBoxes(textLayer);\n if (!boxes) {\n return;\n }\n selection.empty();\n const layer = this.#getLayerForTextLayer(textLayer);\n const isNoneMode = this.#mode === AnnotationEditorType.NONE;\n const callback = () => {\n const editor = layer?.createAndAddNewEditor({\n x: 0,\n y: 0\n }, false, {\n methodOfCreation,\n boxes,\n anchorNode,\n anchorOffset,\n focusNode,\n focusOffset,\n text\n });\n if (isNoneMode) {\n this.showAllEditors("highlight", true, true);\n }\n if (comment) {\n editor?.editComment();\n }\n };\n if (isNoneMode) {\n this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback);\n return;\n }\n callback();\n }\n commentSelection(methodOfCreation = "") {\n this.highlightSelection(methodOfCreation, true);\n }\n #beforeUnload(e) {\n this.commitOrRemove();\n this.currentLayer?.endDrawingSession(false);\n }\n #displayFloatingToolbar() {\n const selection = document.getSelection();\n if (!selection || selection.isCollapsed) {\n return;\n }\n const anchorElement = this.#getAnchorElementForSelection(selection);\n const textLayer = anchorElement.closest(".textLayer");\n const boxes = this.getSelectionBoxes(textLayer);\n if (!boxes) {\n return;\n }\n this.#floatingToolbar ||= new FloatingToolbar(this);\n this.#floatingToolbar.show(textLayer, boxes, this.direction === "ltr");\n }\n getAndRemoveDataFromAnnotationStorage(annotationId) {\n if (!this.#annotationStorage) {\n return null;\n }\n const key = `${AnnotationEditorPrefix}${annotationId}`;\n const storedValue = this.#annotationStorage.getRawValue(key);\n if (storedValue) {\n this.#annotationStorage.remove(key);\n }\n return storedValue;\n }\n addToAnnotationStorage(editor) {\n if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {\n this.#annotationStorage.setValue(editor.id, editor);\n }\n }\n a11yAlert(messageId, args = null) {\n const viewerAlert = this.#viewerAlert;\n if (!viewerAlert) {\n return;\n }\n viewerAlert.setAttribute("data-l10n-id", messageId);\n if (args) {\n viewerAlert.setAttribute("data-l10n-args", JSON.stringify(args));\n } else {\n viewerAlert.removeAttribute("data-l10n-args");\n }\n }\n #selectionChange() {\n const selection = document.getSelection();\n if (!selection || selection.isCollapsed) {\n if (this.#selectedTextNode) {\n this.#floatingToolbar?.hide();\n this.#selectedTextNode = null;\n this.#dispatchUpdateStates({\n hasSelectedText: false\n });\n }\n return;\n }\n const {\n anchorNode\n } = selection;\n if (anchorNode === this.#selectedTextNode) {\n return;\n }\n const anchorElement = this.#getAnchorElementForSelection(selection);\n const textLayer = anchorElement.closest(".textLayer");\n if (!textLayer) {\n if (this.#selectedTextNode) {\n this.#floatingToolbar?.hide();\n this.#selectedTextNode = null;\n this.#dispatchUpdateStates({\n hasSelectedText: false\n });\n }\n return;\n }\n this.#floatingToolbar?.hide();\n this.#selectedTextNode = anchorNode;\n this.#dispatchUpdateStates({\n hasSelectedText: true\n });\n if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) {\n return;\n }\n if (this.#mode === AnnotationEditorType.HIGHLIGHT) {\n this.showAllEditors("highlight", true, true);\n }\n this.#highlightWhenShiftUp = this.isShiftKeyDown;\n if (!this.isShiftKeyDown) {\n const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null;\n activeLayer?.toggleDrawing();\n if (this.#isPointerDown) {\n const ac = new AbortController();\n const signal = this.combinedSignal(ac);\n const pointerup = e => {\n if (e.type === "pointerup" && e.button !== 0) {\n return;\n }\n ac.abort();\n activeLayer?.toggleDrawing(true);\n if (e.type === "pointerup") {\n this.#onSelectEnd("main_toolbar");\n }\n };\n window.addEventListener("pointerup", pointerup, {\n signal\n });\n window.addEventListener("blur", pointerup, {\n signal\n });\n } else {\n activeLayer?.toggleDrawing(true);\n this.#onSelectEnd("main_toolbar");\n }\n }\n }\n #onSelectEnd(methodOfCreation = "") {\n if (this.#mode === AnnotationEditorType.HIGHLIGHT) {\n this.highlightSelection(methodOfCreation);\n } else if (this.#enableHighlightFloatingButton) {\n this.#displayFloatingToolbar();\n }\n }\n #addSelectionListener() {\n document.addEventListener("selectionchange", this.#selectionChange.bind(this), {\n signal: this._signal\n });\n }\n #addFocusManager() {\n if (this.#focusManagerAC) {\n return;\n }\n this.#focusManagerAC = new AbortController();\n const signal = this.combinedSignal(this.#focusManagerAC);\n window.addEventListener("focus", this.focus.bind(this), {\n signal\n });\n window.addEventListener("blur", this.blur.bind(this), {\n signal\n });\n }\n #removeFocusManager() {\n this.#focusManagerAC?.abort();\n this.#focusManagerAC = null;\n }\n blur() {\n this.isShiftKeyDown = false;\n if (this.#highlightWhenShiftUp) {\n this.#highlightWhenShiftUp = false;\n this.#onSelectEnd("main_toolbar");\n }\n if (!this.hasSelection) {\n return;\n }\n const {\n activeElement\n } = document;\n for (const editor of this.#selectedEditors) {\n if (editor.div.contains(activeElement)) {\n this.#lastActiveElement = [editor, activeElement];\n editor._focusEventsAllowed = false;\n break;\n }\n }\n }\n focus() {\n if (!this.#lastActiveElement) {\n return;\n }\n const [lastEditor, lastActiveElement] = this.#lastActiveElement;\n this.#lastActiveElement = null;\n lastActiveElement.addEventListener("focusin", () => {\n lastEditor._focusEventsAllowed = true;\n }, {\n once: true,\n signal: this._signal\n });\n lastActiveElement.focus();\n }\n #addKeyboardManager() {\n if (this.#keyboardManagerAC) {\n return;\n }\n this.#keyboardManagerAC = new AbortController();\n const signal = this.combinedSignal(this.#keyboardManagerAC);\n window.addEventListener("keydown", this.keydown.bind(this), {\n signal\n });\n window.addEventListener("keyup", this.keyup.bind(this), {\n signal\n });\n }\n #removeKeyboardManager() {\n this.#keyboardManagerAC?.abort();\n this.#keyboardManagerAC = null;\n }\n #addCopyPasteListeners() {\n if (this.#copyPasteAC) {\n return;\n }\n this.#copyPasteAC = new AbortController();\n const signal = this.combinedSignal(this.#copyPasteAC);\n document.addEventListener("copy", this.copy.bind(this), {\n signal\n });\n document.addEventListener("cut", this.cut.bind(this), {\n signal\n });\n document.addEventListener("paste", this.paste.bind(this), {\n signal\n });\n }\n #removeCopyPasteListeners() {\n this.#copyPasteAC?.abort();\n this.#copyPasteAC = null;\n }\n #addDragAndDropListeners() {\n const signal = this._signal;\n document.addEventListener("dragover", this.dragOver.bind(this), {\n signal\n });\n document.addEventListener("drop", this.drop.bind(this), {\n signal\n });\n }\n addEditListeners() {\n this.#addKeyboardManager();\n this.setEditingState(true);\n }\n removeEditListeners() {\n this.#removeKeyboardManager();\n this.setEditingState(false);\n }\n dragOver(event) {\n for (const {\n type\n } of event.dataTransfer.items) {\n for (const editorType of this.#editorTypes) {\n if (editorType.isHandlingMimeForPasting(type)) {\n event.dataTransfer.dropEffect = "copy";\n event.preventDefault();\n return;\n }\n }\n }\n }\n drop(event) {\n for (const item of event.dataTransfer.items) {\n for (const editorType of this.#editorTypes) {\n if (editorType.isHandlingMimeForPasting(item.type)) {\n editorType.paste(item, this.currentLayer);\n event.preventDefault();\n return;\n }\n }\n }\n }\n copy(event) {\n event.preventDefault();\n this.#activeEditor?.commitOrRemove();\n if (!this.hasSelection) {\n return;\n }\n const editors = [];\n for (const editor of this.#selectedEditors) {\n const serialized = editor.serialize(true);\n if (serialized) {\n editors.push(serialized);\n }\n }\n if (editors.length === 0) {\n return;\n }\n event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));\n }\n cut(event) {\n this.copy(event);\n this.delete();\n }\n async paste(event) {\n event.preventDefault();\n const {\n clipboardData\n } = event;\n for (const item of clipboardData.items) {\n for (const editorType of this.#editorTypes) {\n if (editorType.isHandlingMimeForPasting(item.type)) {\n editorType.paste(item, this.currentLayer);\n return;\n }\n }\n }\n let data = clipboardData.getData("application/pdfjs");\n if (!data) {\n return;\n }\n try {\n data = JSON.parse(data);\n } catch (ex) {\n warn(`paste: "${ex.message}".`);\n return;\n }\n if (!Array.isArray(data)) {\n return;\n }\n this.unselectAll();\n const layer = this.currentLayer;\n try {\n const newEditors = [];\n for (const editor of data) {\n const deserializedEditor = await layer.deserialize(editor);\n if (!deserializedEditor) {\n return;\n }\n newEditors.push(deserializedEditor);\n }\n const cmd = () => {\n for (const editor of newEditors) {\n this.#addEditorToLayer(editor);\n }\n this.#selectEditors(newEditors);\n };\n const undo = () => {\n for (const editor of newEditors) {\n editor.remove();\n }\n };\n this.addCommands({\n cmd,\n undo,\n mustExec: true\n });\n } catch (ex) {\n warn(`paste: "${ex.message}".`);\n }\n }\n keydown(event) {\n if (!this.isShiftKeyDown && event.key === "Shift") {\n this.isShiftKeyDown = true;\n }\n if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) {\n AnnotationEditorUIManager._keyboardManager.exec(this, event);\n }\n }\n keyup(event) {\n if (this.isShiftKeyDown && event.key === "Shift") {\n this.isShiftKeyDown = false;\n if (this.#highlightWhenShiftUp) {\n this.#highlightWhenShiftUp = false;\n this.#onSelectEnd("main_toolbar");\n }\n }\n }\n onEditingAction({\n name\n }) {\n switch (name) {\n case "undo":\n case "redo":\n case "delete":\n case "selectAll":\n this[name]();\n break;\n case "highlightSelection":\n this.highlightSelection("context_menu");\n break;\n case "commentSelection":\n this.commentSelection("context_menu");\n break;\n }\n }\n #dispatchUpdateStates(details) {\n const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);\n if (hasChanged) {\n this._eventBus.dispatch("annotationeditorstateschanged", {\n source: this,\n details: Object.assign(this.#previousStates, details)\n });\n if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) {\n this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]);\n }\n }\n }\n #dispatchUpdateUI(details) {\n this._eventBus.dispatch("annotationeditorparamschanged", {\n source: this,\n details\n });\n }\n setEditingState(isEditing) {\n if (isEditing) {\n this.#addFocusManager();\n this.#addCopyPasteListeners();\n this.#dispatchUpdateStates({\n isEditing: this.#mode !== AnnotationEditorType.NONE,\n isEmpty: this.#isEmpty(),\n hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),\n hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),\n hasSelectedEditor: false\n });\n } else {\n this.#removeFocusManager();\n this.#removeCopyPasteListeners();\n this.#dispatchUpdateStates({\n isEditing: false\n });\n this.disableUserSelect(false);\n }\n }\n registerEditorTypes(types) {\n if (this.#editorTypes) {\n return;\n }\n this.#editorTypes = types;\n for (const editorType of this.#editorTypes) {\n this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);\n }\n }\n getId() {\n return this.#idManager.id;\n }\n get currentLayer() {\n return this.#allLayers.get(this.#currentPageIndex);\n }\n getLayer(pageIndex) {\n return this.#allLayers.get(pageIndex);\n }\n get currentPageIndex() {\n return this.#currentPageIndex;\n }\n addLayer(layer) {\n this.#allLayers.set(layer.pageIndex, layer);\n if (this.#isEnabled) {\n layer.enable();\n } else {\n layer.disable();\n }\n }\n removeLayer(layer) {\n this.#allLayers.delete(layer.pageIndex);\n }\n async updateMode(mode, editId = null, isFromUser = false, isFromKeyboard = false, mustEnterInEditMode = false, editComment = false) {\n if (this.#mode === mode) {\n return;\n }\n if (this.#updateModeCapability) {\n await this.#updateModeCapability.promise;\n if (!this.#updateModeCapability) {\n return;\n }\n }\n this.#updateModeCapability = Promise.withResolvers();\n this.#currentDrawingSession?.commitOrRemove();\n if (this.#mode === AnnotationEditorType.POPUP) {\n this.#commentManager?.hideSidebar();\n }\n this.#commentManager?.destroyPopup();\n this.#mode = mode;\n if (mode === AnnotationEditorType.NONE) {\n this.setEditingState(false);\n this.#disableAll();\n for (const editor of this.#allEditors.values()) {\n editor.hideStandaloneCommentButton();\n }\n this._editorUndoBar?.hide();\n this.toggleComment(null);\n this.#updateModeCapability.resolve();\n return;\n }\n for (const editor of this.#allEditors.values()) {\n editor.addStandaloneCommentButton();\n }\n if (mode === AnnotationEditorType.SIGNATURE) {\n await this.#signatureManager?.loadSignatures();\n }\n if (isFromUser) {\n CurrentPointers.clearPointerType();\n }\n this.setEditingState(true);\n await this.#enableAll();\n this.unselectAll();\n for (const layer of this.#allLayers.values()) {\n layer.updateMode(mode);\n }\n if (mode === AnnotationEditorType.POPUP) {\n this.#allEditableAnnotations ||= await this.#pdfDocument.getAnnotationsByType(new Set(this.#editorTypes.map(editorClass => editorClass._editorType)));\n const elementIds = new Set();\n const allComments = [];\n for (const editor of this.#allEditors.values()) {\n const {\n annotationElementId,\n hasComment,\n deleted\n } = editor;\n if (annotationElementId) {\n elementIds.add(annotationElementId);\n }\n if (hasComment && !deleted) {\n allComments.push(editor.getData());\n }\n }\n for (const annotation of this.#allEditableAnnotations) {\n const {\n id,\n popupRef,\n contentsObj\n } = annotation;\n if (popupRef && contentsObj?.str && !elementIds.has(id) && !this.#deletedAnnotationsElementIds.has(id)) {\n allComments.push(annotation);\n }\n }\n this.#commentManager?.showSidebar(allComments);\n }\n if (!editId) {\n if (isFromKeyboard) {\n this.addNewEditorFromKeyboard();\n }\n this.#updateModeCapability.resolve();\n return;\n }\n for (const editor of this.#allEditors.values()) {\n if (editor.uid === editId) {\n this.setSelected(editor);\n if (editComment) {\n editor.editComment();\n } else if (mustEnterInEditMode) {\n editor.enterInEditMode();\n } else {\n editor.focus();\n }\n } else {\n editor.unselect();\n }\n }\n this.#updateModeCapability.resolve();\n }\n addNewEditorFromKeyboard() {\n if (this.currentLayer.canCreateNewEmptyEditor()) {\n this.currentLayer.addNewEditor();\n }\n }\n updateToolbar(options) {\n if (options.mode === this.#mode) {\n return;\n }\n this._eventBus.dispatch("switchannotationeditormode", {\n source: this,\n ...options\n });\n }\n updateParams(type, value) {\n if (!this.#editorTypes) {\n return;\n }\n switch (type) {\n case AnnotationEditorParamsType.CREATE:\n this.currentLayer.addNewEditor(value);\n return;\n case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:\n this._eventBus.dispatch("reporttelemetry", {\n source: this,\n details: {\n type: "editing",\n data: {\n type: "highlight",\n action: "toggle_visibility"\n }\n }\n });\n (this.#showAllStates ||= new Map()).set(type, value);\n this.showAllEditors("highlight", value);\n break;\n }\n if (this.hasSelection) {\n for (const editor of this.#selectedEditors) {\n editor.updateParams(type, value);\n }\n } else {\n for (const editorType of this.#editorTypes) {\n editorType.updateDefaultParams(type, value);\n }\n }\n }\n showAllEditors(type, visible, updateButton = false) {\n for (const editor of this.#allEditors.values()) {\n if (editor.editorType === type) {\n editor.show(visible);\n }\n }\n const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true;\n if (state !== visible) {\n this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]);\n }\n }\n enableWaiting(mustWait = false) {\n if (this.#isWaiting === mustWait) {\n return;\n }\n this.#isWaiting = mustWait;\n for (const layer of this.#allLayers.values()) {\n if (mustWait) {\n layer.disableClick();\n } else {\n layer.enableClick();\n }\n layer.div.classList.toggle("waiting", mustWait);\n }\n }\n async #enableAll() {\n if (!this.#isEnabled) {\n this.#isEnabled = true;\n const promises = [];\n for (const layer of this.#allLayers.values()) {\n promises.push(layer.enable());\n }\n await Promise.all(promises);\n for (const editor of this.#allEditors.values()) {\n editor.enable();\n }\n }\n }\n #disableAll() {\n this.unselectAll();\n if (this.#isEnabled) {\n this.#isEnabled = false;\n for (const layer of this.#allLayers.values()) {\n layer.disable();\n }\n for (const editor of this.#allEditors.values()) {\n editor.disable();\n }\n }\n }\n *getEditors(pageIndex) {\n for (const editor of this.#allEditors.values()) {\n if (editor.pageIndex === pageIndex) {\n yield editor;\n }\n }\n }\n getEditor(id) {\n return this.#allEditors.get(id);\n }\n addEditor(editor) {\n this.#allEditors.set(editor.id, editor);\n }\n removeEditor(editor) {\n if (editor.div.contains(document.activeElement)) {\n if (this.#focusMainContainerTimeoutId) {\n clearTimeout(this.#focusMainContainerTimeoutId);\n }\n this.#focusMainContainerTimeoutId = setTimeout(() => {\n this.focusMainContainer();\n this.#focusMainContainerTimeoutId = null;\n }, 0);\n }\n this.#allEditors.delete(editor.id);\n if (editor.annotationElementId) {\n this.#missingCanvases?.delete(editor.annotationElementId);\n }\n this.unselect(editor);\n if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) {\n this.#annotationStorage?.remove(editor.id);\n }\n }\n addDeletedAnnotationElement(editor) {\n this.#deletedAnnotationsElementIds.add(editor.annotationElementId);\n this.addChangedExistingAnnotation(editor);\n editor.deleted = true;\n }\n isDeletedAnnotationElement(annotationElementId) {\n return this.#deletedAnnotationsElementIds.has(annotationElementId);\n }\n removeDeletedAnnotationElement(editor) {\n this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);\n this.removeChangedExistingAnnotation(editor);\n editor.deleted = false;\n }\n #addEditorToLayer(editor) {\n const layer = this.#allLayers.get(editor.pageIndex);\n if (layer) {\n layer.addOrRebuild(editor);\n } else {\n this.addEditor(editor);\n this.addToAnnotationStorage(editor);\n }\n }\n setActiveEditor(editor) {\n if (this.#activeEditor === editor) {\n return;\n }\n this.#activeEditor = editor;\n if (editor) {\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n }\n }\n get #lastSelectedEditor() {\n let ed = null;\n for (ed of this.#selectedEditors) {}\n return ed;\n }\n updateUI(editor) {\n if (this.#lastSelectedEditor === editor) {\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n }\n }\n updateUIForDefaultProperties(editorType) {\n this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);\n }\n toggleSelected(editor) {\n if (this.#selectedEditors.has(editor)) {\n this.#selectedEditors.delete(editor);\n editor.unselect();\n this.#dispatchUpdateStates({\n hasSelectedEditor: this.hasSelection\n });\n return;\n }\n this.#selectedEditors.add(editor);\n editor.select();\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n this.#dispatchUpdateStates({\n hasSelectedEditor: true\n });\n }\n setSelected(editor) {\n this.updateToolbar({\n mode: editor.mode,\n editId: editor.uid\n });\n this.#currentDrawingSession?.commitOrRemove();\n for (const ed of this.#selectedEditors) {\n if (ed !== editor) {\n ed.unselect();\n }\n }\n this.#selectedEditors.clear();\n this.#selectedEditors.add(editor);\n editor.select();\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n this.#dispatchUpdateStates({\n hasSelectedEditor: true\n });\n }\n isSelected(editor) {\n return this.#selectedEditors.has(editor);\n }\n get firstSelectedEditor() {\n return this.#selectedEditors.values().next().value;\n }\n unselect(editor) {\n editor.unselect();\n this.#selectedEditors.delete(editor);\n this.#dispatchUpdateStates({\n hasSelectedEditor: this.hasSelection\n });\n }\n get hasSelection() {\n return this.#selectedEditors.size !== 0;\n }\n get isEnterHandled() {\n return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled;\n }\n undo() {\n this.#commandManager.undo();\n this.#dispatchUpdateStates({\n hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),\n hasSomethingToRedo: true,\n isEmpty: this.#isEmpty()\n });\n this._editorUndoBar?.hide();\n }\n redo() {\n this.#commandManager.redo();\n this.#dispatchUpdateStates({\n hasSomethingToUndo: true,\n hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),\n isEmpty: this.#isEmpty()\n });\n }\n addCommands(params) {\n this.#commandManager.add(params);\n this.#dispatchUpdateStates({\n hasSomethingToUndo: true,\n hasSomethingToRedo: false,\n isEmpty: this.#isEmpty()\n });\n }\n cleanUndoStack(type) {\n this.#commandManager.cleanType(type);\n }\n #isEmpty() {\n if (this.#allEditors.size === 0) {\n return true;\n }\n if (this.#allEditors.size === 1) {\n for (const editor of this.#allEditors.values()) {\n return editor.isEmpty();\n }\n }\n return false;\n }\n delete() {\n this.commitOrRemove();\n const drawingEditor = this.currentLayer?.endDrawingSession(true);\n if (!this.hasSelection && !drawingEditor) {\n return;\n }\n const editors = drawingEditor ? [drawingEditor] : [...this.#selectedEditors];\n const cmd = () => {\n this._editorUndoBar?.show(undo, editors.length === 1 ? editors[0].editorType : editors.length);\n for (const editor of editors) {\n editor.remove();\n }\n };\n const undo = () => {\n for (const editor of editors) {\n this.#addEditorToLayer(editor);\n }\n };\n this.addCommands({\n cmd,\n undo,\n mustExec: true\n });\n }\n commitOrRemove() {\n this.#activeEditor?.commitOrRemove();\n }\n hasSomethingToControl() {\n return this.#activeEditor || this.hasSelection;\n }\n #selectEditors(editors) {\n for (const editor of this.#selectedEditors) {\n editor.unselect();\n }\n this.#selectedEditors.clear();\n for (const editor of editors) {\n if (editor.isEmpty()) {\n continue;\n }\n this.#selectedEditors.add(editor);\n editor.select();\n }\n this.#dispatchUpdateStates({\n hasSelectedEditor: this.hasSelection\n });\n }\n selectAll() {\n for (const editor of this.#selectedEditors) {\n editor.commit();\n }\n this.#selectEditors(this.#allEditors.values());\n }\n unselectAll() {\n if (this.#activeEditor) {\n this.#activeEditor.commitOrRemove();\n if (this.#mode !== AnnotationEditorType.NONE) {\n return;\n }\n }\n if (this.#currentDrawingSession?.commitOrRemove()) {\n return;\n }\n if (!this.hasSelection) {\n return;\n }\n for (const editor of this.#selectedEditors) {\n editor.unselect();\n }\n this.#selectedEditors.clear();\n this.#dispatchUpdateStates({\n hasSelectedEditor: false\n });\n }\n translateSelectedEditors(x, y, noCommit = false) {\n if (!noCommit) {\n this.commitOrRemove();\n }\n if (!this.hasSelection) {\n return;\n }\n this.#translation[0] += x;\n this.#translation[1] += y;\n const [totalX, totalY] = this.#translation;\n const editors = [...this.#selectedEditors];\n const TIME_TO_WAIT = 1000;\n if (this.#translationTimeoutId) {\n clearTimeout(this.#translationTimeoutId);\n }\n this.#translationTimeoutId = setTimeout(() => {\n this.#translationTimeoutId = null;\n this.#translation[0] = this.#translation[1] = 0;\n this.addCommands({\n cmd: () => {\n for (const editor of editors) {\n if (this.#allEditors.has(editor.id)) {\n editor.translateInPage(totalX, totalY);\n editor.translationDone();\n }\n }\n },\n undo: () => {\n for (const editor of editors) {\n if (this.#allEditors.has(editor.id)) {\n editor.translateInPage(-totalX, -totalY);\n editor.translationDone();\n }\n }\n },\n mustExec: false\n });\n }, TIME_TO_WAIT);\n for (const editor of editors) {\n editor.translateInPage(x, y);\n editor.translationDone();\n }\n }\n setUpDragSession() {\n if (!this.hasSelection) {\n return;\n }\n this.disableUserSelect(true);\n this.#draggingEditors = new Map();\n for (const editor of this.#selectedEditors) {\n this.#draggingEditors.set(editor, {\n savedX: editor.x,\n savedY: editor.y,\n savedPageIndex: editor.pageIndex,\n newX: 0,\n newY: 0,\n newPageIndex: -1\n });\n }\n }\n endDragSession() {\n if (!this.#draggingEditors) {\n return false;\n }\n this.disableUserSelect(false);\n const map = this.#draggingEditors;\n this.#draggingEditors = null;\n let mustBeAddedInUndoStack = false;\n for (const [{\n x,\n y,\n pageIndex\n }, value] of map) {\n value.newX = x;\n value.newY = y;\n value.newPageIndex = pageIndex;\n mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex;\n }\n if (!mustBeAddedInUndoStack) {\n return false;\n }\n const move = (editor, x, y, pageIndex) => {\n if (this.#allEditors.has(editor.id)) {\n const parent = this.#allLayers.get(pageIndex);\n if (parent) {\n editor._setParentAndPosition(parent, x, y);\n } else {\n editor.pageIndex = pageIndex;\n editor.x = x;\n editor.y = y;\n }\n }\n };\n this.addCommands({\n cmd: () => {\n for (const [editor, {\n newX,\n newY,\n newPageIndex\n }] of map) {\n move(editor, newX, newY, newPageIndex);\n }\n },\n undo: () => {\n for (const [editor, {\n savedX,\n savedY,\n savedPageIndex\n }] of map) {\n move(editor, savedX, savedY, savedPageIndex);\n }\n },\n mustExec: true\n });\n return true;\n }\n dragSelectedEditors(tx, ty) {\n if (!this.#draggingEditors) {\n return;\n }\n for (const editor of this.#draggingEditors.keys()) {\n editor.drag(tx, ty);\n }\n }\n rebuild(editor) {\n if (editor.parent === null) {\n const parent = this.getLayer(editor.pageIndex);\n if (parent) {\n parent.changeParent(editor);\n parent.addOrRebuild(editor);\n } else {\n this.addEditor(editor);\n this.addToAnnotationStorage(editor);\n editor.rebuild();\n }\n } else {\n editor.parent.addOrRebuild(editor);\n }\n }\n get isEditorHandlingKeyboard() {\n return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents();\n }\n isActive(editor) {\n return this.#activeEditor === editor;\n }\n getActive() {\n return this.#activeEditor;\n }\n getMode() {\n return this.#mode;\n }\n isEditingMode() {\n return this.#mode !== AnnotationEditorType.NONE;\n }\n get imageManager() {\n return shadow(this, "imageManager", new ImageManager());\n }\n getSelectionBoxes(textLayer) {\n if (!textLayer) {\n return null;\n }\n const selection = document.getSelection();\n for (let i = 0, ii = selection.rangeCount; i < ii; i++) {\n if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) {\n return null;\n }\n }\n const {\n x: layerX,\n y: layerY,\n width: parentWidth,\n height: parentHeight\n } = textLayer.getBoundingClientRect();\n let rotator;\n switch (textLayer.getAttribute("data-main-rotation")) {\n case "90":\n rotator = (x, y, w, h) => ({\n x: (y - layerY) / parentHeight,\n y: 1 - (x + w - layerX) / parentWidth,\n width: h / parentHeight,\n height: w / parentWidth\n });\n break;\n case "180":\n rotator = (x, y, w, h) => ({\n x: 1 - (x + w - layerX) / parentWidth,\n y: 1 - (y + h - layerY) / parentHeight,\n width: w / parentWidth,\n height: h / parentHeight\n });\n break;\n case "270":\n rotator = (x, y, w, h) => ({\n x: 1 - (y + h - layerY) / parentHeight,\n y: (x - layerX) / parentWidth,\n width: h / parentHeight,\n height: w / parentWidth\n });\n break;\n default:\n rotator = (x, y, w, h) => ({\n x: (x - layerX) / parentWidth,\n y: (y - layerY) / parentHeight,\n width: w / parentWidth,\n height: h / parentHeight\n });\n break;\n }\n const boxes = [];\n for (let i = 0, ii = selection.rangeCount; i < ii; i++) {\n const range = selection.getRangeAt(i);\n if (range.collapsed) {\n continue;\n }\n for (const {\n x,\n y,\n width,\n height\n } of range.getClientRects()) {\n if (width === 0 || height === 0) {\n continue;\n }\n boxes.push(rotator(x, y, width, height));\n }\n }\n return boxes.length === 0 ? null : boxes;\n }\n addChangedExistingAnnotation({\n annotationElementId,\n id\n }) {\n (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id);\n }\n removeChangedExistingAnnotation({\n annotationElementId\n }) {\n this.#changedExistingAnnotations?.delete(annotationElementId);\n }\n renderAnnotationElement(annotation) {\n const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);\n if (!editorId) {\n return;\n }\n const editor = this.#annotationStorage.getRawValue(editorId);\n if (!editor) {\n return;\n }\n if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {\n return;\n }\n editor.renderAnnotationElement(annotation);\n }\n setMissingCanvas(annotationId, annotationElementId, canvas) {\n const editor = this.#missingCanvases?.get(annotationId);\n if (!editor) {\n return;\n }\n editor.setCanvas(annotationElementId, canvas);\n this.#missingCanvases.delete(annotationId);\n }\n addMissingCanvas(annotationId, editor) {\n (this.#missingCanvases ||= new Map()).set(annotationId, editor);\n }\n}\n\n;// ./src/display/editor/alt_text.js\n\nclass AltText {\n #altText = null;\n #altTextDecorative = false;\n #altTextButton = null;\n #altTextButtonLabel = null;\n #altTextTooltip = null;\n #altTextTooltipTimeout = null;\n #altTextWasFromKeyBoard = false;\n #badge = null;\n #editor = null;\n #guessedText = null;\n #textWithDisclaimer = null;\n #useNewAltTextFlow = false;\n static #l10nNewButton = null;\n static _l10n = null;\n constructor(editor) {\n this.#editor = editor;\n this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;\n AltText.#l10nNewButton ||= Object.freeze({\n added: "pdfjs-editor-new-alt-text-added-button",\n "added-label": "pdfjs-editor-new-alt-text-added-button-label",\n missing: "pdfjs-editor-new-alt-text-missing-button",\n "missing-label": "pdfjs-editor-new-alt-text-missing-button-label",\n review: "pdfjs-editor-new-alt-text-to-review-button",\n "review-label": "pdfjs-editor-new-alt-text-to-review-button-label"\n });\n }\n static initialize(l10n) {\n AltText._l10n ??= l10n;\n }\n async render() {\n const altText = this.#altTextButton = document.createElement("button");\n altText.className = "altText";\n altText.tabIndex = "0";\n const label = this.#altTextButtonLabel = document.createElement("span");\n altText.append(label);\n if (this.#useNewAltTextFlow) {\n altText.classList.add("new");\n altText.setAttribute("data-l10n-id", AltText.#l10nNewButton.missing);\n label.setAttribute("data-l10n-id", AltText.#l10nNewButton["missing-label"]);\n } else {\n altText.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button");\n label.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button-label");\n }\n const signal = this.#editor._uiManager._signal;\n altText.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n altText.addEventListener("pointerdown", event => event.stopPropagation(), {\n signal\n });\n const onClick = event => {\n event.preventDefault();\n this.#editor._uiManager.editAltText(this.#editor);\n if (this.#useNewAltTextFlow) {\n this.#editor._reportTelemetry({\n action: "pdfjs.image.alt_text.image_status_label_clicked",\n data: {\n label: this.#label\n }\n });\n }\n };\n altText.addEventListener("click", onClick, {\n capture: true,\n signal\n });\n altText.addEventListener("keydown", event => {\n if (event.target === altText && event.key === "Enter") {\n this.#altTextWasFromKeyBoard = true;\n onClick(event);\n }\n }, {\n signal\n });\n await this.#setState();\n return altText;\n }\n get #label() {\n return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing";\n }\n finish() {\n if (!this.#altTextButton) {\n return;\n }\n this.#altTextButton.focus({\n focusVisible: this.#altTextWasFromKeyBoard\n });\n this.#altTextWasFromKeyBoard = false;\n }\n isEmpty() {\n if (this.#useNewAltTextFlow) {\n return this.#altText === null;\n }\n return !this.#altText && !this.#altTextDecorative;\n }\n hasData() {\n if (this.#useNewAltTextFlow) {\n return this.#altText !== null || !!this.#guessedText;\n }\n return this.isEmpty();\n }\n get guessedText() {\n return this.#guessedText;\n }\n async setGuessedText(guessedText) {\n if (this.#altText !== null) {\n return;\n }\n this.#guessedText = guessedText;\n this.#textWithDisclaimer = await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer", {\n generatedAltText: guessedText\n });\n this.#setState();\n }\n toggleAltTextBadge(visibility = false) {\n if (!this.#useNewAltTextFlow || this.#altText) {\n this.#badge?.remove();\n this.#badge = null;\n return;\n }\n if (!this.#badge) {\n const badge = this.#badge = document.createElement("div");\n badge.className = "noAltTextBadge";\n this.#editor.div.append(badge);\n }\n this.#badge.classList.toggle("hidden", !visibility);\n }\n serialize(isForCopying) {\n let altText = this.#altText;\n if (!isForCopying && this.#guessedText === altText) {\n altText = this.#textWithDisclaimer;\n }\n return {\n altText,\n decorative: this.#altTextDecorative,\n guessedText: this.#guessedText,\n textWithDisclaimer: this.#textWithDisclaimer\n };\n }\n get data() {\n return {\n altText: this.#altText,\n decorative: this.#altTextDecorative\n };\n }\n set data({\n altText,\n decorative,\n guessedText,\n textWithDisclaimer,\n cancel = false\n }) {\n if (guessedText) {\n this.#guessedText = guessedText;\n this.#textWithDisclaimer = textWithDisclaimer;\n }\n if (this.#altText === altText && this.#altTextDecorative === decorative) {\n return;\n }\n if (!cancel) {\n this.#altText = altText;\n this.#altTextDecorative = decorative;\n }\n this.#setState();\n }\n toggle(enabled = false) {\n if (!this.#altTextButton) {\n return;\n }\n if (!enabled && this.#altTextTooltipTimeout) {\n clearTimeout(this.#altTextTooltipTimeout);\n this.#altTextTooltipTimeout = null;\n }\n this.#altTextButton.disabled = !enabled;\n }\n shown() {\n this.#editor._reportTelemetry({\n action: "pdfjs.image.alt_text.image_status_label_displayed",\n data: {\n label: this.#label\n }\n });\n }\n destroy() {\n this.#altTextButton?.remove();\n this.#altTextButton = null;\n this.#altTextButtonLabel = null;\n this.#altTextTooltip = null;\n this.#badge?.remove();\n this.#badge = null;\n }\n async #setState() {\n const button = this.#altTextButton;\n if (!button) {\n return;\n }\n if (this.#useNewAltTextFlow) {\n button.classList.toggle("done", !!this.#altText);\n button.setAttribute("data-l10n-id", AltText.#l10nNewButton[this.#label]);\n this.#altTextButtonLabel?.setAttribute("data-l10n-id", AltText.#l10nNewButton[`${this.#label}-label`]);\n if (!this.#altText) {\n this.#altTextTooltip?.remove();\n return;\n }\n } else {\n if (!this.#altText && !this.#altTextDecorative) {\n button.classList.remove("done");\n this.#altTextTooltip?.remove();\n return;\n }\n button.classList.add("done");\n button.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-edit-button");\n }\n let tooltip = this.#altTextTooltip;\n if (!tooltip) {\n this.#altTextTooltip = tooltip = document.createElement("span");\n tooltip.className = "tooltip";\n tooltip.setAttribute("role", "tooltip");\n tooltip.id = `alt-text-tooltip-${this.#editor.id}`;\n const DELAY_TO_SHOW_TOOLTIP = 100;\n const signal = this.#editor._uiManager._signal;\n signal.addEventListener("abort", () => {\n clearTimeout(this.#altTextTooltipTimeout);\n this.#altTextTooltipTimeout = null;\n }, {\n once: true\n });\n button.addEventListener("mouseenter", () => {\n this.#altTextTooltipTimeout = setTimeout(() => {\n this.#altTextTooltipTimeout = null;\n this.#altTextTooltip.classList.add("show");\n this.#editor._reportTelemetry({\n action: "alt_text_tooltip"\n });\n }, DELAY_TO_SHOW_TOOLTIP);\n }, {\n signal\n });\n button.addEventListener("mouseleave", () => {\n if (this.#altTextTooltipTimeout) {\n clearTimeout(this.#altTextTooltipTimeout);\n this.#altTextTooltipTimeout = null;\n }\n this.#altTextTooltip?.classList.remove("show");\n }, {\n signal\n });\n }\n if (this.#altTextDecorative) {\n tooltip.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-decorative-tooltip");\n } else {\n tooltip.removeAttribute("data-l10n-id");\n tooltip.textContent = this.#altText;\n }\n if (!tooltip.parentNode) {\n button.append(tooltip);\n }\n const element = this.#editor.getElementForAltText();\n element?.setAttribute("aria-describedby", tooltip.id);\n }\n}\n\n;// ./src/display/editor/comment.js\n\nclass Comment {\n #commentStandaloneButton = null;\n #commentToolbarButton = null;\n #commentWasFromKeyBoard = false;\n #editor = null;\n #initialText = null;\n #richText = null;\n #text = null;\n #date = null;\n #deleted = false;\n #popupPosition = null;\n constructor(editor) {\n this.#editor = editor;\n }\n renderForToolbar() {\n const button = this.#commentToolbarButton = document.createElement("button");\n button.className = "comment";\n return this.#render(button, false);\n }\n renderForStandalone() {\n const button = this.#commentStandaloneButton = document.createElement("button");\n button.className = "annotationCommentButton";\n const position = this.#editor.commentButtonPosition;\n if (position) {\n const {\n style\n } = button;\n style.insetInlineEnd = `calc(${100 * (this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0])}% - var(--comment-button-dim))`;\n style.top = `calc(${100 * position[1]}% - var(--comment-button-dim))`;\n const color = this.#editor.commentButtonColor;\n if (color) {\n style.backgroundColor = color;\n }\n }\n return this.#render(button, true);\n }\n focusButton() {\n setTimeout(() => {\n (this.#commentStandaloneButton ?? this.#commentToolbarButton)?.focus();\n }, 0);\n }\n onUpdatedColor() {\n if (!this.#commentStandaloneButton) {\n return;\n }\n const color = this.#editor.commentButtonColor;\n if (color) {\n this.#commentStandaloneButton.style.backgroundColor = color;\n }\n this.#editor._uiManager.updatePopupColor(this.#editor);\n }\n get commentButtonWidth() {\n return (this.#commentStandaloneButton?.getBoundingClientRect().width ?? 0) / this.#editor.parent.boundingClientRect.width;\n }\n get commentPopupPositionInLayer() {\n if (this.#popupPosition) {\n return this.#popupPosition;\n }\n if (!this.#commentStandaloneButton) {\n return null;\n }\n const {\n x,\n y,\n height\n } = this.#commentStandaloneButton.getBoundingClientRect();\n const {\n x: parentX,\n y: parentY,\n width: parentWidth,\n height: parentHeight\n } = this.#editor.parent.boundingClientRect;\n return [(x - parentX) / parentWidth, (y + height - parentY) / parentHeight];\n }\n set commentPopupPositionInLayer(pos) {\n this.#popupPosition = pos;\n }\n hasDefaultPopupPosition() {\n return this.#popupPosition === null;\n }\n removeStandaloneCommentButton() {\n this.#commentStandaloneButton?.remove();\n this.#commentStandaloneButton = null;\n }\n removeToolbarCommentButton() {\n this.#commentToolbarButton?.remove();\n this.#commentToolbarButton = null;\n }\n setCommentButtonStates({\n selected,\n hasPopup\n }) {\n if (!this.#commentStandaloneButton) {\n return;\n }\n this.#commentStandaloneButton.classList.toggle("selected", selected);\n this.#commentStandaloneButton.ariaExpanded = hasPopup;\n }\n #render(comment, isStandalone) {\n if (!this.#editor._uiManager.hasCommentManager()) {\n return null;\n }\n comment.tabIndex = "0";\n comment.ariaHasPopup = "dialog";\n if (isStandalone) {\n comment.ariaControls = "commentPopup";\n comment.setAttribute("data-l10n-id", "pdfjs-show-comment-button");\n } else {\n comment.ariaControlsElements = [this.#editor._uiManager.getCommentDialogElement()];\n comment.setAttribute("data-l10n-id", "pdfjs-editor-add-comment-button");\n }\n const signal = this.#editor._uiManager._signal;\n if (!(signal instanceof AbortSignal) || signal.aborted) {\n return comment;\n }\n comment.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n if (isStandalone) {\n comment.addEventListener("focusin", e => {\n this.#editor._focusEventsAllowed = false;\n stopEvent(e);\n }, {\n capture: true,\n signal\n });\n comment.addEventListener("focusout", e => {\n this.#editor._focusEventsAllowed = true;\n stopEvent(e);\n }, {\n capture: true,\n signal\n });\n }\n comment.addEventListener("pointerdown", event => event.stopPropagation(), {\n signal\n });\n const onClick = event => {\n event.preventDefault();\n if (comment === this.#commentToolbarButton) {\n this.edit();\n } else {\n this.#editor.toggleComment(true);\n }\n };\n comment.addEventListener("click", onClick, {\n capture: true,\n signal\n });\n comment.addEventListener("keydown", event => {\n if (event.target === comment && event.key === "Enter") {\n this.#commentWasFromKeyBoard = true;\n onClick(event);\n }\n }, {\n signal\n });\n comment.addEventListener("pointerenter", () => {\n this.#editor.toggleComment(false, true);\n }, {\n signal\n });\n comment.addEventListener("pointerleave", () => {\n this.#editor.toggleComment(false, false);\n }, {\n signal\n });\n return comment;\n }\n edit(options) {\n const position = this.commentPopupPositionInLayer;\n let posX, posY;\n if (position) {\n [posX, posY] = position;\n } else {\n [posX, posY] = this.#editor.commentButtonPosition;\n const {\n width,\n height,\n x,\n y\n } = this.#editor;\n posX = x + posX * width;\n posY = y + posY * height;\n }\n const parentDimensions = this.#editor.parent.boundingClientRect;\n const {\n x: parentX,\n y: parentY,\n width: parentWidth,\n height: parentHeight\n } = parentDimensions;\n this.#editor._uiManager.editComment(this.#editor, parentX + posX * parentWidth, parentY + posY * parentHeight, {\n ...options,\n parentDimensions\n });\n }\n finish() {\n if (!this.#commentToolbarButton) {\n return;\n }\n this.#commentToolbarButton.focus({\n focusVisible: this.#commentWasFromKeyBoard\n });\n this.#commentWasFromKeyBoard = false;\n }\n isDeleted() {\n return this.#deleted || this.#text === "";\n }\n isEmpty() {\n return this.#text === null;\n }\n hasBeenEdited() {\n return this.isDeleted() || this.#text !== this.#initialText;\n }\n serialize() {\n return this.data;\n }\n get data() {\n return {\n text: this.#text,\n richText: this.#richText,\n date: this.#date,\n deleted: this.isDeleted()\n };\n }\n set data(text) {\n if (text !== this.#text) {\n this.#richText = null;\n }\n if (text === null) {\n this.#text = "";\n this.#deleted = true;\n return;\n }\n this.#text = text;\n this.#date = new Date();\n this.#deleted = false;\n }\n restoreData({\n text,\n richText,\n date\n }) {\n this.#text = text;\n this.#richText = richText;\n this.#date = date;\n this.#deleted = false;\n }\n setInitialText(text, richText = null) {\n this.#initialText = text;\n this.data = text;\n this.#date = null;\n this.#richText = richText;\n }\n shown() {}\n destroy() {\n this.#commentToolbarButton?.remove();\n this.#commentToolbarButton = null;\n this.#commentStandaloneButton?.remove();\n this.#commentStandaloneButton = null;\n this.#text = "";\n this.#richText = null;\n this.#date = null;\n this.#editor = null;\n this.#commentWasFromKeyBoard = false;\n this.#deleted = false;\n }\n}\n\n;// ./src/display/touch_manager.js\n\nclass TouchManager {\n #container;\n #isPinching = false;\n #isPinchingStopped = null;\n #isPinchingDisabled;\n #onPinchStart;\n #onPinching;\n #onPinchEnd;\n #pointerDownAC = null;\n #signal;\n #touchInfo = null;\n #touchManagerAC;\n #touchMoveAC = null;\n constructor({\n container,\n isPinchingDisabled = null,\n isPinchingStopped = null,\n onPinchStart = null,\n onPinching = null,\n onPinchEnd = null,\n signal\n }) {\n this.#container = container;\n this.#isPinchingStopped = isPinchingStopped;\n this.#isPinchingDisabled = isPinchingDisabled;\n this.#onPinchStart = onPinchStart;\n this.#onPinching = onPinching;\n this.#onPinchEnd = onPinchEnd;\n this.#touchManagerAC = new AbortController();\n this.#signal = AbortSignal.any([signal, this.#touchManagerAC.signal]);\n container.addEventListener("touchstart", this.#onTouchStart.bind(this), {\n passive: false,\n signal: this.#signal\n });\n }\n get MIN_TOUCH_DISTANCE_TO_PINCH() {\n return 35 / OutputScale.pixelRatio;\n }\n #onTouchStart(evt) {\n if (this.#isPinchingDisabled?.()) {\n return;\n }\n if (evt.touches.length === 1) {\n if (this.#pointerDownAC) {\n return;\n }\n const pointerDownAC = this.#pointerDownAC = new AbortController();\n const signal = AbortSignal.any([this.#signal, pointerDownAC.signal]);\n const container = this.#container;\n const opts = {\n capture: true,\n signal,\n passive: false\n };\n const cancelPointerDown = e => {\n if (e.pointerType === "touch") {\n this.#pointerDownAC?.abort();\n this.#pointerDownAC = null;\n }\n };\n container.addEventListener("pointerdown", e => {\n if (e.pointerType === "touch") {\n stopEvent(e);\n cancelPointerDown(e);\n }\n }, opts);\n container.addEventListener("pointerup", cancelPointerDown, opts);\n container.addEventListener("pointercancel", cancelPointerDown, opts);\n return;\n }\n if (!this.#touchMoveAC) {\n this.#touchMoveAC = new AbortController();\n const signal = AbortSignal.any([this.#signal, this.#touchMoveAC.signal]);\n const container = this.#container;\n const opt = {\n signal,\n capture: false,\n passive: false\n };\n container.addEventListener("touchmove", this.#onTouchMove.bind(this), opt);\n const onTouchEnd = this.#onTouchEnd.bind(this);\n container.addEventListener("touchend", onTouchEnd, opt);\n container.addEventListener("touchcancel", onTouchEnd, opt);\n opt.capture = true;\n container.addEventListener("pointerdown", stopEvent, opt);\n container.addEventListener("pointermove", stopEvent, opt);\n container.addEventListener("pointercancel", stopEvent, opt);\n container.addEventListener("pointerup", stopEvent, opt);\n this.#onPinchStart?.();\n }\n stopEvent(evt);\n if (evt.touches.length !== 2 || this.#isPinchingStopped?.()) {\n this.#touchInfo = null;\n return;\n }\n let [touch0, touch1] = evt.touches;\n if (touch0.identifier > touch1.identifier) {\n [touch0, touch1] = [touch1, touch0];\n }\n this.#touchInfo = {\n touch0X: touch0.screenX,\n touch0Y: touch0.screenY,\n touch1X: touch1.screenX,\n touch1Y: touch1.screenY\n };\n }\n #onTouchMove(evt) {\n if (!this.#touchInfo || evt.touches.length !== 2) {\n return;\n }\n stopEvent(evt);\n let [touch0, touch1] = evt.touches;\n if (touch0.identifier > touch1.identifier) {\n [touch0, touch1] = [touch1, touch0];\n }\n const {\n screenX: screen0X,\n screenY: screen0Y\n } = touch0;\n const {\n screenX: screen1X,\n screenY: screen1Y\n } = touch1;\n const touchInfo = this.#touchInfo;\n const {\n touch0X: pTouch0X,\n touch0Y: pTouch0Y,\n touch1X: pTouch1X,\n touch1Y: pTouch1Y\n } = touchInfo;\n const prevGapX = pTouch1X - pTouch0X;\n const prevGapY = pTouch1Y - pTouch0Y;\n const currGapX = screen1X - screen0X;\n const currGapY = screen1Y - screen0Y;\n const distance = Math.hypot(currGapX, currGapY) || 1;\n const pDistance = Math.hypot(prevGapX, prevGapY) || 1;\n if (!this.#isPinching && Math.abs(pDistance - distance) <= TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH) {\n return;\n }\n touchInfo.touch0X = screen0X;\n touchInfo.touch0Y = screen0Y;\n touchInfo.touch1X = screen1X;\n touchInfo.touch1Y = screen1Y;\n if (!this.#isPinching) {\n this.#isPinching = true;\n return;\n }\n const origin = [(screen0X + screen1X) / 2, (screen0Y + screen1Y) / 2];\n this.#onPinching?.(origin, pDistance, distance);\n }\n #onTouchEnd(evt) {\n if (evt.touches.length >= 2) {\n return;\n }\n if (this.#touchMoveAC) {\n this.#touchMoveAC.abort();\n this.#touchMoveAC = null;\n this.#onPinchEnd?.();\n }\n if (!this.#touchInfo) {\n return;\n }\n stopEvent(evt);\n this.#touchInfo = null;\n this.#isPinching = false;\n }\n destroy() {\n this.#touchManagerAC?.abort();\n this.#touchManagerAC = null;\n this.#pointerDownAC?.abort();\n this.#pointerDownAC = null;\n }\n}\n\n;// ./src/display/editor/editor.js\n\n\n\n\n\n\n\n\n\nclass AnnotationEditor {\n #accessibilityData = null;\n #allResizerDivs = null;\n #altText = null;\n #comment = null;\n #commentStandaloneButton = null;\n #disabled = false;\n #dragPointerId = null;\n #dragPointerType = "";\n #resizersDiv = null;\n #lastPointerCoords = null;\n #savedDimensions = null;\n #fakeAnnotation = null;\n #focusAC = null;\n #focusedResizerName = "";\n #hasBeenClicked = false;\n #initialRect = null;\n #isEditing = false;\n #isInEditMode = false;\n #isResizerEnabledForKeyboard = false;\n #moveInDOMTimeout = null;\n #prevDragX = 0;\n #prevDragY = 0;\n #telemetryTimeouts = null;\n #touchManager = null;\n isSelected = false;\n _isCopy = false;\n _editToolbar = null;\n _initialOptions = Object.create(null);\n _initialData = null;\n _isVisible = true;\n _uiManager = null;\n _focusEventsAllowed = true;\n static _l10n = null;\n static _l10nResizer = null;\n #isDraggable = false;\n #zIndex = AnnotationEditor._zIndex++;\n static _borderLineWidth = -1;\n static _colorManager = new ColorManager();\n static _zIndex = 1;\n static _telemetryTimeout = 1000;\n static get _resizerKeyboardManager() {\n const resize = AnnotationEditor.prototype._resizeWithKeyboard;\n const small = AnnotationEditorUIManager.TRANSLATE_SMALL;\n const big = AnnotationEditorUIManager.TRANSLATE_BIG;\n return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, {\n args: [-small, 0]\n }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, {\n args: [-big, 0]\n }], [["ArrowRight", "mac+ArrowRight"], resize, {\n args: [small, 0]\n }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, {\n args: [big, 0]\n }], [["ArrowUp", "mac+ArrowUp"], resize, {\n args: [0, -small]\n }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, {\n args: [0, -big]\n }], [["ArrowDown", "mac+ArrowDown"], resize, {\n args: [0, small]\n }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, {\n args: [0, big]\n }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]]));\n }\n constructor(parameters) {\n this.parent = parameters.parent;\n this.id = parameters.id;\n this.width = this.height = null;\n this.pageIndex = parameters.parent.pageIndex;\n this.name = parameters.name;\n this.div = null;\n this._uiManager = parameters.uiManager;\n this.annotationElementId = null;\n this._willKeepAspectRatio = false;\n this._initialOptions.isCentered = parameters.isCentered;\n this._structTreeParentId = null;\n this.annotationElementId = parameters.annotationElementId || null;\n this.creationDate = parameters.creationDate || new Date();\n this.modificationDate = parameters.modificationDate || null;\n this.canAddComment = true;\n const {\n rotation,\n rawDims: {\n pageWidth,\n pageHeight,\n pageX,\n pageY\n }\n } = this.parent.viewport;\n this.rotation = rotation;\n this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360;\n this.pageDimensions = [pageWidth, pageHeight];\n this.pageTranslation = [pageX, pageY];\n const [width, height] = this.parentDimensions;\n this.x = parameters.x / width;\n this.y = parameters.y / height;\n this.isAttachedToDOM = false;\n this.deleted = false;\n }\n updatePageIndex(newPageIndex) {\n this.pageIndex = newPageIndex;\n }\n get editorType() {\n return Object.getPrototypeOf(this).constructor._type;\n }\n get mode() {\n return Object.getPrototypeOf(this).constructor._editorType;\n }\n static get isDrawer() {\n return false;\n }\n static get _defaultLineColor() {\n return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));\n }\n static deleteAnnotationElement(editor) {\n const fakeEditor = new FakeEditor({\n id: editor.parent.getNextId(),\n parent: editor.parent,\n uiManager: editor._uiManager\n });\n fakeEditor.annotationElementId = editor.annotationElementId;\n fakeEditor.deleted = true;\n fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);\n }\n static initialize(l10n, _uiManager) {\n AnnotationEditor._l10n ??= l10n;\n AnnotationEditor._l10nResizer ||= Object.freeze({\n topLeft: "pdfjs-editor-resizer-top-left",\n topMiddle: "pdfjs-editor-resizer-top-middle",\n topRight: "pdfjs-editor-resizer-top-right",\n middleRight: "pdfjs-editor-resizer-middle-right",\n bottomRight: "pdfjs-editor-resizer-bottom-right",\n bottomMiddle: "pdfjs-editor-resizer-bottom-middle",\n bottomLeft: "pdfjs-editor-resizer-bottom-left",\n middleLeft: "pdfjs-editor-resizer-middle-left"\n });\n if (AnnotationEditor._borderLineWidth !== -1) {\n return;\n }\n const style = getComputedStyle(document.documentElement);\n AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0;\n }\n static updateDefaultParams(_type, _value) {}\n static get defaultPropertiesToUpdate() {\n return [];\n }\n static isHandlingMimeForPasting(mime) {\n return false;\n }\n static paste(item, parent) {\n unreachable("Not implemented");\n }\n get propertiesToUpdate() {\n return [];\n }\n get _isDraggable() {\n return this.#isDraggable;\n }\n set _isDraggable(value) {\n this.#isDraggable = value;\n this.div?.classList.toggle("draggable", value);\n }\n get uid() {\n return this.annotationElementId || this.id;\n }\n get isEnterHandled() {\n return true;\n }\n center() {\n const [pageWidth, pageHeight] = this.pageDimensions;\n switch (this.parentRotation) {\n case 90:\n this.x -= this.height * pageHeight / (pageWidth * 2);\n this.y += this.width * pageWidth / (pageHeight * 2);\n break;\n case 180:\n this.x += this.width / 2;\n this.y += this.height / 2;\n break;\n case 270:\n this.x += this.height * pageHeight / (pageWidth * 2);\n this.y -= this.width * pageWidth / (pageHeight * 2);\n break;\n default:\n this.x -= this.width / 2;\n this.y -= this.height / 2;\n break;\n }\n this.fixAndSetPosition();\n }\n addCommands(params) {\n this._uiManager.addCommands(params);\n }\n get currentLayer() {\n return this._uiManager.currentLayer;\n }\n setInBackground() {\n this.div.style.zIndex = 0;\n }\n setInForeground() {\n this.div.style.zIndex = this.#zIndex;\n }\n setParent(parent) {\n if (parent !== null) {\n this.pageIndex = parent.pageIndex;\n this.pageDimensions = parent.pageDimensions;\n } else {\n this.#stopResizing();\n this.#fakeAnnotation?.remove();\n this.#fakeAnnotation = null;\n }\n this.parent = parent;\n }\n focusin(event) {\n if (!this._focusEventsAllowed) {\n return;\n }\n if (!this.#hasBeenClicked) {\n this.parent.setSelected(this);\n } else {\n this.#hasBeenClicked = false;\n }\n }\n focusout(event) {\n if (!this._focusEventsAllowed) {\n return;\n }\n if (!this.isAttachedToDOM) {\n return;\n }\n const target = event.relatedTarget;\n if (target?.closest(`#${this.id}`)) {\n return;\n }\n event.preventDefault();\n if (!this.parent?.isMultipleSelection) {\n this.commitOrRemove();\n }\n }\n commitOrRemove() {\n if (this.isEmpty()) {\n this.remove();\n } else {\n this.commit();\n }\n }\n commit() {\n if (!this.isInEditMode()) {\n return;\n }\n this.addToAnnotationStorage();\n }\n addToAnnotationStorage() {\n this._uiManager.addToAnnotationStorage(this);\n }\n setAt(x, y, tx, ty) {\n const [width, height] = this.parentDimensions;\n [tx, ty] = this.screenToPageTranslation(tx, ty);\n this.x = (x + tx) / width;\n this.y = (y + ty) / height;\n this.fixAndSetPosition();\n }\n _moveAfterPaste(baseX, baseY) {\n const [parentWidth, parentHeight] = this.parentDimensions;\n this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);\n this._onTranslated();\n }\n #translate([width, height], x, y) {\n [x, y] = this.screenToPageTranslation(x, y);\n this.x += x / width;\n this.y += y / height;\n this._onTranslating(this.x, this.y);\n this.fixAndSetPosition();\n }\n translate(x, y) {\n this.#translate(this.parentDimensions, x, y);\n }\n translateInPage(x, y) {\n this.#initialRect ||= [this.x, this.y, this.width, this.height];\n this.#translate(this.pageDimensions, x, y);\n this.div.scrollIntoView({\n block: "nearest"\n });\n }\n translationDone() {\n this._onTranslated(this.x, this.y);\n }\n drag(tx, ty) {\n this.#initialRect ||= [this.x, this.y, this.width, this.height];\n const {\n div,\n parentDimensions: [parentWidth, parentHeight]\n } = this;\n this.x += tx / parentWidth;\n this.y += ty / parentHeight;\n if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {\n const {\n x,\n y\n } = this.div.getBoundingClientRect();\n if (this.parent.findNewParent(this, x, y)) {\n this.x -= Math.floor(this.x);\n this.y -= Math.floor(this.y);\n }\n }\n let {\n x,\n y\n } = this;\n const [bx, by] = this.getBaseTranslation();\n x += bx;\n y += by;\n const {\n style\n } = div;\n style.left = `${(100 * x).toFixed(2)}%`;\n style.top = `${(100 * y).toFixed(2)}%`;\n this._onTranslating(x, y);\n div.scrollIntoView({\n block: "nearest"\n });\n }\n _onTranslating(x, y) {}\n _onTranslated(x, y) {}\n get _hasBeenMoved() {\n return !!this.#initialRect && (this.#initialRect[0] !== this.x || this.#initialRect[1] !== this.y);\n }\n get _hasBeenResized() {\n return !!this.#initialRect && (this.#initialRect[2] !== this.width || this.#initialRect[3] !== this.height);\n }\n getBaseTranslation() {\n const [parentWidth, parentHeight] = this.parentDimensions;\n const {\n _borderLineWidth\n } = AnnotationEditor;\n const x = _borderLineWidth / parentWidth;\n const y = _borderLineWidth / parentHeight;\n switch (this.rotation) {\n case 90:\n return [-x, y];\n case 180:\n return [x, y];\n case 270:\n return [x, -y];\n default:\n return [-x, -y];\n }\n }\n get _mustFixPosition() {\n return true;\n }\n fixAndSetPosition(rotation = this.rotation) {\n const {\n div: {\n style\n },\n pageDimensions: [pageWidth, pageHeight]\n } = this;\n let {\n x,\n y,\n width,\n height\n } = this;\n width *= pageWidth;\n height *= pageHeight;\n x *= pageWidth;\n y *= pageHeight;\n if (this._mustFixPosition) {\n switch (rotation) {\n case 0:\n x = MathClamp(x, 0, pageWidth - width);\n y = MathClamp(y, 0, pageHeight - height);\n break;\n case 90:\n x = MathClamp(x, 0, pageWidth - height);\n y = MathClamp(y, width, pageHeight);\n break;\n case 180:\n x = MathClamp(x, width, pageWidth);\n y = MathClamp(y, height, pageHeight);\n break;\n case 270:\n x = MathClamp(x, height, pageWidth);\n y = MathClamp(y, 0, pageHeight - width);\n break;\n }\n }\n this.x = x /= pageWidth;\n this.y = y /= pageHeight;\n const [bx, by] = this.getBaseTranslation();\n x += bx;\n y += by;\n style.left = `${(100 * x).toFixed(2)}%`;\n style.top = `${(100 * y).toFixed(2)}%`;\n this.moveInDOM();\n }\n static #rotatePoint(x, y, angle) {\n switch (angle) {\n case 90:\n return [y, -x];\n case 180:\n return [-x, -y];\n case 270:\n return [-y, x];\n default:\n return [x, y];\n }\n }\n screenToPageTranslation(x, y) {\n return AnnotationEditor.#rotatePoint(x, y, this.parentRotation);\n }\n pageTranslationToScreen(x, y) {\n return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation);\n }\n #getRotationMatrix(rotation) {\n switch (rotation) {\n case 90:\n {\n const [pageWidth, pageHeight] = this.pageDimensions;\n return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];\n }\n case 180:\n return [-1, 0, 0, -1];\n case 270:\n {\n const [pageWidth, pageHeight] = this.pageDimensions;\n return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];\n }\n default:\n return [1, 0, 0, 1];\n }\n }\n get parentScale() {\n return this._uiManager.viewParameters.realScale;\n }\n get parentRotation() {\n return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;\n }\n get parentDimensions() {\n const {\n parentScale,\n pageDimensions: [pageWidth, pageHeight]\n } = this;\n return [pageWidth * parentScale, pageHeight * parentScale];\n }\n setDims() {\n const {\n div: {\n style\n },\n width,\n height\n } = this;\n style.width = `${(100 * width).toFixed(2)}%`;\n style.height = `${(100 * height).toFixed(2)}%`;\n }\n getInitialTranslation() {\n return [0, 0];\n }\n #createResizers() {\n if (this.#resizersDiv) {\n return;\n }\n this.#resizersDiv = document.createElement("div");\n this.#resizersDiv.classList.add("resizers");\n const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"];\n const signal = this._uiManager._signal;\n for (const name of classes) {\n const div = document.createElement("div");\n this.#resizersDiv.append(div);\n div.classList.add("resizer", name);\n div.setAttribute("data-resizer-name", name);\n div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), {\n signal\n });\n div.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n div.tabIndex = -1;\n }\n this.div.prepend(this.#resizersDiv);\n }\n #resizerPointerdown(name, event) {\n event.preventDefault();\n const {\n isMac\n } = FeatureTest.platform;\n if (event.button !== 0 || event.ctrlKey && isMac) {\n return;\n }\n this.#altText?.toggle(false);\n const savedDraggable = this._isDraggable;\n this._isDraggable = false;\n this.#lastPointerCoords = [event.screenX, event.screenY];\n const ac = new AbortController();\n const signal = this._uiManager.combinedSignal(ac);\n this.parent.togglePointerEvents(false);\n window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), {\n passive: true,\n capture: true,\n signal\n });\n window.addEventListener("touchmove", stopEvent, {\n passive: false,\n signal\n });\n window.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n this.#savedDimensions = {\n savedX: this.x,\n savedY: this.y,\n savedWidth: this.width,\n savedHeight: this.height\n };\n const savedParentCursor = this.parent.div.style.cursor;\n const savedCursor = this.div.style.cursor;\n this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor;\n const pointerUpCallback = () => {\n ac.abort();\n this.parent.togglePointerEvents(true);\n this.#altText?.toggle(true);\n this._isDraggable = savedDraggable;\n this.parent.div.style.cursor = savedParentCursor;\n this.div.style.cursor = savedCursor;\n this.#addResizeToUndoStack();\n };\n window.addEventListener("pointerup", pointerUpCallback, {\n signal\n });\n window.addEventListener("blur", pointerUpCallback, {\n signal\n });\n }\n #resize(x, y, width, height) {\n this.width = width;\n this.height = height;\n this.x = x;\n this.y = y;\n this.setDims();\n this.fixAndSetPosition();\n this._onResized();\n }\n _onResized() {}\n #addResizeToUndoStack() {\n if (!this.#savedDimensions) {\n return;\n }\n const {\n savedX,\n savedY,\n savedWidth,\n savedHeight\n } = this.#savedDimensions;\n this.#savedDimensions = null;\n const newX = this.x;\n const newY = this.y;\n const newWidth = this.width;\n const newHeight = this.height;\n if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) {\n return;\n }\n this.addCommands({\n cmd: this.#resize.bind(this, newX, newY, newWidth, newHeight),\n undo: this.#resize.bind(this, savedX, savedY, savedWidth, savedHeight),\n mustExec: true\n });\n }\n static _round(x) {\n return Math.round(x * 10000) / 10000;\n }\n #resizerPointermove(name, event) {\n const [parentWidth, parentHeight] = this.parentDimensions;\n const savedX = this.x;\n const savedY = this.y;\n const savedWidth = this.width;\n const savedHeight = this.height;\n const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;\n const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;\n const rotationMatrix = this.#getRotationMatrix(this.rotation);\n const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];\n const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);\n const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y];\n let getPoint;\n let getOpposite;\n let isDiagonal = false;\n let isHorizontal = false;\n switch (name) {\n case "topLeft":\n isDiagonal = true;\n getPoint = (w, h) => [0, 0];\n getOpposite = (w, h) => [w, h];\n break;\n case "topMiddle":\n getPoint = (w, h) => [w / 2, 0];\n getOpposite = (w, h) => [w / 2, h];\n break;\n case "topRight":\n isDiagonal = true;\n getPoint = (w, h) => [w, 0];\n getOpposite = (w, h) => [0, h];\n break;\n case "middleRight":\n isHorizontal = true;\n getPoint = (w, h) => [w, h / 2];\n getOpposite = (w, h) => [0, h / 2];\n break;\n case "bottomRight":\n isDiagonal = true;\n getPoint = (w, h) => [w, h];\n getOpposite = (w, h) => [0, 0];\n break;\n case "bottomMiddle":\n getPoint = (w, h) => [w / 2, h];\n getOpposite = (w, h) => [w / 2, 0];\n break;\n case "bottomLeft":\n isDiagonal = true;\n getPoint = (w, h) => [0, h];\n getOpposite = (w, h) => [w, 0];\n break;\n case "middleLeft":\n isHorizontal = true;\n getPoint = (w, h) => [0, h / 2];\n getOpposite = (w, h) => [w, h / 2];\n break;\n }\n const point = getPoint(savedWidth, savedHeight);\n const oppositePoint = getOpposite(savedWidth, savedHeight);\n let transfOppositePoint = transf(...oppositePoint);\n const oppositeX = AnnotationEditor._round(savedX + transfOppositePoint[0]);\n const oppositeY = AnnotationEditor._round(savedY + transfOppositePoint[1]);\n let ratioX = 1;\n let ratioY = 1;\n let deltaX, deltaY;\n if (!event.fromKeyboard) {\n const {\n screenX,\n screenY\n } = event;\n const [lastScreenX, lastScreenY] = this.#lastPointerCoords;\n [deltaX, deltaY] = this.screenToPageTranslation(screenX - lastScreenX, screenY - lastScreenY);\n this.#lastPointerCoords[0] = screenX;\n this.#lastPointerCoords[1] = screenY;\n } else {\n ({\n deltaX,\n deltaY\n } = event);\n }\n [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);\n if (isDiagonal) {\n const oldDiag = Math.hypot(savedWidth, savedHeight);\n ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);\n } else if (isHorizontal) {\n ratioX = MathClamp(Math.abs(oppositePoint[0] - point[0] - deltaX), minWidth, 1) / savedWidth;\n } else {\n ratioY = MathClamp(Math.abs(oppositePoint[1] - point[1] - deltaY), minHeight, 1) / savedHeight;\n }\n const newWidth = AnnotationEditor._round(savedWidth * ratioX);\n const newHeight = AnnotationEditor._round(savedHeight * ratioY);\n transfOppositePoint = transf(...getOpposite(newWidth, newHeight));\n const newX = oppositeX - transfOppositePoint[0];\n const newY = oppositeY - transfOppositePoint[1];\n this.#initialRect ||= [this.x, this.y, this.width, this.height];\n this.width = newWidth;\n this.height = newHeight;\n this.x = newX;\n this.y = newY;\n this.setDims();\n this.fixAndSetPosition();\n this._onResizing();\n }\n _onResizing() {}\n altTextFinish() {\n this.#altText?.finish();\n }\n get toolbarButtons() {\n return null;\n }\n async addEditToolbar() {\n if (this._editToolbar || this.#isInEditMode) {\n return this._editToolbar;\n }\n this._editToolbar = new EditorToolbar(this);\n this.div.append(this._editToolbar.render());\n const {\n toolbarButtons\n } = this;\n if (toolbarButtons) {\n for (const [name, tool] of toolbarButtons) {\n await this._editToolbar.addButton(name, tool);\n }\n }\n if (!this.hasComment) {\n this._editToolbar.addButton("comment", this.addCommentButton());\n }\n this._editToolbar.addButton("delete");\n return this._editToolbar;\n }\n addCommentButtonInToolbar() {\n this._editToolbar?.addButtonBefore("comment", this.addCommentButton(), ".deleteButton");\n }\n removeCommentButtonFromToolbar() {\n this._editToolbar?.removeButton("comment");\n }\n removeEditToolbar() {\n this._editToolbar?.remove();\n this._editToolbar = null;\n this.#altText?.destroy();\n }\n addContainer(container) {\n const editToolbarDiv = this._editToolbar?.div;\n if (editToolbarDiv) {\n editToolbarDiv.before(container);\n } else {\n this.div.append(container);\n }\n }\n getClientDimensions() {\n return this.div.getBoundingClientRect();\n }\n createAltText() {\n if (!this.#altText) {\n AltText.initialize(AnnotationEditor._l10n);\n this.#altText = new AltText(this);\n if (this.#accessibilityData) {\n this.#altText.data = this.#accessibilityData;\n this.#accessibilityData = null;\n }\n }\n return this.#altText;\n }\n get altTextData() {\n return this.#altText?.data;\n }\n set altTextData(data) {\n if (!this.#altText) {\n return;\n }\n this.#altText.data = data;\n }\n get guessedAltText() {\n return this.#altText?.guessedText;\n }\n async setGuessedAltText(text) {\n await this.#altText?.setGuessedText(text);\n }\n serializeAltText(isForCopying) {\n return this.#altText?.serialize(isForCopying);\n }\n hasAltText() {\n return !!this.#altText && !this.#altText.isEmpty();\n }\n hasAltTextData() {\n return this.#altText?.hasData() ?? false;\n }\n focusCommentButton() {\n this.#comment?.focusButton();\n }\n addCommentButton() {\n return this.canAddComment ? this.#comment ||= new Comment(this) : null;\n }\n addStandaloneCommentButton() {\n if (!this._uiManager.hasCommentManager()) {\n return;\n }\n if (this.#commentStandaloneButton) {\n if (this._uiManager.isEditingMode()) {\n this.#commentStandaloneButton.classList.remove("hidden");\n }\n return;\n }\n if (!this.hasComment) {\n return;\n }\n this.#commentStandaloneButton = this.#comment.renderForStandalone();\n this.div.append(this.#commentStandaloneButton);\n }\n removeStandaloneCommentButton() {\n this.#comment.removeStandaloneCommentButton();\n this.#commentStandaloneButton = null;\n }\n hideStandaloneCommentButton() {\n this.#commentStandaloneButton?.classList.add("hidden");\n }\n get comment() {\n if (!this.#comment) {\n return null;\n }\n const {\n data: {\n richText,\n text,\n date,\n deleted\n }\n } = this.#comment;\n return {\n text,\n richText,\n date,\n deleted,\n color: this.getNonHCMColor(),\n opacity: this.opacity ?? 1\n };\n }\n set comment(value) {\n this.#comment ||= new Comment(this);\n if (typeof value === "object" && value !== null) {\n this.#comment.restoreData(value);\n } else {\n this.#comment.data = value;\n }\n if (this.hasComment) {\n this.removeCommentButtonFromToolbar();\n this.addStandaloneCommentButton();\n this._uiManager.updateComment(this);\n } else {\n this.addCommentButtonInToolbar();\n this.removeStandaloneCommentButton();\n this._uiManager.removeComment(this);\n }\n }\n setCommentData({\n comment,\n popupRef,\n richText\n }) {\n if (!popupRef) {\n return;\n }\n this.#comment ||= new Comment(this);\n this.#comment.setInitialText(comment, richText);\n if (!this.annotationElementId) {\n return;\n }\n const storedData = this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);\n if (storedData) {\n this.updateFromAnnotationLayer(storedData);\n }\n }\n get hasEditedComment() {\n return this.#comment?.hasBeenEdited();\n }\n get hasDeletedComment() {\n return this.#comment?.isDeleted();\n }\n get hasComment() {\n return !!this.#comment && !this.#comment.isEmpty() && !this.#comment.isDeleted();\n }\n async editComment(options) {\n this.#comment ||= new Comment(this);\n this.#comment.edit(options);\n }\n toggleComment(isSelected, visibility = undefined) {\n if (this.hasComment) {\n this._uiManager.toggleComment(this, isSelected, visibility);\n }\n }\n setSelectedCommentButton(selected) {\n this.#comment.setSelectedButton(selected);\n }\n addComment(serialized) {\n if (this.hasEditedComment) {\n const DEFAULT_POPUP_WIDTH = 180;\n const DEFAULT_POPUP_HEIGHT = 100;\n const [,,, trY] = serialized.rect;\n const [pageWidth] = this.pageDimensions;\n const [pageX] = this.pageTranslation;\n const blX = pageX + pageWidth + 1;\n const blY = trY - DEFAULT_POPUP_HEIGHT;\n const trX = blX + DEFAULT_POPUP_WIDTH;\n serialized.popup = {\n contents: this.comment.text,\n deleted: this.comment.deleted,\n rect: [blX, blY, trX, trY]\n };\n }\n }\n updateFromAnnotationLayer({\n popup: {\n contents,\n deleted\n }\n }) {\n this.#comment.data = deleted ? null : contents;\n }\n get parentBoundingClientRect() {\n return this.parent.boundingClientRect;\n }\n render() {\n const div = this.div = document.createElement("div");\n div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);\n div.className = this.name;\n div.setAttribute("id", this.id);\n div.tabIndex = this.#disabled ? -1 : 0;\n div.setAttribute("role", "application");\n if (this.defaultL10nId) {\n div.setAttribute("data-l10n-id", this.defaultL10nId);\n }\n if (!this._isVisible) {\n div.classList.add("hidden");\n }\n this.setInForeground();\n this.#addFocusListeners();\n const [parentWidth, parentHeight] = this.parentDimensions;\n if (this.parentRotation % 180 !== 0) {\n div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`;\n div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`;\n }\n const [tx, ty] = this.getInitialTranslation();\n this.translate(tx, ty);\n bindEvents(this, div, ["keydown", "pointerdown", "dblclick"]);\n if (this.isResizable && this._uiManager._supportsPinchToZoom) {\n this.#touchManager ||= new TouchManager({\n container: div,\n isPinchingDisabled: () => !this.isSelected,\n onPinchStart: this.#touchPinchStartCallback.bind(this),\n onPinching: this.#touchPinchCallback.bind(this),\n onPinchEnd: this.#touchPinchEndCallback.bind(this),\n signal: this._uiManager._signal\n });\n }\n this.addStandaloneCommentButton();\n this._uiManager._editorUndoBar?.hide();\n return div;\n }\n #touchPinchStartCallback() {\n this.#savedDimensions = {\n savedX: this.x,\n savedY: this.y,\n savedWidth: this.width,\n savedHeight: this.height\n };\n this.#altText?.toggle(false);\n this.parent.togglePointerEvents(false);\n }\n #touchPinchCallback(_origin, prevDistance, distance) {\n const slowDownFactor = 0.7;\n let factor = slowDownFactor * (distance / prevDistance) + 1 - slowDownFactor;\n if (factor === 1) {\n return;\n }\n const rotationMatrix = this.#getRotationMatrix(this.rotation);\n const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y];\n const [parentWidth, parentHeight] = this.parentDimensions;\n const savedX = this.x;\n const savedY = this.y;\n const savedWidth = this.width;\n const savedHeight = this.height;\n const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;\n const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;\n factor = Math.max(Math.min(factor, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);\n const newWidth = AnnotationEditor._round(savedWidth * factor);\n const newHeight = AnnotationEditor._round(savedHeight * factor);\n if (newWidth === savedWidth && newHeight === savedHeight) {\n return;\n }\n this.#initialRect ||= [savedX, savedY, savedWidth, savedHeight];\n const transfCenterPoint = transf(savedWidth / 2, savedHeight / 2);\n const centerX = AnnotationEditor._round(savedX + transfCenterPoint[0]);\n const centerY = AnnotationEditor._round(savedY + transfCenterPoint[1]);\n const newTransfCenterPoint = transf(newWidth / 2, newHeight / 2);\n this.x = centerX - newTransfCenterPoint[0];\n this.y = centerY - newTransfCenterPoint[1];\n this.width = newWidth;\n this.height = newHeight;\n this.setDims();\n this.fixAndSetPosition();\n this._onResizing();\n }\n #touchPinchEndCallback() {\n this.#altText?.toggle(true);\n this.parent.togglePointerEvents(true);\n this.#addResizeToUndoStack();\n }\n pointerdown(event) {\n const {\n isMac\n } = FeatureTest.platform;\n if (event.button !== 0 || event.ctrlKey && isMac) {\n event.preventDefault();\n return;\n }\n this.#hasBeenClicked = true;\n if (this._isDraggable) {\n this.#setUpDragSession(event);\n return;\n }\n this.#selectOnPointerEvent(event);\n }\n #selectOnPointerEvent(event) {\n const {\n isMac\n } = FeatureTest.platform;\n if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {\n this.parent.toggleSelected(this);\n } else {\n this.parent.setSelected(this);\n }\n }\n #setUpDragSession(event) {\n const {\n isSelected\n } = this;\n this._uiManager.setUpDragSession();\n let hasDraggingStarted = false;\n const ac = new AbortController();\n const signal = this._uiManager.combinedSignal(ac);\n const opts = {\n capture: true,\n passive: false,\n signal\n };\n const cancelDrag = e => {\n ac.abort();\n this.#dragPointerId = null;\n this.#hasBeenClicked = false;\n if (!this._uiManager.endDragSession()) {\n this.#selectOnPointerEvent(e);\n }\n if (hasDraggingStarted) {\n this._onStopDragging();\n }\n };\n if (isSelected) {\n this.#prevDragX = event.clientX;\n this.#prevDragY = event.clientY;\n this.#dragPointerId = event.pointerId;\n this.#dragPointerType = event.pointerType;\n window.addEventListener("pointermove", e => {\n if (!hasDraggingStarted) {\n hasDraggingStarted = true;\n this._uiManager.toggleComment(this, true, false);\n this._onStartDragging();\n }\n const {\n clientX: x,\n clientY: y,\n pointerId\n } = e;\n if (pointerId !== this.#dragPointerId) {\n stopEvent(e);\n return;\n }\n const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY);\n this.#prevDragX = x;\n this.#prevDragY = y;\n this._uiManager.dragSelectedEditors(tx, ty);\n }, opts);\n window.addEventListener("touchmove", stopEvent, opts);\n window.addEventListener("pointerdown", e => {\n if (e.pointerType === this.#dragPointerType) {\n if (this.#touchManager || e.isPrimary) {\n cancelDrag(e);\n }\n }\n stopEvent(e);\n }, opts);\n }\n const pointerUpCallback = e => {\n if (!this.#dragPointerId || this.#dragPointerId === e.pointerId) {\n cancelDrag(e);\n return;\n }\n stopEvent(e);\n };\n window.addEventListener("pointerup", pointerUpCallback, {\n signal\n });\n window.addEventListener("blur", pointerUpCallback, {\n signal\n });\n }\n _onStartDragging() {}\n _onStopDragging() {}\n moveInDOM() {\n if (this.#moveInDOMTimeout) {\n clearTimeout(this.#moveInDOMTimeout);\n }\n this.#moveInDOMTimeout = setTimeout(() => {\n this.#moveInDOMTimeout = null;\n this.parent?.moveEditorInDOM(this);\n }, 0);\n }\n _setParentAndPosition(parent, x, y) {\n parent.changeParent(this);\n this.x = x;\n this.y = y;\n this.fixAndSetPosition();\n this._onTranslated();\n }\n getRect(tx, ty, rotation = this.rotation) {\n const scale = this.parentScale;\n const [pageWidth, pageHeight] = this.pageDimensions;\n const [pageX, pageY] = this.pageTranslation;\n const shiftX = tx / scale;\n const shiftY = ty / scale;\n const x = this.x * pageWidth;\n const y = this.y * pageHeight;\n const width = this.width * pageWidth;\n const height = this.height * pageHeight;\n switch (rotation) {\n case 0:\n return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];\n case 90:\n return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];\n case 180:\n return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];\n case 270:\n return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];\n default:\n throw new Error("Invalid rotation");\n }\n }\n getRectInCurrentCoords(rect, pageHeight) {\n const [x1, y1, x2, y2] = rect;\n const width = x2 - x1;\n const height = y2 - y1;\n switch (this.rotation) {\n case 0:\n return [x1, pageHeight - y2, width, height];\n case 90:\n return [x1, pageHeight - y1, height, width];\n case 180:\n return [x2, pageHeight - y1, width, height];\n case 270:\n return [x2, pageHeight - y2, height, width];\n default:\n throw new Error("Invalid rotation");\n }\n }\n getPDFRect() {\n return this.getRect(0, 0);\n }\n getNonHCMColor() {\n return this.color && AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color));\n }\n onUpdatedColor() {\n this.#comment?.onUpdatedColor();\n }\n getData() {\n const {\n comment: {\n text: str,\n color,\n date,\n opacity,\n deleted,\n richText\n },\n uid: id,\n pageIndex,\n creationDate,\n modificationDate\n } = this;\n return {\n id,\n pageIndex,\n rect: this.getPDFRect(),\n richText,\n contentsObj: {\n str\n },\n creationDate,\n modificationDate: date || modificationDate,\n popupRef: !deleted,\n color,\n opacity\n };\n }\n onceAdded(focus) {}\n isEmpty() {\n return false;\n }\n enableEditMode() {\n if (this.isInEditMode()) {\n return false;\n }\n this.parent.setEditingState(false);\n this.#isInEditMode = true;\n return true;\n }\n disableEditMode() {\n if (!this.isInEditMode()) {\n return false;\n }\n this.parent.setEditingState(true);\n this.#isInEditMode = false;\n return true;\n }\n isInEditMode() {\n return this.#isInEditMode;\n }\n shouldGetKeyboardEvents() {\n return this.#isResizerEnabledForKeyboard;\n }\n needsToBeRebuilt() {\n return this.div && !this.isAttachedToDOM;\n }\n get isOnScreen() {\n const {\n top,\n left,\n bottom,\n right\n } = this.getClientDimensions();\n const {\n innerHeight,\n innerWidth\n } = window;\n return left < innerWidth && right > 0 && top < innerHeight && bottom > 0;\n }\n #addFocusListeners() {\n if (this.#focusAC || !this.div) {\n return;\n }\n this.#focusAC = new AbortController();\n const signal = this._uiManager.combinedSignal(this.#focusAC);\n this.div.addEventListener("focusin", this.focusin.bind(this), {\n signal\n });\n this.div.addEventListener("focusout", this.focusout.bind(this), {\n signal\n });\n }\n rebuild() {\n this.#addFocusListeners();\n }\n rotate(_angle) {}\n resize() {}\n serializeDeleted() {\n return {\n id: this.annotationElementId,\n deleted: true,\n pageIndex: this.pageIndex,\n popupRef: this._initialData?.popupRef || ""\n };\n }\n serialize(isForCopying = false, context = null) {\n return {\n annotationType: this.mode,\n pageIndex: this.pageIndex,\n rect: this.getPDFRect(),\n rotation: this.rotation,\n structTreeParentId: this._structTreeParentId,\n popupRef: this._initialData?.popupRef || ""\n };\n }\n static async deserialize(data, parent, uiManager) {\n const editor = new this.prototype.constructor({\n parent,\n id: parent.getNextId(),\n uiManager,\n annotationElementId: data.annotationElementId,\n creationDate: data.creationDate,\n modificationDate: data.modificationDate\n });\n editor.rotation = data.rotation;\n editor.#accessibilityData = data.accessibilityData;\n editor._isCopy = data.isCopy || false;\n const [pageWidth, pageHeight] = editor.pageDimensions;\n const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);\n editor.x = x / pageWidth;\n editor.y = y / pageHeight;\n editor.width = width / pageWidth;\n editor.height = height / pageHeight;\n return editor;\n }\n get hasBeenModified() {\n return !!this.annotationElementId && (this.deleted || this.serialize() !== null);\n }\n remove() {\n this.#focusAC?.abort();\n this.#focusAC = null;\n if (!this.isEmpty()) {\n this.commit();\n }\n if (this.parent) {\n this.parent.remove(this);\n } else {\n this._uiManager.removeEditor(this);\n }\n this.hideCommentPopup();\n if (this.#moveInDOMTimeout) {\n clearTimeout(this.#moveInDOMTimeout);\n this.#moveInDOMTimeout = null;\n }\n this.#stopResizing();\n this.removeEditToolbar();\n if (this.#telemetryTimeouts) {\n for (const timeout of this.#telemetryTimeouts.values()) {\n clearTimeout(timeout);\n }\n this.#telemetryTimeouts = null;\n }\n this.parent = null;\n this.#touchManager?.destroy();\n this.#touchManager = null;\n this.#fakeAnnotation?.remove();\n this.#fakeAnnotation = null;\n }\n get isResizable() {\n return false;\n }\n makeResizable() {\n if (this.isResizable) {\n this.#createResizers();\n this.#resizersDiv.classList.remove("hidden");\n }\n }\n get toolbarPosition() {\n return null;\n }\n get commentButtonPosition() {\n return this._uiManager.direction === "ltr" ? [1, 0] : [0, 0];\n }\n get commentButtonPositionInPage() {\n const {\n commentButtonPosition: [posX, posY]\n } = this;\n const [blX, blY, trX, trY] = this.getPDFRect();\n return [AnnotationEditor._round(blX + (trX - blX) * posX), AnnotationEditor._round(blY + (trY - blY) * (1 - posY))];\n }\n get commentButtonColor() {\n return this._uiManager.makeCommentColor(this.getNonHCMColor(), this.opacity);\n }\n get commentPopupPosition() {\n return this.#comment.commentPopupPositionInLayer;\n }\n set commentPopupPosition(pos) {\n this.#comment.commentPopupPositionInLayer = pos;\n }\n hasDefaultPopupPosition() {\n return this.#comment.hasDefaultPopupPosition();\n }\n get commentButtonWidth() {\n return this.#comment.commentButtonWidth;\n }\n get elementBeforePopup() {\n return this.div;\n }\n setCommentButtonStates(options) {\n this.#comment?.setCommentButtonStates(options);\n }\n keydown(event) {\n if (!this.isResizable || event.target !== this.div || event.key !== "Enter") {\n return;\n }\n this._uiManager.setSelected(this);\n this.#savedDimensions = {\n savedX: this.x,\n savedY: this.y,\n savedWidth: this.width,\n savedHeight: this.height\n };\n const children = this.#resizersDiv.children;\n if (!this.#allResizerDivs) {\n this.#allResizerDivs = Array.from(children);\n const boundResizerKeydown = this.#resizerKeydown.bind(this);\n const boundResizerBlur = this.#resizerBlur.bind(this);\n const signal = this._uiManager._signal;\n for (const div of this.#allResizerDivs) {\n const name = div.getAttribute("data-resizer-name");\n div.setAttribute("role", "spinbutton");\n div.addEventListener("keydown", boundResizerKeydown, {\n signal\n });\n div.addEventListener("blur", boundResizerBlur, {\n signal\n });\n div.addEventListener("focus", this.#resizerFocus.bind(this, name), {\n signal\n });\n div.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);\n }\n }\n const first = this.#allResizerDivs[0];\n let firstPosition = 0;\n for (const div of children) {\n if (div === first) {\n break;\n }\n firstPosition++;\n }\n const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4);\n if (nextFirstPosition !== firstPosition) {\n if (nextFirstPosition < firstPosition) {\n for (let i = 0; i < firstPosition - nextFirstPosition; i++) {\n this.#resizersDiv.append(this.#resizersDiv.firstElementChild);\n }\n } else if (nextFirstPosition > firstPosition) {\n for (let i = 0; i < nextFirstPosition - firstPosition; i++) {\n this.#resizersDiv.firstElementChild.before(this.#resizersDiv.lastElementChild);\n }\n }\n let i = 0;\n for (const child of children) {\n const div = this.#allResizerDivs[i++];\n const name = div.getAttribute("data-resizer-name");\n child.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]);\n }\n }\n this.#setResizerTabIndex(0);\n this.#isResizerEnabledForKeyboard = true;\n this.#resizersDiv.firstElementChild.focus({\n focusVisible: true\n });\n event.preventDefault();\n event.stopImmediatePropagation();\n }\n #resizerKeydown(event) {\n AnnotationEditor._resizerKeyboardManager.exec(this, event);\n }\n #resizerBlur(event) {\n if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) {\n this.#stopResizing();\n }\n }\n #resizerFocus(name) {\n this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : "";\n }\n #setResizerTabIndex(value) {\n if (!this.#allResizerDivs) {\n return;\n }\n for (const div of this.#allResizerDivs) {\n div.tabIndex = value;\n }\n }\n _resizeWithKeyboard(x, y) {\n if (!this.#isResizerEnabledForKeyboard) {\n return;\n }\n this.#resizerPointermove(this.#focusedResizerName, {\n deltaX: x,\n deltaY: y,\n fromKeyboard: true\n });\n }\n #stopResizing() {\n this.#isResizerEnabledForKeyboard = false;\n this.#setResizerTabIndex(-1);\n this.#addResizeToUndoStack();\n }\n _stopResizingWithKeyboard() {\n this.#stopResizing();\n this.div.focus();\n }\n select() {\n if (this.isSelected && this._editToolbar) {\n this._editToolbar.show();\n return;\n }\n this.isSelected = true;\n this.makeResizable();\n this.div?.classList.add("selectedEditor");\n if (!this._editToolbar) {\n this.addEditToolbar().then(() => {\n if (this.div?.classList.contains("selectedEditor")) {\n this._editToolbar?.show();\n }\n });\n return;\n }\n this._editToolbar?.show();\n this.#altText?.toggleAltTextBadge(false);\n }\n focus() {\n if (this.div && !this.div.contains(document.activeElement)) {\n setTimeout(() => this.div?.focus({\n preventScroll: true\n }), 0);\n }\n }\n unselect() {\n if (!this.isSelected) {\n return;\n }\n this.isSelected = false;\n this.#resizersDiv?.classList.add("hidden");\n this.div?.classList.remove("selectedEditor");\n if (this.div?.contains(document.activeElement)) {\n this._uiManager.currentLayer.div.focus({\n preventScroll: true\n });\n }\n this._editToolbar?.hide();\n this.#altText?.toggleAltTextBadge(true);\n this.hideCommentPopup();\n }\n hideCommentPopup() {\n if (this.hasComment) {\n this._uiManager.toggleComment(null);\n }\n }\n updateParams(type, value) {}\n disableEditing() {}\n enableEditing() {}\n get canChangeContent() {\n return false;\n }\n enterInEditMode() {\n if (!this.canChangeContent) {\n return;\n }\n this.enableEditMode();\n this.div.focus();\n }\n dblclick(event) {\n if (event.target.nodeName === "BUTTON") {\n return;\n }\n this.enterInEditMode();\n this.parent.updateToolbar({\n mode: this.constructor._editorType,\n editId: this.uid\n });\n }\n getElementForAltText() {\n return this.div;\n }\n get contentDiv() {\n return this.div;\n }\n get isEditing() {\n return this.#isEditing;\n }\n set isEditing(value) {\n this.#isEditing = value;\n if (!this.parent) {\n return;\n }\n if (value) {\n this.parent.setSelected(this);\n this.parent.setActiveEditor(this);\n } else {\n this.parent.setActiveEditor(null);\n }\n }\n static get MIN_SIZE() {\n return 16;\n }\n static canCreateNewEmptyEditor() {\n return true;\n }\n get telemetryInitialData() {\n return {\n action: "added"\n };\n }\n get telemetryFinalData() {\n return null;\n }\n _reportTelemetry(data, mustWait = false) {\n if (mustWait) {\n this.#telemetryTimeouts ||= new Map();\n const {\n action\n } = data;\n let timeout = this.#telemetryTimeouts.get(action);\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n this._reportTelemetry(data);\n this.#telemetryTimeouts.delete(action);\n if (this.#telemetryTimeouts.size === 0) {\n this.#telemetryTimeouts = null;\n }\n }, AnnotationEditor._telemetryTimeout);\n this.#telemetryTimeouts.set(action, timeout);\n return;\n }\n data.type ||= this.editorType;\n this._uiManager._eventBus.dispatch("reporttelemetry", {\n source: this,\n details: {\n type: "editing",\n data\n }\n });\n }\n show(visible = this._isVisible) {\n this.div.classList.toggle("hidden", !visible);\n this._isVisible = visible;\n }\n enable() {\n if (this.div) {\n this.div.tabIndex = 0;\n }\n this.#disabled = false;\n }\n disable() {\n if (this.div) {\n this.div.tabIndex = -1;\n }\n this.#disabled = true;\n }\n updateFakeAnnotationElement(annotationLayer) {\n if (!this.#fakeAnnotation && !this.deleted) {\n this.#fakeAnnotation = annotationLayer.addFakeAnnotation(this);\n return;\n }\n if (this.deleted) {\n this.#fakeAnnotation.remove();\n this.#fakeAnnotation = null;\n return;\n }\n if (this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized) {\n this.#fakeAnnotation.updateEdited({\n rect: this.getPDFRect(),\n popup: this.comment\n });\n }\n }\n renderAnnotationElement(annotation) {\n if (this.deleted) {\n annotation.hide();\n return null;\n }\n let content = annotation.container.querySelector(".annotationContent");\n if (!content) {\n content = document.createElement("div");\n content.classList.add("annotationContent", this.editorType);\n annotation.container.prepend(content);\n } else if (content.nodeName === "CANVAS") {\n const canvas = content;\n content = document.createElement("div");\n content.classList.add("annotationContent", this.editorType);\n canvas.before(content);\n }\n return content;\n }\n resetAnnotationElement(annotation) {\n const {\n firstElementChild\n } = annotation.container;\n if (firstElementChild?.nodeName === "DIV" && firstElementChild.classList.contains("annotationContent")) {\n firstElementChild.remove();\n }\n }\n}\nclass FakeEditor extends AnnotationEditor {\n constructor(params) {\n super(params);\n this.annotationElementId = params.annotationElementId;\n this.deleted = true;\n }\n serialize() {\n return this.serializeDeleted();\n }\n}\n\n;// ./src/shared/murmurhash3.js\n\n\n\n\n\n\n\n\nconst SEED = 0xc3d2e1f0;\nconst MASK_HIGH = 0xffff0000;\nconst MASK_LOW = 0xffff;\nclass MurmurHash3_64 {\n constructor(seed) {\n this.h1 = seed ? seed & 0xffffffff : SEED;\n this.h2 = seed ? seed & 0xffffffff : SEED;\n }\n update(input) {\n let data, length;\n if (typeof input === "string") {\n data = new Uint8Array(input.length * 2);\n length = 0;\n for (let i = 0, ii = input.length; i < ii; i++) {\n const code = input.charCodeAt(i);\n if (code <= 0xff) {\n data[length++] = code;\n } else {\n data[length++] = code >>> 8;\n data[length++] = code & 0xff;\n }\n }\n } else if (ArrayBuffer.isView(input)) {\n data = input.slice();\n length = data.byteLength;\n } else {\n throw new Error("Invalid data format, must be a string or TypedArray.");\n }\n const blockCounts = length >> 2;\n const tailLength = length - blockCounts * 4;\n const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);\n let k1 = 0,\n k2 = 0;\n let h1 = this.h1,\n h2 = this.h2;\n const C1 = 0xcc9e2d51,\n C2 = 0x1b873593;\n const C1_LOW = C1 & MASK_LOW,\n C2_LOW = C2 & MASK_LOW;\n for (let i = 0; i < blockCounts; i++) {\n if (i & 1) {\n k1 = dataUint32[i];\n k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;\n k1 = k1 << 15 | k1 >>> 17;\n k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;\n h1 ^= k1;\n h1 = h1 << 13 | h1 >>> 19;\n h1 = h1 * 5 + 0xe6546b64;\n } else {\n k2 = dataUint32[i];\n k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;\n k2 = k2 << 15 | k2 >>> 17;\n k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;\n h2 ^= k2;\n h2 = h2 << 13 | h2 >>> 19;\n h2 = h2 * 5 + 0xe6546b64;\n }\n }\n k1 = 0;\n switch (tailLength) {\n case 3:\n k1 ^= data[blockCounts * 4 + 2] << 16;\n case 2:\n k1 ^= data[blockCounts * 4 + 1] << 8;\n case 1:\n k1 ^= data[blockCounts * 4];\n k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;\n k1 = k1 << 15 | k1 >>> 17;\n k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;\n if (blockCounts & 1) {\n h1 ^= k1;\n } else {\n h2 ^= k1;\n }\n }\n this.h1 = h1;\n this.h2 = h2;\n }\n hexdigest() {\n let h1 = this.h1,\n h2 = this.h2;\n h1 ^= h2 >>> 1;\n h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;\n h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;\n h1 ^= h2 >>> 1;\n h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;\n h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;\n h1 ^= h2 >>> 1;\n return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");\n }\n}\n\n;// ./src/display/annotation_storage.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst SerializableEmpty = Object.freeze({\n map: null,\n hash: "",\n transfer: undefined\n});\nclass AnnotationStorage {\n #modified = false;\n #modifiedIds = null;\n #editorsMap = null;\n #storage = new Map();\n onSetModified = null;\n onResetModified = null;\n onAnnotationEditor = null;\n getValue(key, defaultValue) {\n const value = this.#storage.get(key);\n if (value === undefined) {\n return defaultValue;\n }\n return Object.assign(defaultValue, value);\n }\n getRawValue(key) {\n return this.#storage.get(key);\n }\n remove(key) {\n const storedValue = this.#storage.get(key);\n if (storedValue === undefined) {\n return;\n }\n if (storedValue instanceof AnnotationEditor) {\n this.#editorsMap.delete(storedValue.annotationElementId);\n }\n this.#storage.delete(key);\n if (this.#storage.size === 0) {\n this.resetModified();\n }\n if (typeof this.onAnnotationEditor === "function") {\n for (const value of this.#storage.values()) {\n if (value instanceof AnnotationEditor) {\n return;\n }\n }\n this.onAnnotationEditor(null);\n }\n }\n setValue(key, value) {\n const obj = this.#storage.get(key);\n let modified = false;\n if (obj !== undefined) {\n for (const [entry, val] of Object.entries(value)) {\n if (obj[entry] !== val) {\n modified = true;\n obj[entry] = val;\n }\n }\n } else {\n modified = true;\n this.#storage.set(key, value);\n }\n if (modified) {\n this.#setModified();\n }\n if (value instanceof AnnotationEditor) {\n (this.#editorsMap ||= new Map()).set(value.annotationElementId, value);\n if (typeof this.onAnnotationEditor === "function") {\n this.onAnnotationEditor(value.constructor._type);\n }\n }\n }\n has(key) {\n return this.#storage.has(key);\n }\n get size() {\n return this.#storage.size;\n }\n #setModified() {\n if (!this.#modified) {\n this.#modified = true;\n if (typeof this.onSetModified === "function") {\n this.onSetModified();\n }\n }\n }\n resetModified() {\n if (this.#modified) {\n this.#modified = false;\n if (typeof this.onResetModified === "function") {\n this.onResetModified();\n }\n }\n }\n get print() {\n return new PrintAnnotationStorage(this);\n }\n get serializable() {\n if (this.#storage.size === 0) {\n return SerializableEmpty;\n }\n const map = new Map(),\n hash = new MurmurHash3_64(),\n transfer = [];\n const context = Object.create(null);\n let hasBitmap = false;\n for (const [key, val] of this.#storage) {\n const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val;\n if (val.page) {\n val.pageIndex = val.page._pageIndex;\n delete val.page;\n }\n if (serialized) {\n map.set(key, serialized);\n hash.update(`${key}:${JSON.stringify(serialized)}`);\n hasBitmap ||= !!serialized.bitmap;\n }\n }\n if (hasBitmap) {\n for (const value of map.values()) {\n if (value.bitmap) {\n transfer.push(value.bitmap);\n }\n }\n }\n return map.size > 0 ? {\n map,\n hash: hash.hexdigest(),\n transfer\n } : SerializableEmpty;\n }\n get editorStats() {\n let stats = null;\n const typeToEditor = new Map();\n let numberOfEditedComments = 0;\n let numberOfDeletedComments = 0;\n for (const value of this.#storage.values()) {\n if (!(value instanceof AnnotationEditor)) {\n if (value.popup) {\n if (value.popup.deleted) {\n numberOfDeletedComments += 1;\n } else {\n numberOfEditedComments += 1;\n }\n }\n continue;\n }\n if (value.isCommentDeleted) {\n numberOfDeletedComments += 1;\n } else if (value.hasEditedComment) {\n numberOfEditedComments += 1;\n }\n const editorStats = value.telemetryFinalData;\n if (!editorStats) {\n continue;\n }\n const {\n type\n } = editorStats;\n if (!typeToEditor.has(type)) {\n typeToEditor.set(type, Object.getPrototypeOf(value).constructor);\n }\n stats ||= Object.create(null);\n const map = stats[type] ||= new Map();\n for (const [key, val] of Object.entries(editorStats)) {\n if (key === "type") {\n continue;\n }\n const counters = map.getOrInsertComputed(key, makeMap);\n counters.set(val, (counters.get(val) ?? 0) + 1);\n }\n }\n if (numberOfDeletedComments > 0 || numberOfEditedComments > 0) {\n stats ||= Object.create(null);\n stats.comments = {\n deleted: numberOfDeletedComments,\n edited: numberOfEditedComments\n };\n }\n if (!stats) {\n return null;\n }\n for (const [type, editor] of typeToEditor) {\n stats[type] = editor.computeTelemetryFinalData(stats[type]);\n }\n return stats;\n }\n resetModifiedIds() {\n this.#modifiedIds = null;\n }\n updateEditor(annotationId, data) {\n const value = this.#editorsMap?.get(annotationId);\n if (value) {\n value.updateFromAnnotationLayer(data);\n return true;\n }\n return false;\n }\n getEditor(annotationId) {\n return this.#editorsMap?.get(annotationId) || null;\n }\n get modifiedIds() {\n if (this.#modifiedIds) {\n return this.#modifiedIds;\n }\n const ids = [];\n if (this.#editorsMap) {\n for (const value of this.#editorsMap.values()) {\n if (!value.serialize()) {\n continue;\n }\n ids.push(value.annotationElementId);\n }\n }\n return this.#modifiedIds = {\n ids: new Set(ids),\n hash: ids.join(",")\n };\n }\n [Symbol.iterator]() {\n return this.#storage.entries();\n }\n}\nclass PrintAnnotationStorage extends AnnotationStorage {\n #serializable = SerializableEmpty;\n constructor(parent) {\n super();\n const {\n serializable\n } = parent;\n if (serializable === SerializableEmpty) {\n return;\n }\n const {\n map,\n hash,\n transfer\n } = serializable;\n const clone = structuredClone(map, transfer ? {\n transfer\n } : null);\n this.#serializable = {\n map: clone,\n hash,\n transfer: []\n };\n }\n get print() {\n unreachable("Should not call PrintAnnotationStorage.print");\n }\n get serializable() {\n return this.#serializable;\n }\n get modifiedIds() {\n return shadow(this, "modifiedIds", {\n ids: new Set(),\n hash: ""\n });\n }\n}\n\n;// ./src/display/font_loader.js\n\n\n\n\n\n\n\n\n\n\n\nclass FontLoader {\n #systemFonts = new Set();\n constructor({\n ownerDocument = globalThis.document,\n styleElement = null\n }) {\n this._document = ownerDocument;\n this.nativeFontFaces = new Set();\n this.styleElement = null;\n this.loadingRequests = [];\n this.loadTestFontId = 0;\n }\n addNativeFontFace(nativeFontFace) {\n this.nativeFontFaces.add(nativeFontFace);\n this._document.fonts.add(nativeFontFace);\n }\n removeNativeFontFace(nativeFontFace) {\n this.nativeFontFaces.delete(nativeFontFace);\n this._document.fonts.delete(nativeFontFace);\n }\n insertRule(rule) {\n if (!this.styleElement) {\n this.styleElement = this._document.createElement("style");\n this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);\n }\n const styleSheet = this.styleElement.sheet;\n styleSheet.insertRule(rule, styleSheet.cssRules.length);\n }\n clear() {\n for (const nativeFontFace of this.nativeFontFaces) {\n this._document.fonts.delete(nativeFontFace);\n }\n this.nativeFontFaces.clear();\n this.#systemFonts.clear();\n if (this.styleElement) {\n this.styleElement.remove();\n this.styleElement = null;\n }\n }\n async loadSystemFont({\n systemFontInfo: info,\n disableFontFace,\n _inspectFont\n }) {\n if (!info || this.#systemFonts.has(info.loadedName)) {\n return;\n }\n assert(!disableFontFace, "loadSystemFont shouldn\'t be called when `disableFontFace` is set.");\n if (this.isFontLoadingAPISupported) {\n const {\n loadedName,\n src,\n style\n } = info;\n const fontFace = new FontFace(loadedName, src, style);\n this.addNativeFontFace(fontFace);\n try {\n await fontFace.load();\n this.#systemFonts.add(loadedName);\n _inspectFont?.(info);\n } catch {\n warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`);\n this.removeNativeFontFace(fontFace);\n }\n return;\n }\n unreachable("Not implemented: loadSystemFont without the Font Loading API.");\n }\n async bind(font) {\n if (font.attached || font.missingFile && !font.systemFontInfo) {\n return;\n }\n font.attached = true;\n if (font.systemFontInfo) {\n await this.loadSystemFont(font);\n return;\n }\n if (this.isFontLoadingAPISupported) {\n const nativeFontFace = font.createNativeFontFace();\n if (nativeFontFace) {\n this.addNativeFontFace(nativeFontFace);\n try {\n await nativeFontFace.loaded;\n } catch (ex) {\n warn(`Failed to load font \'${nativeFontFace.family}\': \'${ex}\'.`);\n font.disableFontFace = true;\n throw ex;\n }\n }\n return;\n }\n const rule = font.createFontFaceRule();\n if (rule) {\n this.insertRule(rule);\n if (this.isSyncFontLoadingSupported) {\n return;\n }\n await new Promise(resolve => {\n const request = this._queueLoadingCallback(resolve);\n this._prepareFontLoadEvent(font, request);\n });\n }\n }\n get isFontLoadingAPISupported() {\n const hasFonts = !!this._document?.fonts;\n return shadow(this, "isFontLoadingAPISupported", hasFonts);\n }\n get isSyncFontLoadingSupported() {\n return shadow(this, "isSyncFontLoadingSupported", isNodeJS || FeatureTest.platform.isFirefox);\n }\n _queueLoadingCallback(callback) {\n function completeRequest() {\n assert(!request.done, "completeRequest() cannot be called twice.");\n request.done = true;\n while (loadingRequests.length > 0 && loadingRequests[0].done) {\n const otherRequest = loadingRequests.shift();\n setTimeout(otherRequest.callback, 0);\n }\n }\n const {\n loadingRequests\n } = this;\n const request = {\n done: false,\n complete: completeRequest,\n callback\n };\n loadingRequests.push(request);\n return request;\n }\n get _loadTestFont() {\n const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");\n return shadow(this, "_loadTestFont", testFont);\n }\n _prepareFontLoadEvent(font, request) {\n function int32(data, offset) {\n return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;\n }\n function spliceString(s, offset, remove, insert) {\n const chunk1 = s.substring(0, offset);\n const chunk2 = s.substring(offset + remove);\n return chunk1 + insert + chunk2;\n }\n let i, ii;\n const canvas = this._document.createElement("canvas");\n canvas.width = 1;\n canvas.height = 1;\n const ctx = canvas.getContext("2d");\n let called = 0;\n function isFontReady(name, callback) {\n if (++called > 30) {\n warn("Load test font never loaded.");\n callback();\n return;\n }\n ctx.font = "30px " + name;\n ctx.fillText(".", 0, 20);\n const imageData = ctx.getImageData(0, 0, 1, 1);\n if (imageData.data[3] > 0) {\n callback();\n return;\n }\n setTimeout(isFontReady.bind(null, name, callback));\n }\n const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;\n let data = this._loadTestFont;\n const COMMENT_OFFSET = 976;\n data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);\n const CFF_CHECKSUM_OFFSET = 16;\n const XXXX_VALUE = 0x58585858;\n let checksum = int32(data, CFF_CHECKSUM_OFFSET);\n for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {\n checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;\n }\n if (i < loadTestFontId.length) {\n checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;\n }\n data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));\n const url = `url(data:font/opentype;base64,${btoa(data)});`;\n const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;\n this.insertRule(rule);\n const div = this._document.createElement("div");\n div.style.visibility = "hidden";\n div.style.width = div.style.height = "10px";\n div.style.position = "absolute";\n div.style.top = div.style.left = "0px";\n for (const name of [font.loadedName, loadTestFontId]) {\n const span = this._document.createElement("span");\n span.textContent = "Hi";\n span.style.fontFamily = name;\n div.append(span);\n }\n this._document.body.append(div);\n isFontReady(loadTestFontId, () => {\n div.remove();\n request.complete();\n });\n }\n}\nclass FontFaceObject {\n #fontData;\n constructor(translatedData, inspectFont = null, extra, charProcOperatorList) {\n this.compiledGlyphs = Object.create(null);\n this.#fontData = translatedData;\n this._inspectFont = inspectFont;\n if (extra) {\n Object.assign(this, extra);\n }\n if (charProcOperatorList) {\n this.charProcOperatorList = charProcOperatorList;\n }\n }\n createNativeFontFace() {\n if (!this.data || this.disableFontFace) {\n return null;\n }\n let nativeFontFace;\n if (!this.cssFontInfo) {\n nativeFontFace = new FontFace(this.loadedName, this.data, {});\n } else {\n const css = {\n weight: this.cssFontInfo.fontWeight\n };\n if (this.cssFontInfo.italicAngle) {\n css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;\n }\n nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);\n }\n this._inspectFont?.(this);\n return nativeFontFace;\n }\n createFontFaceRule() {\n if (!this.data || this.disableFontFace) {\n return null;\n }\n const url = `url(data:${this.mimetype};base64,${this.data.toBase64()});`;\n let rule;\n if (!this.cssFontInfo) {\n rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;\n } else {\n let css = `font-weight: ${this.cssFontInfo.fontWeight};`;\n if (this.cssFontInfo.italicAngle) {\n css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;\n }\n rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;\n }\n this._inspectFont?.(this, url);\n return rule;\n }\n getPathGenerator(objs, character) {\n if (this.compiledGlyphs[character] !== undefined) {\n return this.compiledGlyphs[character];\n }\n const objId = this.loadedName + "_path_" + character;\n let cmds;\n try {\n cmds = objs.get(objId);\n } catch (ex) {\n warn(`getPathGenerator - ignoring character: "${ex}".`);\n }\n const path = makePathFromDrawOPS(cmds?.path);\n if (!this.fontExtraProperties) {\n objs.delete(objId);\n }\n return this.compiledGlyphs[character] = path;\n }\n get black() {\n return this.#fontData.black;\n }\n get bold() {\n return this.#fontData.bold;\n }\n get disableFontFace() {\n return this.#fontData.disableFontFace ?? false;\n }\n set disableFontFace(value) {\n shadow(this, "disableFontFace", !!value);\n }\n get fontExtraProperties() {\n return this.#fontData.fontExtraProperties ?? false;\n }\n get isInvalidPDFjsFont() {\n return this.#fontData.isInvalidPDFjsFont;\n }\n get isType3Font() {\n return this.#fontData.isType3Font;\n }\n get italic() {\n return this.#fontData.italic;\n }\n get missingFile() {\n return this.#fontData.missingFile;\n }\n get remeasure() {\n return this.#fontData.remeasure;\n }\n get vertical() {\n return this.#fontData.vertical;\n }\n get ascent() {\n return this.#fontData.ascent;\n }\n get defaultWidth() {\n return this.#fontData.defaultWidth;\n }\n get descent() {\n return this.#fontData.descent;\n }\n get bbox() {\n return this.#fontData.bbox;\n }\n set bbox(bbox) {\n shadow(this, "bbox", bbox);\n }\n get fontMatrix() {\n return this.#fontData.fontMatrix;\n }\n get fallbackName() {\n return this.#fontData.fallbackName;\n }\n get loadedName() {\n return this.#fontData.loadedName;\n }\n get mimetype() {\n return this.#fontData.mimetype;\n }\n get name() {\n return this.#fontData.name;\n }\n get data() {\n return this.#fontData.data;\n }\n clearData() {\n this.#fontData.clearData();\n }\n get cssFontInfo() {\n return this.#fontData.cssFontInfo;\n }\n get systemFontInfo() {\n return this.#fontData.systemFontInfo;\n }\n get defaultVMetrics() {\n return this.#fontData.defaultVMetrics;\n }\n}\n\n;// ./src/shared/obj-bin-transform.js\n\n\n\n\n\n\n\n\n\n\nclass CssFontInfo {\n #buffer;\n #view;\n #decoder;\n static strings = ["fontFamily", "fontWeight", "italicAngle"];\n static write(info) {\n const encoder = new TextEncoder();\n const encodedStrings = {};\n let stringsLength = 0;\n for (const prop of CssFontInfo.strings) {\n const encoded = encoder.encode(info[prop]);\n encodedStrings[prop] = encoded;\n stringsLength += 4 + encoded.length;\n }\n const buffer = new ArrayBuffer(stringsLength);\n const data = new Uint8Array(buffer);\n const view = new DataView(buffer);\n let offset = 0;\n for (const prop of CssFontInfo.strings) {\n const encoded = encodedStrings[prop];\n const length = encoded.length;\n view.setUint32(offset, length);\n data.set(encoded, offset + 4);\n offset += 4 + length;\n }\n assert(offset === buffer.byteLength, "CssFontInfo.write: Buffer overflow");\n return buffer;\n }\n constructor(buffer) {\n this.#buffer = buffer;\n this.#view = new DataView(this.#buffer);\n this.#decoder = new TextDecoder();\n }\n #readString(index) {\n assert(index < CssFontInfo.strings.length, "Invalid string index");\n let offset = 0;\n for (let i = 0; i < index; i++) {\n offset += this.#view.getUint32(offset) + 4;\n }\n const length = this.#view.getUint32(offset);\n return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length));\n }\n get fontFamily() {\n return this.#readString(0);\n }\n get fontWeight() {\n return this.#readString(1);\n }\n get italicAngle() {\n return this.#readString(2);\n }\n}\nclass SystemFontInfo {\n #buffer;\n #view;\n #decoder;\n static strings = ["css", "loadedName", "baseFontName", "src"];\n static write(info) {\n const encoder = new TextEncoder();\n const encodedStrings = {};\n let stringsLength = 0;\n for (const prop of SystemFontInfo.strings) {\n const encoded = encoder.encode(info[prop]);\n encodedStrings[prop] = encoded;\n stringsLength += 4 + encoded.length;\n }\n stringsLength += 4;\n let encodedStyleStyle,\n encodedStyleWeight,\n lengthEstimate = 1 + stringsLength;\n if (info.style) {\n encodedStyleStyle = encoder.encode(info.style.style);\n encodedStyleWeight = encoder.encode(info.style.weight);\n lengthEstimate += 4 + encodedStyleStyle.length + 4 + encodedStyleWeight.length;\n }\n const buffer = new ArrayBuffer(lengthEstimate);\n const data = new Uint8Array(buffer);\n const view = new DataView(buffer);\n let offset = 0;\n view.setUint8(offset++, info.guessFallback ? 1 : 0);\n view.setUint32(offset, 0);\n offset += 4;\n stringsLength = 0;\n for (const prop of SystemFontInfo.strings) {\n const encoded = encodedStrings[prop];\n const length = encoded.length;\n stringsLength += 4 + length;\n view.setUint32(offset, length);\n data.set(encoded, offset + 4);\n offset += 4 + length;\n }\n view.setUint32(offset - stringsLength - 4, stringsLength);\n if (info.style) {\n view.setUint32(offset, encodedStyleStyle.length);\n data.set(encodedStyleStyle, offset + 4);\n offset += 4 + encodedStyleStyle.length;\n view.setUint32(offset, encodedStyleWeight.length);\n data.set(encodedStyleWeight, offset + 4);\n offset += 4 + encodedStyleWeight.length;\n }\n assert(offset <= buffer.byteLength, "SubstitionInfo.write: Buffer overflow");\n return buffer.transferToFixedLength(offset);\n }\n constructor(buffer) {\n this.#buffer = buffer;\n this.#view = new DataView(this.#buffer);\n this.#decoder = new TextDecoder();\n }\n get guessFallback() {\n return this.#view.getUint8(0) !== 0;\n }\n #readString(index) {\n assert(index < SystemFontInfo.strings.length, "Invalid string index");\n let offset = 5;\n for (let i = 0; i < index; i++) {\n offset += this.#view.getUint32(offset) + 4;\n }\n const length = this.#view.getUint32(offset);\n return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length));\n }\n get css() {\n return this.#readString(0);\n }\n get loadedName() {\n return this.#readString(1);\n }\n get baseFontName() {\n return this.#readString(2);\n }\n get src() {\n return this.#readString(3);\n }\n get style() {\n let offset = 1;\n offset += 4 + this.#view.getUint32(offset);\n const styleLength = this.#view.getUint32(offset);\n const style = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, styleLength));\n offset += 4 + styleLength;\n const weightLength = this.#view.getUint32(offset);\n const weight = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, weightLength));\n return {\n style,\n weight\n };\n }\n}\nclass FontInfo {\n static bools = ["black", "bold", "disableFontFace", "fontExtraProperties", "isInvalidPDFjsFont", "isType3Font", "italic", "missingFile", "remeasure", "vertical"];\n static numbers = ["ascent", "defaultWidth", "descent"];\n static strings = ["fallbackName", "loadedName", "mimetype", "name"];\n static #OFFSET_NUMBERS = Math.ceil(this.bools.length * 2 / 8);\n static #OFFSET_BBOX = this.#OFFSET_NUMBERS + this.numbers.length * 8;\n static #OFFSET_FONT_MATRIX = this.#OFFSET_BBOX + 1 + 2 * 4;\n static #OFFSET_DEFAULT_VMETRICS = this.#OFFSET_FONT_MATRIX + 1 + 8 * 6;\n static #OFFSET_STRINGS = this.#OFFSET_DEFAULT_VMETRICS + 1 + 2 * 3;\n #buffer;\n #decoder;\n #view;\n constructor({\n data,\n extra\n }) {\n this.#buffer = data;\n this.#decoder = new TextDecoder();\n this.#view = new DataView(this.#buffer);\n if (extra) {\n Object.assign(this, extra);\n }\n }\n #readBoolean(index) {\n assert(index < FontInfo.bools.length, "Invalid boolean index");\n const byteOffset = Math.floor(index / 4);\n const bitOffset = index * 2 % 8;\n const value = this.#view.getUint8(byteOffset) >> bitOffset & 0x03;\n return value === 0x00 ? undefined : value === 0x02;\n }\n get black() {\n return this.#readBoolean(0);\n }\n get bold() {\n return this.#readBoolean(1);\n }\n get disableFontFace() {\n return this.#readBoolean(2);\n }\n get fontExtraProperties() {\n return this.#readBoolean(3);\n }\n get isInvalidPDFjsFont() {\n return this.#readBoolean(4);\n }\n get isType3Font() {\n return this.#readBoolean(5);\n }\n get italic() {\n return this.#readBoolean(6);\n }\n get missingFile() {\n return this.#readBoolean(7);\n }\n get remeasure() {\n return this.#readBoolean(8);\n }\n get vertical() {\n return this.#readBoolean(9);\n }\n #readNumber(index) {\n assert(index < FontInfo.numbers.length, "Invalid number index");\n return this.#view.getFloat64(FontInfo.#OFFSET_NUMBERS + index * 8);\n }\n get ascent() {\n return this.#readNumber(0);\n }\n get defaultWidth() {\n return this.#readNumber(1);\n }\n get descent() {\n return this.#readNumber(2);\n }\n get bbox() {\n let offset = FontInfo.#OFFSET_BBOX;\n const numCoords = this.#view.getUint8(offset);\n if (numCoords === 0) {\n return undefined;\n }\n offset += 1;\n const bbox = [];\n for (let i = 0; i < 4; i++) {\n bbox.push(this.#view.getInt16(offset, true));\n offset += 2;\n }\n return bbox;\n }\n get fontMatrix() {\n let offset = FontInfo.#OFFSET_FONT_MATRIX;\n const numPoints = this.#view.getUint8(offset);\n if (numPoints === 0) {\n return undefined;\n }\n offset += 1;\n const fontMatrix = [];\n for (let i = 0; i < 6; i++) {\n fontMatrix.push(this.#view.getFloat64(offset, true));\n offset += 8;\n }\n return fontMatrix;\n }\n get defaultVMetrics() {\n let offset = FontInfo.#OFFSET_DEFAULT_VMETRICS;\n const numMetrics = this.#view.getUint8(offset);\n if (numMetrics === 0) {\n return undefined;\n }\n offset += 1;\n const defaultVMetrics = [];\n for (let i = 0; i < 3; i++) {\n defaultVMetrics.push(this.#view.getInt16(offset, true));\n offset += 2;\n }\n return defaultVMetrics;\n }\n #readString(index) {\n assert(index < FontInfo.strings.length, "Invalid string index");\n let offset = FontInfo.#OFFSET_STRINGS + 4;\n for (let i = 0; i < index; i++) {\n offset += this.#view.getUint32(offset) + 4;\n }\n const length = this.#view.getUint32(offset);\n const stringData = new Uint8Array(length);\n stringData.set(new Uint8Array(this.#buffer, offset + 4, length));\n return this.#decoder.decode(stringData);\n }\n get fallbackName() {\n return this.#readString(0);\n }\n get loadedName() {\n return this.#readString(1);\n }\n get mimetype() {\n return this.#readString(2);\n }\n get name() {\n return this.#readString(3);\n }\n get data() {\n let offset = FontInfo.#OFFSET_STRINGS;\n const stringsLength = this.#view.getUint32(offset);\n offset += 4 + stringsLength;\n const systemFontInfoLength = this.#view.getUint32(offset);\n offset += 4 + systemFontInfoLength;\n const cssFontInfoLength = this.#view.getUint32(offset);\n offset += 4 + cssFontInfoLength;\n const length = this.#view.getUint32(offset);\n if (length === 0) {\n return undefined;\n }\n return new Uint8Array(this.#buffer, offset + 4, length);\n }\n clearData() {\n let offset = FontInfo.#OFFSET_STRINGS;\n const stringsLength = this.#view.getUint32(offset);\n offset += 4 + stringsLength;\n const systemFontInfoLength = this.#view.getUint32(offset);\n offset += 4 + systemFontInfoLength;\n const cssFontInfoLength = this.#view.getUint32(offset);\n offset += 4 + cssFontInfoLength;\n const length = this.#view.getUint32(offset);\n const data = new Uint8Array(this.#buffer, offset + 4, length);\n data.fill(0);\n this.#view.setUint32(offset, 0);\n }\n get cssFontInfo() {\n let offset = FontInfo.#OFFSET_STRINGS;\n const stringsLength = this.#view.getUint32(offset);\n offset += 4 + stringsLength;\n const systemFontInfoLength = this.#view.getUint32(offset);\n offset += 4 + systemFontInfoLength;\n const cssFontInfoLength = this.#view.getUint32(offset);\n if (cssFontInfoLength === 0) {\n return null;\n }\n const cssFontInfoData = new Uint8Array(cssFontInfoLength);\n cssFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, cssFontInfoLength));\n return new CssFontInfo(cssFontInfoData.buffer);\n }\n get systemFontInfo() {\n let offset = FontInfo.#OFFSET_STRINGS;\n const stringsLength = this.#view.getUint32(offset);\n offset += 4 + stringsLength;\n const systemFontInfoLength = this.#view.getUint32(offset);\n if (systemFontInfoLength === 0) {\n return null;\n }\n const systemFontInfoData = new Uint8Array(systemFontInfoLength);\n systemFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, systemFontInfoLength));\n return new SystemFontInfo(systemFontInfoData.buffer);\n }\n static write(font) {\n const systemFontInfoBuffer = font.systemFontInfo ? SystemFontInfo.write(font.systemFontInfo) : null;\n const cssFontInfoBuffer = font.cssFontInfo ? CssFontInfo.write(font.cssFontInfo) : null;\n const encoder = new TextEncoder();\n const encodedStrings = {};\n let stringsLength = 0;\n for (const prop of FontInfo.strings) {\n encodedStrings[prop] = encoder.encode(font[prop]);\n stringsLength += 4 + encodedStrings[prop].length;\n }\n const lengthEstimate = FontInfo.#OFFSET_STRINGS + 4 + stringsLength + 4 + (systemFontInfoBuffer ? systemFontInfoBuffer.byteLength : 0) + 4 + (cssFontInfoBuffer ? cssFontInfoBuffer.byteLength : 0) + 4 + (font.data ? font.data.length : 0);\n const buffer = new ArrayBuffer(lengthEstimate);\n const data = new Uint8Array(buffer);\n const view = new DataView(buffer);\n let offset = 0;\n const numBools = FontInfo.bools.length;\n let boolByte = 0,\n boolBit = 0;\n for (let i = 0; i < numBools; i++) {\n const value = font[FontInfo.bools[i]];\n const bits = value === undefined ? 0x00 : value ? 0x02 : 0x01;\n boolByte |= bits << boolBit;\n boolBit += 2;\n if (boolBit === 8 || i === numBools - 1) {\n view.setUint8(offset++, boolByte);\n boolByte = 0;\n boolBit = 0;\n }\n }\n assert(offset === FontInfo.#OFFSET_NUMBERS, "FontInfo.write: Boolean properties offset mismatch");\n for (const prop of FontInfo.numbers) {\n view.setFloat64(offset, font[prop]);\n offset += 8;\n }\n assert(offset === FontInfo.#OFFSET_BBOX, "FontInfo.write: Number properties offset mismatch");\n if (font.bbox) {\n view.setUint8(offset++, 4);\n for (const coord of font.bbox) {\n view.setInt16(offset, coord, true);\n offset += 2;\n }\n } else {\n view.setUint8(offset++, 0);\n offset += 2 * 4;\n }\n assert(offset === FontInfo.#OFFSET_FONT_MATRIX, "FontInfo.write: BBox properties offset mismatch");\n if (font.fontMatrix) {\n view.setUint8(offset++, 6);\n for (const point of font.fontMatrix) {\n view.setFloat64(offset, point, true);\n offset += 8;\n }\n } else {\n view.setUint8(offset++, 0);\n offset += 8 * 6;\n }\n assert(offset === FontInfo.#OFFSET_DEFAULT_VMETRICS, "FontInfo.write: FontMatrix properties offset mismatch");\n if (font.defaultVMetrics) {\n view.setUint8(offset++, 1);\n for (const metric of font.defaultVMetrics) {\n view.setInt16(offset, metric, true);\n offset += 2;\n }\n } else {\n view.setUint8(offset++, 0);\n offset += 3 * 2;\n }\n assert(offset === FontInfo.#OFFSET_STRINGS, "FontInfo.write: DefaultVMetrics properties offset mismatch");\n view.setUint32(FontInfo.#OFFSET_STRINGS, 0);\n offset += 4;\n for (const prop of FontInfo.strings) {\n const encoded = encodedStrings[prop];\n const length = encoded.length;\n view.setUint32(offset, length);\n data.set(encoded, offset + 4);\n offset += 4 + length;\n }\n view.setUint32(FontInfo.#OFFSET_STRINGS, offset - FontInfo.#OFFSET_STRINGS - 4);\n if (!systemFontInfoBuffer) {\n view.setUint32(offset, 0);\n offset += 4;\n } else {\n const length = systemFontInfoBuffer.byteLength;\n view.setUint32(offset, length);\n assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at systemFontInfo");\n data.set(new Uint8Array(systemFontInfoBuffer), offset + 4);\n offset += 4 + length;\n }\n if (!cssFontInfoBuffer) {\n view.setUint32(offset, 0);\n offset += 4;\n } else {\n const length = cssFontInfoBuffer.byteLength;\n view.setUint32(offset, length);\n assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at cssFontInfo");\n data.set(new Uint8Array(cssFontInfoBuffer), offset + 4);\n offset += 4 + length;\n }\n if (font.data === undefined) {\n view.setUint32(offset, 0);\n offset += 4;\n } else {\n view.setUint32(offset, font.data.length);\n data.set(font.data, offset + 4);\n offset += 4 + font.data.length;\n }\n assert(offset <= buffer.byteLength, "FontInfo.write: Buffer overflow");\n return buffer.transferToFixedLength(offset);\n }\n}\nclass PatternInfo {\n static #KIND = 0;\n static #HAS_BBOX = 1;\n static #HAS_BACKGROUND = 2;\n static #SHADING_TYPE = 3;\n static #N_COORD = 4;\n static #N_COLOR = 8;\n static #N_STOP = 12;\n static #N_FIGURES = 16;\n constructor(buffer) {\n this.buffer = buffer;\n this.view = new DataView(buffer);\n this.data = new Uint8Array(buffer);\n }\n static write(ir) {\n let kind,\n bbox = null,\n coords = [],\n colors = [],\n colorStops = [],\n figures = [],\n shadingType = null,\n background = null;\n switch (ir[0]) {\n case "RadialAxial":\n kind = ir[1] === "axial" ? 1 : 2;\n bbox = ir[2];\n colorStops = ir[3];\n if (kind === 1) {\n coords.push(...ir[4], ...ir[5]);\n } else {\n coords.push(ir[4][0], ir[4][1], ir[6], ir[5][0], ir[5][1], ir[7]);\n }\n break;\n case "Mesh":\n kind = 3;\n shadingType = ir[1];\n coords = ir[2];\n colors = ir[3];\n figures = ir[4] || [];\n bbox = ir[6];\n background = ir[7];\n break;\n default:\n throw new Error(`Unsupported pattern type: ${ir[0]}`);\n }\n const nCoord = Math.floor(coords.length / 2);\n const nColor = Math.floor(colors.length / 3);\n const nStop = colorStops.length;\n const nFigures = figures.length;\n let figuresSize = 0;\n for (const figure of figures) {\n figuresSize += 1;\n figuresSize = Math.ceil(figuresSize / 4) * 4;\n figuresSize += 4 + figure.coords.length * 4;\n figuresSize += 4 + figure.colors.length * 4;\n if (figure.verticesPerRow !== undefined) {\n figuresSize += 4;\n }\n }\n const byteLen = 20 + nCoord * 8 + nColor * 3 + nStop * 8 + (bbox ? 16 : 0) + (background ? 3 : 0) + figuresSize;\n const buffer = new ArrayBuffer(byteLen);\n const dataView = new DataView(buffer);\n const u8data = new Uint8Array(buffer);\n dataView.setUint8(PatternInfo.#KIND, kind);\n dataView.setUint8(PatternInfo.#HAS_BBOX, bbox ? 1 : 0);\n dataView.setUint8(PatternInfo.#HAS_BACKGROUND, background ? 1 : 0);\n dataView.setUint8(PatternInfo.#SHADING_TYPE, shadingType);\n dataView.setUint32(PatternInfo.#N_COORD, nCoord, true);\n dataView.setUint32(PatternInfo.#N_COLOR, nColor, true);\n dataView.setUint32(PatternInfo.#N_STOP, nStop, true);\n dataView.setUint32(PatternInfo.#N_FIGURES, nFigures, true);\n let offset = 20;\n const coordsView = new Float32Array(buffer, offset, nCoord * 2);\n coordsView.set(coords);\n offset += nCoord * 8;\n u8data.set(colors, offset);\n offset += nColor * 3;\n for (const [pos, hex] of colorStops) {\n dataView.setFloat32(offset, pos, true);\n offset += 4;\n dataView.setUint32(offset, parseInt(hex.slice(1), 16), true);\n offset += 4;\n }\n if (bbox) {\n for (const v of bbox) {\n dataView.setFloat32(offset, v, true);\n offset += 4;\n }\n }\n if (background) {\n u8data.set(background, offset);\n offset += 3;\n }\n for (let i = 0; i < figures.length; i++) {\n const figure = figures[i];\n dataView.setUint8(offset, figure.type);\n offset += 1;\n offset = Math.ceil(offset / 4) * 4;\n dataView.setUint32(offset, figure.coords.length, true);\n offset += 4;\n const figureCoordsView = new Int32Array(buffer, offset, figure.coords.length);\n figureCoordsView.set(figure.coords);\n offset += figure.coords.length * 4;\n dataView.setUint32(offset, figure.colors.length, true);\n offset += 4;\n const colorsView = new Int32Array(buffer, offset, figure.colors.length);\n colorsView.set(figure.colors);\n offset += figure.colors.length * 4;\n if (figure.verticesPerRow !== undefined) {\n dataView.setUint32(offset, figure.verticesPerRow, true);\n offset += 4;\n }\n }\n return buffer;\n }\n getIR() {\n const dataView = this.view;\n const kind = this.data[PatternInfo.#KIND];\n const hasBBox = !!this.data[PatternInfo.#HAS_BBOX];\n const hasBackground = !!this.data[PatternInfo.#HAS_BACKGROUND];\n const nCoord = dataView.getUint32(PatternInfo.#N_COORD, true);\n const nColor = dataView.getUint32(PatternInfo.#N_COLOR, true);\n const nStop = dataView.getUint32(PatternInfo.#N_STOP, true);\n const nFigures = dataView.getUint32(PatternInfo.#N_FIGURES, true);\n let offset = 20;\n const coords = new Float32Array(this.buffer, offset, nCoord * 2);\n offset += nCoord * 8;\n const colors = new Uint8Array(this.buffer, offset, nColor * 3);\n offset += nColor * 3;\n const stops = [];\n for (let i = 0; i < nStop; ++i) {\n const p = dataView.getFloat32(offset, true);\n offset += 4;\n const rgb = dataView.getUint32(offset, true);\n offset += 4;\n stops.push([p, `#${rgb.toString(16).padStart(6, "0")}`]);\n }\n let bbox = null;\n if (hasBBox) {\n bbox = [];\n for (let i = 0; i < 4; ++i) {\n bbox.push(dataView.getFloat32(offset, true));\n offset += 4;\n }\n }\n let background = null;\n if (hasBackground) {\n background = new Uint8Array(this.buffer, offset, 3);\n offset += 3;\n }\n const figures = [];\n for (let i = 0; i < nFigures; ++i) {\n const type = dataView.getUint8(offset);\n offset += 1;\n offset = Math.ceil(offset / 4) * 4;\n const coordsLength = dataView.getUint32(offset, true);\n offset += 4;\n const figureCoords = new Int32Array(this.buffer, offset, coordsLength);\n offset += coordsLength * 4;\n const colorsLength = dataView.getUint32(offset, true);\n offset += 4;\n const figureColors = new Int32Array(this.buffer, offset, colorsLength);\n offset += colorsLength * 4;\n const figure = {\n type,\n coords: figureCoords,\n colors: figureColors\n };\n if (type === MeshFigureType.LATTICE) {\n figure.verticesPerRow = dataView.getUint32(offset, true);\n offset += 4;\n }\n figures.push(figure);\n }\n if (kind === 1) {\n return ["RadialAxial", "axial", bbox, stops, Array.from(coords.slice(0, 2)), Array.from(coords.slice(2, 4)), null, null];\n }\n if (kind === 2) {\n return ["RadialAxial", "radial", bbox, stops, [coords[0], coords[1]], [coords[3], coords[4]], coords[2], coords[5]];\n }\n if (kind === 3) {\n const shadingType = this.data[PatternInfo.#SHADING_TYPE];\n let bounds = null;\n if (coords.length > 0) {\n let minX = coords[0],\n maxX = coords[0];\n let minY = coords[1],\n maxY = coords[1];\n for (let i = 0; i < coords.length; i += 2) {\n const x = coords[i],\n y = coords[i + 1];\n minX = minX > x ? x : minX;\n minY = minY > y ? y : minY;\n maxX = maxX < x ? x : maxX;\n maxY = maxY < y ? y : maxY;\n }\n bounds = [minX, minY, maxX, maxY];\n }\n return ["Mesh", shadingType, coords, colors, figures, bounds, bbox, background];\n }\n throw new Error(`Unsupported pattern kind: ${kind}`);\n }\n}\nclass FontPathInfo {\n static write(path) {\n let data;\n let buffer;\n if (FeatureTest.isFloat16ArraySupported) {\n buffer = new ArrayBuffer(path.length * 2);\n data = new Float16Array(buffer);\n } else {\n buffer = new ArrayBuffer(path.length * 4);\n data = new Float32Array(buffer);\n }\n data.set(path);\n return buffer;\n }\n #buffer;\n constructor(buffer) {\n this.#buffer = buffer;\n }\n get path() {\n if (FeatureTest.isFloat16ArraySupported) {\n return new Float16Array(this.#buffer);\n }\n return new Float32Array(this.#buffer);\n }\n}\n\n;// ./src/display/api_utils.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction getUrlProp(val) {\n if (val instanceof URL) {\n return val;\n }\n if (typeof val === "string") {\n if (isNodeJS) {\n if (/^[a-z][a-z0-9\\-+.]+:/i.test(val)) {\n return new URL(val);\n }\n const url = process.getBuiltinModule("url");\n return new URL(url.pathToFileURL(val));\n }\n const url = URL.parse(val, window.location);\n if (url) {\n return url;\n }\n }\n throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");\n}\nfunction getDataProp(val) {\n if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {\n throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");\n }\n if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {\n return val;\n }\n if (typeof val === "string") {\n return stringToBytes(val);\n }\n if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) {\n return new Uint8Array(val);\n }\n throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");\n}\nfunction getFactoryUrlProp(val) {\n if (typeof val !== "string") {\n return null;\n }\n if (val.endsWith("/")) {\n return val;\n }\n throw new Error(`Invalid factory url: "${val}" must include trailing slash.`);\n}\nconst isRefProxy = v => typeof v === "object" && Number.isInteger(v?.num) && v.num >= 0 && Number.isInteger(v?.gen) && v.gen >= 0;\nconst isNameProxy = v => typeof v === "object" && typeof v?.name === "string";\nconst isValidExplicitDest = _isValidExplicitDest.bind(null, isRefProxy, isNameProxy);\nclass LoopbackPort {\n #listeners = new Map();\n #deferred = Promise.resolve();\n postMessage(obj, transfer) {\n const event = {\n data: structuredClone(obj, transfer ? {\n transfer\n } : null)\n };\n this.#deferred.then(() => {\n for (const [listener] of this.#listeners) {\n listener.call(this, event);\n }\n });\n }\n addEventListener(name, listener, options = null) {\n let rmAbort = null;\n if (options?.signal instanceof AbortSignal) {\n const {\n signal\n } = options;\n if (signal.aborted) {\n warn("LoopbackPort - cannot use an `aborted` signal.");\n return;\n }\n const onAbort = () => this.removeEventListener(name, listener);\n rmAbort = () => signal.removeEventListener("abort", onAbort);\n signal.addEventListener("abort", onAbort);\n }\n this.#listeners.set(listener, rmAbort);\n }\n removeEventListener(name, listener) {\n const rmAbort = this.#listeners.get(listener);\n rmAbort?.();\n this.#listeners.delete(listener);\n }\n terminate() {\n for (const [, rmAbort] of this.#listeners) {\n rmAbort?.();\n }\n this.#listeners.clear();\n }\n}\n\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.promise.try.js\nvar es_promise_try = __webpack_require__(1689);\n;// ./src/shared/message_handler.js\n\n\n\nconst CallbackKind = {\n DATA: 1,\n ERROR: 2\n};\nconst StreamKind = {\n CANCEL: 1,\n CANCEL_COMPLETE: 2,\n CLOSE: 3,\n ENQUEUE: 4,\n ERROR: 5,\n PULL: 6,\n PULL_COMPLETE: 7,\n START_COMPLETE: 8\n};\nfunction onFn() {}\nfunction wrapReason(ex) {\n if (ex instanceof AbortException || ex instanceof InvalidPDFException || ex instanceof PasswordException || ex instanceof ResponseException || ex instanceof UnknownErrorException) {\n return ex;\n }\n if (!(ex instanceof Error || typeof ex === "object" && ex !== null)) {\n unreachable(\'wrapReason: Expected "reason" to be a (possibly cloned) Error.\');\n }\n switch (ex.name) {\n case "AbortException":\n return new AbortException(ex.message);\n case "InvalidPDFException":\n return new InvalidPDFException(ex.message);\n case "PasswordException":\n return new PasswordException(ex.message, ex.code);\n case "ResponseException":\n return new ResponseException(ex.message, ex.status, ex.missing);\n case "UnknownErrorException":\n return new UnknownErrorException(ex.message, ex.details);\n }\n return new UnknownErrorException(ex.message, ex.toString());\n}\nclass MessageHandler {\n #messageAC = new AbortController();\n constructor(sourceName, targetName, comObj) {\n this.sourceName = sourceName;\n this.targetName = targetName;\n this.comObj = comObj;\n this.callbackId = 1;\n this.streamId = 1;\n this.streamSinks = Object.create(null);\n this.streamControllers = Object.create(null);\n this.callbackCapabilities = Object.create(null);\n this.actionHandler = Object.create(null);\n comObj.addEventListener("message", this.#onMessage.bind(this), {\n signal: this.#messageAC.signal\n });\n }\n #onMessage({\n data\n }) {\n if (data.targetName !== this.sourceName) {\n return;\n }\n if (data.stream) {\n this.#processStreamMessage(data);\n return;\n }\n if (data.callback) {\n const callbackId = data.callbackId;\n const capability = this.callbackCapabilities[callbackId];\n if (!capability) {\n throw new Error(`Cannot resolve callback ${callbackId}`);\n }\n delete this.callbackCapabilities[callbackId];\n if (data.callback === CallbackKind.DATA) {\n capability.resolve(data.data);\n } else if (data.callback === CallbackKind.ERROR) {\n capability.reject(wrapReason(data.reason));\n } else {\n throw new Error("Unexpected callback case");\n }\n return;\n }\n const action = this.actionHandler[data.action];\n if (!action) {\n throw new Error(`Unknown action from worker: ${data.action}`);\n }\n if (data.callbackId) {\n const sourceName = this.sourceName,\n targetName = data.sourceName,\n comObj = this.comObj;\n Promise.try(action, data.data).then(function (result) {\n comObj.postMessage({\n sourceName,\n targetName,\n callback: CallbackKind.DATA,\n callbackId: data.callbackId,\n data: result\n });\n }, function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n callback: CallbackKind.ERROR,\n callbackId: data.callbackId,\n reason: wrapReason(reason)\n });\n });\n return;\n }\n if (data.streamId) {\n this.#createStreamSink(data);\n return;\n }\n action(data.data);\n }\n on(actionName, handler) {\n const ah = this.actionHandler;\n if (ah[actionName]) {\n throw new Error(`There is already an actionName called "${actionName}"`);\n }\n ah[actionName] = handler;\n }\n send(actionName, data, transfers) {\n this.comObj.postMessage({\n sourceName: this.sourceName,\n targetName: this.targetName,\n action: actionName,\n data\n }, transfers);\n }\n sendWithPromise(actionName, data, transfers) {\n const callbackId = this.callbackId++;\n const capability = Promise.withResolvers();\n this.callbackCapabilities[callbackId] = capability;\n try {\n this.comObj.postMessage({\n sourceName: this.sourceName,\n targetName: this.targetName,\n action: actionName,\n callbackId,\n data\n }, transfers);\n } catch (ex) {\n capability.reject(ex);\n }\n return capability.promise;\n }\n sendWithStream(actionName, data, queueingStrategy, transfers) {\n const streamId = this.streamId++,\n sourceName = this.sourceName,\n targetName = this.targetName,\n comObj = this.comObj;\n return new ReadableStream({\n start: controller => {\n const startCapability = Promise.withResolvers();\n this.streamControllers[streamId] = {\n controller,\n startCall: startCapability,\n pullCall: null,\n cancelCall: null,\n isClosed: false\n };\n comObj.postMessage({\n sourceName,\n targetName,\n action: actionName,\n streamId,\n data,\n desiredSize: controller.desiredSize\n }, transfers);\n return startCapability.promise;\n },\n pull: controller => {\n const pullCapability = Promise.withResolvers();\n this.streamControllers[streamId].pullCall = pullCapability;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL,\n streamId,\n desiredSize: controller.desiredSize\n });\n return pullCapability.promise;\n },\n cancel: reason => {\n assert(reason instanceof Error, "cancel must have a valid reason");\n const cancelCapability = Promise.withResolvers();\n this.streamControllers[streamId].cancelCall = cancelCapability;\n this.streamControllers[streamId].isClosed = true;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CANCEL,\n streamId,\n reason: wrapReason(reason)\n });\n return cancelCapability.promise;\n }\n }, queueingStrategy);\n }\n #createStreamSink(data) {\n const streamId = data.streamId,\n sourceName = this.sourceName,\n targetName = data.sourceName,\n comObj = this.comObj;\n const self = this,\n action = this.actionHandler[data.action];\n const streamSink = {\n enqueue(chunk, size = 1, transfers) {\n if (this.isCancelled) {\n return;\n }\n const lastDesiredSize = this.desiredSize;\n this.desiredSize -= size;\n if (lastDesiredSize > 0 && this.desiredSize <= 0) {\n this.sinkCapability = Promise.withResolvers();\n this.ready = this.sinkCapability.promise;\n }\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.ENQUEUE,\n streamId,\n chunk\n }, transfers);\n },\n close() {\n if (this.isCancelled) {\n return;\n }\n this.isCancelled = true;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CLOSE,\n streamId\n });\n delete self.streamSinks[streamId];\n },\n error(reason) {\n assert(reason instanceof Error, "error must have a valid reason");\n if (this.isCancelled) {\n return;\n }\n this.isCancelled = true;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.ERROR,\n streamId,\n reason: wrapReason(reason)\n });\n },\n sinkCapability: Promise.withResolvers(),\n onPull: null,\n onCancel: null,\n isCancelled: false,\n desiredSize: data.desiredSize,\n ready: null\n };\n streamSink.sinkCapability.resolve();\n streamSink.ready = streamSink.sinkCapability.promise;\n this.streamSinks[streamId] = streamSink;\n Promise.try(action, data.data, streamSink).then(function () {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.START_COMPLETE,\n streamId,\n success: true\n });\n }, function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.START_COMPLETE,\n streamId,\n reason: wrapReason(reason)\n });\n });\n }\n #processStreamMessage(data) {\n const streamId = data.streamId,\n sourceName = this.sourceName,\n targetName = data.sourceName,\n comObj = this.comObj;\n const streamController = this.streamControllers[streamId],\n streamSink = this.streamSinks[streamId];\n switch (data.stream) {\n case StreamKind.START_COMPLETE:\n if (data.success) {\n streamController.startCall.resolve();\n } else {\n streamController.startCall.reject(wrapReason(data.reason));\n }\n break;\n case StreamKind.PULL_COMPLETE:\n if (data.success) {\n streamController.pullCall.resolve();\n } else {\n streamController.pullCall.reject(wrapReason(data.reason));\n }\n break;\n case StreamKind.PULL:\n if (!streamSink) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL_COMPLETE,\n streamId,\n success: true\n });\n break;\n }\n if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {\n streamSink.sinkCapability.resolve();\n }\n streamSink.desiredSize = data.desiredSize;\n Promise.try(streamSink.onPull || onFn).then(function () {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL_COMPLETE,\n streamId,\n success: true\n });\n }, function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL_COMPLETE,\n streamId,\n reason: wrapReason(reason)\n });\n });\n break;\n case StreamKind.ENQUEUE:\n assert(streamController, "enqueue should have stream controller");\n if (streamController.isClosed) {\n break;\n }\n streamController.controller.enqueue(data.chunk);\n break;\n case StreamKind.CLOSE:\n assert(streamController, "close should have stream controller");\n if (streamController.isClosed) {\n break;\n }\n streamController.isClosed = true;\n streamController.controller.close();\n this.#deleteStreamController(streamController, streamId);\n break;\n case StreamKind.ERROR:\n assert(streamController, "error should have stream controller");\n streamController.controller.error(wrapReason(data.reason));\n this.#deleteStreamController(streamController, streamId);\n break;\n case StreamKind.CANCEL_COMPLETE:\n if (data.success) {\n streamController.cancelCall.resolve();\n } else {\n streamController.cancelCall.reject(wrapReason(data.reason));\n }\n this.#deleteStreamController(streamController, streamId);\n break;\n case StreamKind.CANCEL:\n if (!streamSink) {\n break;\n }\n const dataReason = wrapReason(data.reason);\n Promise.try(streamSink.onCancel || onFn, dataReason).then(function () {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CANCEL_COMPLETE,\n streamId,\n success: true\n });\n }, function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CANCEL_COMPLETE,\n streamId,\n reason: wrapReason(reason)\n });\n });\n streamSink.sinkCapability.reject(dataReason);\n streamSink.isCancelled = true;\n delete this.streamSinks[streamId];\n break;\n default:\n throw new Error("Unexpected stream case");\n }\n }\n async #deleteStreamController(streamController, streamId) {\n await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]);\n delete this.streamControllers[streamId];\n }\n destroy() {\n this.#messageAC?.abort();\n this.#messageAC = null;\n }\n}\n\n;// ./src/display/canvas_factory.js\n\nclass BaseCanvasFactory {\n #enableHWA = false;\n constructor({\n enableHWA = false\n }) {\n this.#enableHWA = enableHWA;\n }\n create(width, height) {\n if (width <= 0 || height <= 0) {\n throw new Error("Invalid canvas size");\n }\n const canvas = this._createCanvas(width, height);\n return {\n canvas,\n context: canvas.getContext("2d", {\n willReadFrequently: !this.#enableHWA\n })\n };\n }\n reset(canvasAndContext, width, height) {\n if (!canvasAndContext.canvas) {\n throw new Error("Canvas is not specified");\n }\n if (width <= 0 || height <= 0) {\n throw new Error("Invalid canvas size");\n }\n canvasAndContext.canvas.width = width;\n canvasAndContext.canvas.height = height;\n }\n destroy(canvasAndContext) {\n if (!canvasAndContext.canvas) {\n throw new Error("Canvas is not specified");\n }\n canvasAndContext.canvas.width = 0;\n canvasAndContext.canvas.height = 0;\n canvasAndContext.canvas = null;\n canvasAndContext.context = null;\n }\n _createCanvas(width, height) {\n unreachable("Abstract method `_createCanvas` called.");\n }\n}\nclass DOMCanvasFactory extends BaseCanvasFactory {\n constructor({\n ownerDocument = globalThis.document,\n enableHWA = false\n }) {\n super({\n enableHWA\n });\n this._document = ownerDocument;\n }\n _createCanvas(width, height) {\n const canvas = this._document.createElement("canvas");\n canvas.width = width;\n canvas.height = height;\n return canvas;\n }\n}\n\n;// ./src/display/cmap_reader_factory.js\n\n\n\n\n\n\n\n\n\n\nclass BaseCMapReaderFactory {\n constructor({\n baseUrl = null,\n isCompressed = true\n }) {\n this.baseUrl = baseUrl;\n this.isCompressed = isCompressed;\n }\n async fetch({\n name\n }) {\n if (!this.baseUrl) {\n throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");\n }\n if (!name) {\n throw new Error("CMap name must be specified.");\n }\n const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");\n return this._fetch(url).then(cMapData => ({\n cMapData,\n isCompressed: this.isCompressed\n })).catch(reason => {\n throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);\n });\n }\n async _fetch(url) {\n unreachable("Abstract method `_fetch` called.");\n }\n}\nclass DOMCMapReaderFactory extends BaseCMapReaderFactory {\n async _fetch(url) {\n const data = await fetchData(url, this.isCompressed ? "bytes" : "text");\n return data instanceof Uint8Array ? data : stringToBytes(data);\n }\n}\n\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.filter.js\nvar es_iterator_filter = __webpack_require__(2489);\n;// ./src/display/filter_factory.js\n\n\n\n\n\n\nclass BaseFilterFactory {\n addFilter(maps) {\n return "none";\n }\n addHCMFilter(fgColor, bgColor) {\n return "none";\n }\n addAlphaFilter(map) {\n return "none";\n }\n addLuminosityFilter(map) {\n return "none";\n }\n addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {\n return "none";\n }\n destroy(keepHCM = false) {}\n}\nclass DOMFilterFactory extends BaseFilterFactory {\n #baseUrl;\n #_cache;\n #_defs;\n #docId;\n #document;\n #_hcmCache;\n #id = 0;\n constructor({\n docId,\n ownerDocument = globalThis.document\n }) {\n super();\n this.#docId = docId;\n this.#document = ownerDocument;\n }\n get #cache() {\n return this.#_cache ||= new Map();\n }\n get #hcmCache() {\n return this.#_hcmCache ||= new Map();\n }\n get #defs() {\n if (!this.#_defs) {\n const div = this.#document.createElement("div");\n const {\n style\n } = div;\n style.visibility = "hidden";\n style.contain = "strict";\n style.width = style.height = 0;\n style.position = "absolute";\n style.top = style.left = 0;\n style.zIndex = -1;\n const svg = this.#document.createElementNS(SVG_NS, "svg");\n svg.setAttribute("width", 0);\n svg.setAttribute("height", 0);\n this.#_defs = this.#document.createElementNS(SVG_NS, "defs");\n div.append(svg);\n svg.append(this.#_defs);\n this.#document.body.append(div);\n }\n return this.#_defs;\n }\n #createTables(maps) {\n if (maps.length === 1) {\n const mapR = maps[0];\n const buffer = new Array(256);\n for (let i = 0; i < 256; i++) {\n buffer[i] = mapR[i] / 255;\n }\n const table = buffer.join(",");\n return [table, table, table];\n }\n const [mapR, mapG, mapB] = maps;\n const bufferR = new Array(256);\n const bufferG = new Array(256);\n const bufferB = new Array(256);\n for (let i = 0; i < 256; i++) {\n bufferR[i] = mapR[i] / 255;\n bufferG[i] = mapG[i] / 255;\n bufferB[i] = mapB[i] / 255;\n }\n return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];\n }\n #createUrl(id) {\n if (this.#baseUrl === undefined) {\n this.#baseUrl = "";\n const url = this.#document.URL;\n if (url !== this.#document.baseURI) {\n if (isDataScheme(url)) {\n warn(\'#createUrl: ignore "data:"-URL for performance reasons.\');\n } else {\n this.#baseUrl = updateUrlHash(url, "");\n }\n }\n }\n return `url(${this.#baseUrl}#${id})`;\n }\n addFilter(maps) {\n if (!maps) {\n return "none";\n }\n let value = this.#cache.get(maps);\n if (value) {\n return value;\n }\n const [tableR, tableG, tableB] = this.#createTables(maps);\n const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;\n value = this.#cache.get(key);\n if (value) {\n this.#cache.set(maps, value);\n return value;\n }\n const id = `g_${this.#docId}_transfer_map_${this.#id++}`;\n const url = this.#createUrl(id);\n this.#cache.set(maps, url);\n this.#cache.set(key, url);\n const filter = this.#createFilter(id);\n this.#addTransferMapConversion(tableR, tableG, tableB, filter);\n return url;\n }\n addHCMFilter(fgColor, bgColor) {\n const key = `${fgColor}-${bgColor}`;\n const filterName = "base";\n let info = this.#hcmCache.get(filterName);\n if (info?.key === key) {\n return info.url;\n }\n if (info) {\n info.filter?.remove();\n info.key = key;\n info.url = "none";\n info.filter = null;\n } else {\n info = {\n key,\n url: "none",\n filter: null\n };\n this.#hcmCache.set(filterName, info);\n }\n if (!fgColor || !bgColor) {\n return info.url;\n }\n const fgRGB = this.#getRGB(fgColor);\n fgColor = Util.makeHexColor(...fgRGB);\n const bgRGB = this.#getRGB(bgColor);\n bgColor = Util.makeHexColor(...bgRGB);\n this.#defs.style.color = "";\n if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {\n return info.url;\n }\n const map = new Array(256);\n for (let i = 0; i <= 255; i++) {\n const x = i / 255;\n map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;\n }\n const table = map.join(",");\n const id = `g_${this.#docId}_hcm_filter`;\n const filter = info.filter = this.#createFilter(id);\n this.#addTransferMapConversion(table, table, table, filter);\n this.#addGrayConversion(filter);\n const getSteps = (c, n) => {\n const start = fgRGB[c] / 255;\n const end = bgRGB[c] / 255;\n const arr = new Array(n + 1);\n for (let i = 0; i <= n; i++) {\n arr[i] = start + i / n * (end - start);\n }\n return arr.join(",");\n };\n this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);\n info.url = this.#createUrl(id);\n return info.url;\n }\n addAlphaFilter(map) {\n let value = this.#cache.get(map);\n if (value) {\n return value;\n }\n const [tableA] = this.#createTables([map]);\n const key = `alpha_${tableA}`;\n value = this.#cache.get(key);\n if (value) {\n this.#cache.set(map, value);\n return value;\n }\n const id = `g_${this.#docId}_alpha_map_${this.#id++}`;\n const url = this.#createUrl(id);\n this.#cache.set(map, url);\n this.#cache.set(key, url);\n const filter = this.#createFilter(id);\n this.#addTransferMapAlphaConversion(tableA, filter);\n return url;\n }\n addLuminosityFilter(map) {\n let value = this.#cache.get(map || "luminosity");\n if (value) {\n return value;\n }\n let tableA, key;\n if (map) {\n [tableA] = this.#createTables([map]);\n key = `luminosity_${tableA}`;\n } else {\n key = "luminosity";\n }\n value = this.#cache.get(key);\n if (value) {\n this.#cache.set(map, value);\n return value;\n }\n const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;\n const url = this.#createUrl(id);\n this.#cache.set(map, url);\n this.#cache.set(key, url);\n const filter = this.#createFilter(id);\n this.#addLuminosityConversion(filter);\n if (map) {\n this.#addTransferMapAlphaConversion(tableA, filter);\n }\n return url;\n }\n addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {\n const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;\n let info = this.#hcmCache.get(filterName);\n if (info?.key === key) {\n return info.url;\n }\n if (info) {\n info.filter?.remove();\n info.key = key;\n info.url = "none";\n info.filter = null;\n } else {\n info = {\n key,\n url: "none",\n filter: null\n };\n this.#hcmCache.set(filterName, info);\n }\n if (!fgColor || !bgColor) {\n return info.url;\n }\n const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));\n let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]);\n let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]);\n let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this));\n if (bgGray < fgGray) {\n [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB];\n }\n this.#defs.style.color = "";\n const getSteps = (fg, bg, n) => {\n const arr = new Array(256);\n const step = (bgGray - fgGray) / n;\n const newStart = fg / 255;\n const newStep = (bg - fg) / (255 * n);\n let prev = 0;\n for (let i = 0; i <= n; i++) {\n const k = Math.round(fgGray + i * step);\n const value = newStart + i * newStep;\n for (let j = prev; j <= k; j++) {\n arr[j] = value;\n }\n prev = k + 1;\n }\n for (let i = prev; i < 256; i++) {\n arr[i] = arr[prev - 1];\n }\n return arr.join(",");\n };\n const id = `g_${this.#docId}_hcm_${filterName}_filter`;\n const filter = info.filter = this.#createFilter(id);\n this.#addGrayConversion(filter);\n this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);\n info.url = this.#createUrl(id);\n return info.url;\n }\n destroy(keepHCM = false) {\n if (keepHCM && this.#_hcmCache?.size) {\n return;\n }\n this.#_defs?.parentNode.parentNode.remove();\n this.#_defs = null;\n this.#_cache?.clear();\n this.#_cache = null;\n this.#_hcmCache?.clear();\n this.#_hcmCache = null;\n this.#id = 0;\n }\n #addLuminosityConversion(filter) {\n const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");\n feColorMatrix.setAttribute("type", "matrix");\n feColorMatrix.setAttribute("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");\n filter.append(feColorMatrix);\n }\n #addGrayConversion(filter) {\n const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");\n feColorMatrix.setAttribute("type", "matrix");\n feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");\n filter.append(feColorMatrix);\n }\n #createFilter(id) {\n const filter = this.#document.createElementNS(SVG_NS, "filter");\n filter.setAttribute("color-interpolation-filters", "sRGB");\n filter.setAttribute("id", id);\n this.#defs.append(filter);\n return filter;\n }\n #appendFeFunc(feComponentTransfer, func, table) {\n const feFunc = this.#document.createElementNS(SVG_NS, func);\n feFunc.setAttribute("type", "discrete");\n feFunc.setAttribute("tableValues", table);\n feComponentTransfer.append(feFunc);\n }\n #addTransferMapConversion(rTable, gTable, bTable, filter) {\n const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");\n filter.append(feComponentTransfer);\n this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable);\n this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable);\n this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable);\n }\n #addTransferMapAlphaConversion(aTable, filter) {\n const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");\n filter.append(feComponentTransfer);\n this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable);\n }\n #getRGB(color) {\n this.#defs.style.color = color;\n return getRGB(getComputedStyle(this.#defs).getPropertyValue("color"));\n }\n}\n\n;// ./src/display/standard_fontdata_factory.js\n\n\nclass BaseStandardFontDataFactory {\n constructor({\n baseUrl = null\n }) {\n this.baseUrl = baseUrl;\n }\n async fetch({\n filename\n }) {\n if (!this.baseUrl) {\n throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");\n }\n if (!filename) {\n throw new Error("Font filename must be specified.");\n }\n const url = `${this.baseUrl}${filename}`;\n return this._fetch(url).catch(reason => {\n throw new Error(`Unable to load font data at: ${url}`);\n });\n }\n async _fetch(url) {\n unreachable("Abstract method `_fetch` called.");\n }\n}\nclass DOMStandardFontDataFactory extends BaseStandardFontDataFactory {\n async _fetch(url) {\n return fetchData(url, "bytes");\n }\n}\n\n;// ./src/display/wasm_factory.js\n\n\nclass BaseWasmFactory {\n constructor({\n baseUrl = null\n }) {\n this.baseUrl = baseUrl;\n }\n async fetch({\n filename\n }) {\n if (!this.baseUrl) {\n throw new Error("Ensure that the `wasmUrl` API parameter is provided.");\n }\n if (!filename) {\n throw new Error("Wasm filename must be specified.");\n }\n const url = `${this.baseUrl}${filename}`;\n return this._fetch(url).catch(reason => {\n throw new Error(`Unable to load wasm data at: ${url}`);\n });\n }\n async _fetch(url) {\n unreachable("Abstract method `_fetch` called.");\n }\n}\nclass DOMWasmFactory extends BaseWasmFactory {\n async _fetch(url) {\n return fetchData(url, "bytes");\n }\n}\n\n;// ./src/display/node_utils.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nif (isNodeJS) {\n let canvas;\n try {\n const require = process.getBuiltinModule("module").createRequire(import.meta.url);\n try {\n canvas = require("@napi-rs/canvas");\n } catch (ex) {\n warn(`Cannot load "@napi-rs/canvas" package: "${ex}".`);\n }\n } catch (ex) {\n warn(`Cannot access the \\`require\\` function: "${ex}".`);\n }\n if (!globalThis.DOMMatrix) {\n if (canvas?.DOMMatrix) {\n globalThis.DOMMatrix = canvas.DOMMatrix;\n } else {\n warn("Cannot polyfill `DOMMatrix`, rendering may be broken.");\n }\n }\n if (!globalThis.ImageData) {\n if (canvas?.ImageData) {\n globalThis.ImageData = canvas.ImageData;\n } else {\n warn("Cannot polyfill `ImageData`, rendering may be broken.");\n }\n }\n if (!globalThis.Path2D) {\n if (canvas?.Path2D) {\n globalThis.Path2D = canvas.Path2D;\n } else {\n warn("Cannot polyfill `Path2D`, rendering may be broken.");\n }\n }\n if (!globalThis.navigator?.language) {\n globalThis.navigator = {\n language: "en-US",\n platform: "",\n userAgent: ""\n };\n }\n}\nasync function node_utils_fetchData(url) {\n const fs = process.getBuiltinModule("fs");\n const data = await fs.promises.readFile(url);\n return new Uint8Array(data);\n}\nclass NodeFilterFactory extends BaseFilterFactory {}\nclass NodeCanvasFactory extends BaseCanvasFactory {\n _createCanvas(width, height) {\n const require = process.getBuiltinModule("module").createRequire(import.meta.url);\n const canvas = require("@napi-rs/canvas");\n return canvas.createCanvas(width, height);\n }\n}\nclass NodeCMapReaderFactory extends BaseCMapReaderFactory {\n async _fetch(url) {\n return node_utils_fetchData(url);\n }\n}\nclass NodeStandardFontDataFactory extends BaseStandardFontDataFactory {\n async _fetch(url) {\n return node_utils_fetchData(url);\n }\n}\nclass NodeWasmFactory extends BaseWasmFactory {\n async _fetch(url) {\n return node_utils_fetchData(url);\n }\n}\n\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.for-each.js\nvar es_iterator_for_each = __webpack_require__(7588);\n;// ./src/display/canvas_dependency_tracker.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst FORCED_DEPENDENCY_LABEL = "__forcedDependency";\nconst {\n floor,\n ceil\n} = Math;\nfunction expandBBox(array, index, minX, minY, maxX, maxY) {\n array[index * 4 + 0] = Math.min(array[index * 4 + 0], minX);\n array[index * 4 + 1] = Math.min(array[index * 4 + 1], minY);\n array[index * 4 + 2] = Math.max(array[index * 4 + 2], maxX);\n array[index * 4 + 3] = Math.max(array[index * 4 + 3], maxY);\n}\nconst EMPTY_BBOX = new Uint32Array(new Uint8Array([255, 255, 0, 0]).buffer)[0];\nclass BBoxReader {\n #bboxes;\n #coords;\n constructor(bboxes, coords) {\n this.#bboxes = bboxes;\n this.#coords = coords;\n }\n get length() {\n return this.#bboxes.length;\n }\n isEmpty(i) {\n return this.#bboxes[i] === EMPTY_BBOX;\n }\n minX(i) {\n return this.#coords[i * 4 + 0] / 256;\n }\n minY(i) {\n return this.#coords[i * 4 + 1] / 256;\n }\n maxX(i) {\n return (this.#coords[i * 4 + 2] + 1) / 256;\n }\n maxY(i) {\n return (this.#coords[i * 4 + 3] + 1) / 256;\n }\n}\nconst ensureDebugMetadata = (map, key) => map?.getOrInsertComputed(key, () => ({\n dependencies: new Set(),\n isRenderingOperation: false\n}));\nclass CanvasDependencyTracker {\n #simple = {\n __proto__: null\n };\n #incremental = {\n __proto__: null,\n transform: [],\n moveText: [],\n sameLineText: [],\n [FORCED_DEPENDENCY_LABEL]: []\n };\n #namedDependencies = new Map();\n #savesStack = [];\n #markedContentStack = [];\n #baseTransformStack = [[1, 0, 0, 1, 0, 0]];\n #clipBox = [-Infinity, -Infinity, Infinity, Infinity];\n #pendingBBox = new Float64Array([Infinity, Infinity, -Infinity, -Infinity]);\n #pendingBBoxIdx = -1;\n #pendingDependencies = new Set();\n #operations = new Map();\n #fontBBoxTrustworthy = new Map();\n #canvasWidth;\n #canvasHeight;\n #bboxesCoords;\n #bboxes;\n #debugMetadata;\n constructor(canvas, operationsCount, recordDebugMetadata = false) {\n this.#canvasWidth = canvas.width;\n this.#canvasHeight = canvas.height;\n this.#initializeBBoxes(operationsCount);\n if (recordDebugMetadata) {\n this.#debugMetadata = new Map();\n }\n }\n growOperationsCount(operationsCount) {\n if (operationsCount >= this.#bboxes.length) {\n this.#initializeBBoxes(operationsCount, this.#bboxes);\n }\n }\n #initializeBBoxes(operationsCount, oldBBoxes) {\n const buffer = new ArrayBuffer(operationsCount * 4);\n this.#bboxesCoords = new Uint8ClampedArray(buffer);\n this.#bboxes = new Uint32Array(buffer);\n if (oldBBoxes && oldBBoxes.length > 0) {\n this.#bboxes.set(oldBBoxes);\n this.#bboxes.fill(EMPTY_BBOX, oldBBoxes.length);\n } else {\n this.#bboxes.fill(EMPTY_BBOX);\n }\n }\n save(opIdx) {\n this.#simple = {\n __proto__: this.#simple\n };\n this.#incremental = {\n __proto__: this.#incremental,\n transform: {\n __proto__: this.#incremental.transform\n },\n moveText: {\n __proto__: this.#incremental.moveText\n },\n sameLineText: {\n __proto__: this.#incremental.sameLineText\n },\n [FORCED_DEPENDENCY_LABEL]: {\n __proto__: this.#incremental[FORCED_DEPENDENCY_LABEL]\n }\n };\n this.#clipBox = {\n __proto__: this.#clipBox\n };\n this.#savesStack.push(opIdx);\n return this;\n }\n restore(opIdx) {\n const previous = Object.getPrototypeOf(this.#simple);\n if (previous === null) {\n return this;\n }\n this.#simple = previous;\n this.#incremental = Object.getPrototypeOf(this.#incremental);\n this.#clipBox = Object.getPrototypeOf(this.#clipBox);\n const lastSave = this.#savesStack.pop();\n if (lastSave !== undefined) {\n ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave);\n this.#bboxes[opIdx] = this.#bboxes[lastSave];\n }\n return this;\n }\n recordOpenMarker(idx) {\n this.#savesStack.push(idx);\n return this;\n }\n getOpenMarker() {\n if (this.#savesStack.length === 0) {\n return null;\n }\n return this.#savesStack.at(-1);\n }\n recordCloseMarker(opIdx) {\n const lastSave = this.#savesStack.pop();\n if (lastSave !== undefined) {\n ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave);\n this.#bboxes[opIdx] = this.#bboxes[lastSave];\n }\n return this;\n }\n beginMarkedContent(opIdx) {\n this.#markedContentStack.push(opIdx);\n return this;\n }\n endMarkedContent(opIdx) {\n const lastSave = this.#markedContentStack.pop();\n if (lastSave !== undefined) {\n ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave);\n this.#bboxes[opIdx] = this.#bboxes[lastSave];\n }\n return this;\n }\n pushBaseTransform(ctx) {\n this.#baseTransformStack.push(Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform()));\n return this;\n }\n popBaseTransform() {\n if (this.#baseTransformStack.length > 1) {\n this.#baseTransformStack.pop();\n }\n return this;\n }\n recordSimpleData(name, idx) {\n this.#simple[name] = idx;\n return this;\n }\n recordIncrementalData(name, idx) {\n this.#incremental[name].push(idx);\n return this;\n }\n resetIncrementalData(name, idx) {\n this.#incremental[name].length = 0;\n return this;\n }\n recordNamedData(name, idx) {\n this.#namedDependencies.set(name, idx);\n return this;\n }\n recordSimpleDataFromNamed(name, depName, fallbackIdx) {\n this.#simple[name] = this.#namedDependencies.get(depName) ?? fallbackIdx;\n }\n recordFutureForcedDependency(name, idx) {\n this.recordIncrementalData(FORCED_DEPENDENCY_LABEL, idx);\n return this;\n }\n inheritSimpleDataAsFutureForcedDependencies(names) {\n for (const name of names) {\n if (name in this.#simple) {\n this.recordFutureForcedDependency(name, this.#simple[name]);\n }\n }\n return this;\n }\n inheritPendingDependenciesAsFutureForcedDependencies() {\n for (const dep of this.#pendingDependencies) {\n this.recordFutureForcedDependency(FORCED_DEPENDENCY_LABEL, dep);\n }\n return this;\n }\n resetBBox(idx) {\n if (this.#pendingBBoxIdx !== idx) {\n this.#pendingBBoxIdx = idx;\n this.#pendingBBox[0] = Infinity;\n this.#pendingBBox[1] = Infinity;\n this.#pendingBBox[2] = -Infinity;\n this.#pendingBBox[3] = -Infinity;\n }\n return this;\n }\n recordClipBox(idx, ctx, minX, maxX, minY, maxY) {\n const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform());\n const clipBox = [Infinity, Infinity, -Infinity, -Infinity];\n Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, clipBox);\n const intersection = Util.intersect(this.#clipBox, clipBox);\n if (intersection) {\n this.#clipBox[0] = intersection[0];\n this.#clipBox[1] = intersection[1];\n this.#clipBox[2] = intersection[2];\n this.#clipBox[3] = intersection[3];\n } else {\n this.#clipBox[0] = this.#clipBox[1] = Infinity;\n this.#clipBox[2] = this.#clipBox[3] = -Infinity;\n }\n return this;\n }\n recordBBox(idx, ctx, minX, maxX, minY, maxY) {\n const clipBox = this.#clipBox;\n if (clipBox[0] === Infinity) {\n return this;\n }\n const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform());\n if (clipBox[0] === -Infinity) {\n Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, this.#pendingBBox);\n return this;\n }\n const bbox = [Infinity, Infinity, -Infinity, -Infinity];\n Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, bbox);\n this.#pendingBBox[0] = Math.min(this.#pendingBBox[0], Math.max(bbox[0], clipBox[0]));\n this.#pendingBBox[1] = Math.min(this.#pendingBBox[1], Math.max(bbox[1], clipBox[1]));\n this.#pendingBBox[2] = Math.max(this.#pendingBBox[2], Math.min(bbox[2], clipBox[2]));\n this.#pendingBBox[3] = Math.max(this.#pendingBBox[3], Math.min(bbox[3], clipBox[3]));\n return this;\n }\n recordCharacterBBox(idx, ctx, font, scale = 1, x = 0, y = 0, getMeasure) {\n const fontBBox = font.bbox;\n let isBBoxTrustworthy;\n let computedBBox;\n if (fontBBox) {\n isBBoxTrustworthy = fontBBox[2] !== fontBBox[0] && fontBBox[3] !== fontBBox[1] && this.#fontBBoxTrustworthy.get(font);\n if (isBBoxTrustworthy !== false) {\n computedBBox = [0, 0, 0, 0];\n Util.axialAlignedBoundingBox(fontBBox, font.fontMatrix, computedBBox);\n if (scale !== 1 || x !== 0 || y !== 0) {\n Util.scaleMinMax([scale, 0, 0, -scale, x, y], computedBBox);\n }\n if (isBBoxTrustworthy) {\n return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]);\n }\n }\n }\n if (!getMeasure) {\n return this.recordFullPageBBox(idx);\n }\n const measure = getMeasure();\n if (fontBBox && computedBBox && isBBoxTrustworthy === undefined) {\n isBBoxTrustworthy = computedBBox[0] <= x - measure.actualBoundingBoxLeft && computedBBox[2] >= x + measure.actualBoundingBoxRight && computedBBox[1] <= y - measure.actualBoundingBoxAscent && computedBBox[3] >= y + measure.actualBoundingBoxDescent;\n this.#fontBBoxTrustworthy.set(font, isBBoxTrustworthy);\n if (isBBoxTrustworthy) {\n return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]);\n }\n }\n return this.recordBBox(idx, ctx, x - measure.actualBoundingBoxLeft, x + measure.actualBoundingBoxRight, y - measure.actualBoundingBoxAscent, y + measure.actualBoundingBoxDescent);\n }\n recordFullPageBBox(idx) {\n this.#pendingBBox[0] = Math.max(0, this.#clipBox[0]);\n this.#pendingBBox[1] = Math.max(0, this.#clipBox[1]);\n this.#pendingBBox[2] = Math.min(this.#canvasWidth, this.#clipBox[2]);\n this.#pendingBBox[3] = Math.min(this.#canvasHeight, this.#clipBox[3]);\n return this;\n }\n getSimpleIndex(dependencyName) {\n return this.#simple[dependencyName];\n }\n recordDependencies(idx, dependencyNames) {\n const pendingDependencies = this.#pendingDependencies;\n const simple = this.#simple;\n const incremental = this.#incremental;\n for (const name of dependencyNames) {\n if (name in this.#simple) {\n pendingDependencies.add(simple[name]);\n } else if (name in incremental) {\n incremental[name].forEach(pendingDependencies.add, pendingDependencies);\n }\n }\n return this;\n }\n recordNamedDependency(idx, name) {\n if (this.#namedDependencies.has(name)) {\n this.#pendingDependencies.add(this.#namedDependencies.get(name));\n }\n return this;\n }\n recordOperation(idx, preserve = false) {\n this.recordDependencies(idx, [FORCED_DEPENDENCY_LABEL]);\n if (this.#debugMetadata) {\n const metadata = ensureDebugMetadata(this.#debugMetadata, idx);\n const {\n dependencies\n } = metadata;\n this.#pendingDependencies.forEach(dependencies.add, dependencies);\n this.#savesStack.forEach(dependencies.add, dependencies);\n this.#markedContentStack.forEach(dependencies.add, dependencies);\n dependencies.delete(idx);\n metadata.isRenderingOperation = true;\n }\n if (this.#pendingBBoxIdx === idx) {\n const minX = floor(this.#pendingBBox[0] * 256 / this.#canvasWidth);\n const minY = floor(this.#pendingBBox[1] * 256 / this.#canvasHeight);\n const maxX = ceil(this.#pendingBBox[2] * 256 / this.#canvasWidth);\n const maxY = ceil(this.#pendingBBox[3] * 256 / this.#canvasHeight);\n expandBBox(this.#bboxesCoords, idx, minX, minY, maxX, maxY);\n for (const depIdx of this.#pendingDependencies) {\n if (depIdx !== idx) {\n expandBBox(this.#bboxesCoords, depIdx, minX, minY, maxX, maxY);\n }\n }\n for (const saveIdx of this.#savesStack) {\n if (saveIdx !== idx) {\n expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY);\n }\n }\n for (const saveIdx of this.#markedContentStack) {\n if (saveIdx !== idx) {\n expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY);\n }\n }\n if (!preserve) {\n this.#pendingDependencies.clear();\n this.#pendingBBoxIdx = -1;\n }\n }\n return this;\n }\n recordShowTextOperation(idx, preserve = false) {\n const deps = Array.from(this.#pendingDependencies);\n this.recordOperation(idx, preserve);\n this.recordIncrementalData("sameLineText", idx);\n for (const dep of deps) {\n this.recordIncrementalData("sameLineText", dep);\n }\n return this;\n }\n bboxToClipBoxDropOperation(idx, preserve = false) {\n if (this.#pendingBBoxIdx === idx) {\n this.#pendingBBoxIdx = -1;\n this.#clipBox[0] = Math.max(this.#clipBox[0], this.#pendingBBox[0]);\n this.#clipBox[1] = Math.max(this.#clipBox[1], this.#pendingBBox[1]);\n this.#clipBox[2] = Math.min(this.#clipBox[2], this.#pendingBBox[2]);\n this.#clipBox[3] = Math.min(this.#clipBox[3], this.#pendingBBox[3]);\n if (!preserve) {\n this.#pendingDependencies.clear();\n }\n }\n return this;\n }\n _takePendingDependencies() {\n const pendingDependencies = this.#pendingDependencies;\n this.#pendingDependencies = new Set();\n return pendingDependencies;\n }\n _extractOperation(idx) {\n const operation = this.#operations.get(idx);\n this.#operations.delete(idx);\n return operation;\n }\n _pushPendingDependencies(dependencies) {\n for (const dep of dependencies) {\n this.#pendingDependencies.add(dep);\n }\n }\n take() {\n this.#fontBBoxTrustworthy.clear();\n return new BBoxReader(this.#bboxes, this.#bboxesCoords);\n }\n takeDebugMetadata() {\n return this.#debugMetadata;\n }\n}\nclass CanvasNestedDependencyTracker {\n #dependencyTracker;\n #opIdx;\n #ignoreBBoxes;\n #nestingLevel = 0;\n #savesLevel = 0;\n constructor(dependencyTracker, opIdx, ignoreBBoxes) {\n if (dependencyTracker instanceof CanvasNestedDependencyTracker && dependencyTracker.#ignoreBBoxes === !!ignoreBBoxes) {\n return dependencyTracker;\n }\n this.#dependencyTracker = dependencyTracker;\n this.#opIdx = opIdx;\n this.#ignoreBBoxes = !!ignoreBBoxes;\n }\n growOperationsCount() {\n throw new Error("Unreachable");\n }\n save(opIdx) {\n this.#savesLevel++;\n this.#dependencyTracker.save(this.#opIdx);\n return this;\n }\n restore(opIdx) {\n if (this.#savesLevel > 0) {\n this.#dependencyTracker.restore(this.#opIdx);\n this.#savesLevel--;\n }\n return this;\n }\n recordOpenMarker(idx) {\n this.#nestingLevel++;\n return this;\n }\n getOpenMarker() {\n return this.#nestingLevel > 0 ? this.#opIdx : this.#dependencyTracker.getOpenMarker();\n }\n recordCloseMarker(idx) {\n this.#nestingLevel--;\n return this;\n }\n beginMarkedContent(opIdx) {\n return this;\n }\n endMarkedContent(opIdx) {\n return this;\n }\n pushBaseTransform(ctx) {\n this.#dependencyTracker.pushBaseTransform(ctx);\n return this;\n }\n popBaseTransform() {\n this.#dependencyTracker.popBaseTransform();\n return this;\n }\n recordSimpleData(name, idx) {\n this.#dependencyTracker.recordSimpleData(name, this.#opIdx);\n return this;\n }\n recordIncrementalData(name, idx) {\n this.#dependencyTracker.recordIncrementalData(name, this.#opIdx);\n return this;\n }\n resetIncrementalData(name, idx) {\n this.#dependencyTracker.resetIncrementalData(name, this.#opIdx);\n return this;\n }\n recordNamedData(name, idx) {\n return this;\n }\n recordSimpleDataFromNamed(name, depName, fallbackIdx) {\n this.#dependencyTracker.recordSimpleDataFromNamed(name, depName, this.#opIdx);\n return this;\n }\n recordFutureForcedDependency(name, idx) {\n this.#dependencyTracker.recordFutureForcedDependency(name, this.#opIdx);\n return this;\n }\n inheritSimpleDataAsFutureForcedDependencies(names) {\n this.#dependencyTracker.inheritSimpleDataAsFutureForcedDependencies(names);\n return this;\n }\n inheritPendingDependenciesAsFutureForcedDependencies() {\n this.#dependencyTracker.inheritPendingDependenciesAsFutureForcedDependencies();\n return this;\n }\n resetBBox(idx) {\n if (!this.#ignoreBBoxes) {\n this.#dependencyTracker.resetBBox(this.#opIdx);\n }\n return this;\n }\n recordClipBox(idx, ctx, minX, maxX, minY, maxY) {\n if (!this.#ignoreBBoxes) {\n this.#dependencyTracker.recordClipBox(this.#opIdx, ctx, minX, maxX, minY, maxY);\n }\n return this;\n }\n recordBBox(idx, ctx, minX, maxX, minY, maxY) {\n if (!this.#ignoreBBoxes) {\n this.#dependencyTracker.recordBBox(this.#opIdx, ctx, minX, maxX, minY, maxY);\n }\n return this;\n }\n recordCharacterBBox(idx, ctx, font, scale, x, y, getMeasure) {\n if (!this.#ignoreBBoxes) {\n this.#dependencyTracker.recordCharacterBBox(this.#opIdx, ctx, font, scale, x, y, getMeasure);\n }\n return this;\n }\n recordFullPageBBox(idx) {\n if (!this.#ignoreBBoxes) {\n this.#dependencyTracker.recordFullPageBBox(this.#opIdx);\n }\n return this;\n }\n getSimpleIndex(dependencyName) {\n return this.#dependencyTracker.getSimpleIndex(dependencyName);\n }\n recordDependencies(idx, dependencyNames) {\n this.#dependencyTracker.recordDependencies(this.#opIdx, dependencyNames);\n return this;\n }\n recordNamedDependency(idx, name) {\n this.#dependencyTracker.recordNamedDependency(this.#opIdx, name);\n return this;\n }\n recordOperation(idx) {\n this.#dependencyTracker.recordOperation(this.#opIdx, true);\n return this;\n }\n recordShowTextOperation(idx) {\n this.#dependencyTracker.recordShowTextOperation(this.#opIdx, true);\n return this;\n }\n bboxToClipBoxDropOperation(idx) {\n if (!this.#ignoreBBoxes) {\n this.#dependencyTracker.bboxToClipBoxDropOperation(this.#opIdx, true);\n }\n return this;\n }\n take() {\n throw new Error("Unreachable");\n }\n takeDebugMetadata() {\n throw new Error("Unreachable");\n }\n}\nconst Dependencies = {\n stroke: ["path", "transform", "filter", "strokeColor", "strokeAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "dash"],\n fill: ["path", "transform", "filter", "fillColor", "fillAlpha", "globalCompositeOperation", "SMask"],\n imageXObject: ["transform", "SMask", "filter", "fillAlpha", "strokeAlpha", "globalCompositeOperation"],\n rawFillPath: ["filter", "fillColor", "fillAlpha"],\n showText: ["transform", "leading", "charSpacing", "wordSpacing", "hScale", "textRise", "moveText", "textMatrix", "font", "fontObj", "filter", "fillColor", "textRenderingMode", "SMask", "fillAlpha", "strokeAlpha", "globalCompositeOperation", "sameLineText"],\n transform: ["transform"],\n transformAndFill: ["transform", "fillColor"]\n};\n\n;// ./src/display/pattern_helper.js\n\n\n\n\n\n\nconst PathType = {\n FILL: "Fill",\n STROKE: "Stroke",\n SHADING: "Shading"\n};\nfunction applyBoundingBox(ctx, bbox) {\n if (!bbox) {\n return;\n }\n const width = bbox[2] - bbox[0];\n const height = bbox[3] - bbox[1];\n const region = new Path2D();\n region.rect(bbox[0], bbox[1], width, height);\n ctx.clip(region);\n}\nclass BaseShadingPattern {\n isModifyingCurrentTransform() {\n return false;\n }\n getPattern() {\n unreachable("Abstract method `getPattern` called.");\n }\n}\nclass RadialAxialShadingPattern extends BaseShadingPattern {\n constructor(IR) {\n super();\n this._type = IR[1];\n this._bbox = IR[2];\n this._colorStops = IR[3];\n this._p0 = IR[4];\n this._p1 = IR[5];\n this._r0 = IR[6];\n this._r1 = IR[7];\n this.matrix = null;\n }\n isOriginBased() {\n return this._p0[0] === 0 && this._p0[1] === 0 && (!this.isRadial() || this._p1[0] === 0 && this._p1[1] === 0);\n }\n isRadial() {\n return this._type === "radial";\n }\n _createGradient(ctx, transform = null) {\n let grad;\n let firstPoint = this._p0;\n let secondPoint = this._p1;\n if (transform) {\n firstPoint = firstPoint.slice();\n secondPoint = secondPoint.slice();\n Util.applyTransform(firstPoint, transform);\n Util.applyTransform(secondPoint, transform);\n }\n if (this._type === "axial") {\n grad = ctx.createLinearGradient(firstPoint[0], firstPoint[1], secondPoint[0], secondPoint[1]);\n } else if (this._type === "radial") {\n let r0 = this._r0;\n let r1 = this._r1;\n if (transform) {\n const scale = new Float32Array(2);\n Util.singularValueDecompose2dScale(transform, scale);\n r0 *= scale[0];\n r1 *= scale[0];\n }\n grad = ctx.createRadialGradient(firstPoint[0], firstPoint[1], r0, secondPoint[0], secondPoint[1], r1);\n }\n for (const colorStop of this._colorStops) {\n grad.addColorStop(colorStop[0], colorStop[1]);\n }\n return grad;\n }\n getPattern(ctx, owner, inverse, pathType) {\n let pattern;\n if (pathType === PathType.STROKE || pathType === PathType.FILL) {\n if (this.isOriginBased()) {\n let transf = Util.transform(inverse, owner.baseTransform);\n if (this.matrix) {\n transf = Util.transform(transf, this.matrix);\n }\n const precision = 1e-3;\n const n1 = Math.hypot(transf[0], transf[1]);\n const n2 = Math.hypot(transf[2], transf[3]);\n const ps = (transf[0] * transf[2] + transf[1] * transf[3]) / (n1 * n2);\n if (Math.abs(ps) < precision) {\n if (this.isRadial()) {\n if (Math.abs(n1 - n2) < precision) {\n return this._createGradient(ctx, transf);\n }\n } else {\n return this._createGradient(ctx, transf);\n }\n }\n }\n const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0];\n const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;\n const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;\n const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height);\n const tmpCtx = tmpCanvas.context;\n tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);\n tmpCtx.beginPath();\n tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);\n tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);\n inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);\n tmpCtx.transform(...owner.baseTransform);\n if (this.matrix) {\n tmpCtx.transform(...this.matrix);\n }\n applyBoundingBox(tmpCtx, this._bbox);\n tmpCtx.fillStyle = this._createGradient(tmpCtx);\n tmpCtx.fill();\n pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");\n const domMatrix = new DOMMatrix(inverse);\n pattern.setTransform(domMatrix);\n } else {\n applyBoundingBox(ctx, this._bbox);\n pattern = this._createGradient(ctx);\n }\n return pattern;\n }\n}\nfunction drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {\n const coords = context.coords,\n colors = context.colors;\n const bytes = data.data,\n rowSize = data.width * 4;\n let tmp;\n if (coords[p1 + 1] > coords[p2 + 1]) {\n tmp = p1;\n p1 = p2;\n p2 = tmp;\n tmp = c1;\n c1 = c2;\n c2 = tmp;\n }\n if (coords[p2 + 1] > coords[p3 + 1]) {\n tmp = p2;\n p2 = p3;\n p3 = tmp;\n tmp = c2;\n c2 = c3;\n c3 = tmp;\n }\n if (coords[p1 + 1] > coords[p2 + 1]) {\n tmp = p1;\n p1 = p2;\n p2 = tmp;\n tmp = c1;\n c1 = c2;\n c2 = tmp;\n }\n const x1 = (coords[p1] + context.offsetX) * context.scaleX;\n const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;\n const x2 = (coords[p2] + context.offsetX) * context.scaleX;\n const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;\n const x3 = (coords[p3] + context.offsetX) * context.scaleX;\n const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;\n if (y1 >= y3) {\n return;\n }\n const c1r = colors[c1],\n c1g = colors[c1 + 1],\n c1b = colors[c1 + 2];\n const c2r = colors[c2],\n c2g = colors[c2 + 1],\n c2b = colors[c2 + 2];\n const c3r = colors[c3],\n c3g = colors[c3 + 1],\n c3b = colors[c3 + 2];\n const minY = Math.round(y1),\n maxY = Math.round(y3);\n let xa, car, cag, cab;\n let xb, cbr, cbg, cbb;\n for (let y = minY; y <= maxY; y++) {\n if (y < y2) {\n const k = y < y1 ? 0 : (y1 - y) / (y1 - y2);\n xa = x1 - (x1 - x2) * k;\n car = c1r - (c1r - c2r) * k;\n cag = c1g - (c1g - c2g) * k;\n cab = c1b - (c1b - c2b) * k;\n } else {\n let k;\n if (y > y3) {\n k = 1;\n } else if (y2 === y3) {\n k = 0;\n } else {\n k = (y2 - y) / (y2 - y3);\n }\n xa = x2 - (x2 - x3) * k;\n car = c2r - (c2r - c3r) * k;\n cag = c2g - (c2g - c3g) * k;\n cab = c2b - (c2b - c3b) * k;\n }\n let k;\n if (y < y1) {\n k = 0;\n } else if (y > y3) {\n k = 1;\n } else {\n k = (y1 - y) / (y1 - y3);\n }\n xb = x1 - (x1 - x3) * k;\n cbr = c1r - (c1r - c3r) * k;\n cbg = c1g - (c1g - c3g) * k;\n cbb = c1b - (c1b - c3b) * k;\n const x1_ = Math.round(Math.min(xa, xb));\n const x2_ = Math.round(Math.max(xa, xb));\n let j = rowSize * y + x1_ * 4;\n for (let x = x1_; x <= x2_; x++) {\n k = (xa - x) / (xa - xb);\n if (k < 0) {\n k = 0;\n } else if (k > 1) {\n k = 1;\n }\n bytes[j++] = car - (car - cbr) * k | 0;\n bytes[j++] = cag - (cag - cbg) * k | 0;\n bytes[j++] = cab - (cab - cbb) * k | 0;\n bytes[j++] = 255;\n }\n }\n}\nfunction drawFigure(data, figure, context) {\n const ps = figure.coords;\n const cs = figure.colors;\n let i, ii;\n switch (figure.type) {\n case MeshFigureType.LATTICE:\n const verticesPerRow = figure.verticesPerRow;\n const rows = Math.floor(ps.length / verticesPerRow) - 1;\n const cols = verticesPerRow - 1;\n for (i = 0; i < rows; i++) {\n let q = i * verticesPerRow;\n for (let j = 0; j < cols; j++, q++) {\n drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);\n drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);\n }\n }\n break;\n case MeshFigureType.TRIANGLES:\n for (i = 0, ii = ps.length; i < ii; i += 3) {\n drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);\n }\n break;\n default:\n throw new Error("illegal figure");\n }\n}\nclass MeshShadingPattern extends BaseShadingPattern {\n constructor(IR) {\n super();\n this._coords = IR[2];\n this._colors = IR[3];\n this._figures = IR[4];\n this._bounds = IR[5];\n this._bbox = IR[6];\n this._background = IR[7];\n this.matrix = null;\n }\n _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {\n const EXPECTED_SCALE = 1.1;\n const MAX_PATTERN_SIZE = 3000;\n const BORDER_SIZE = 2;\n const offsetX = Math.floor(this._bounds[0]);\n const offsetY = Math.floor(this._bounds[1]);\n const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;\n const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;\n const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);\n const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);\n const scaleX = boundsWidth / width;\n const scaleY = boundsHeight / height;\n const context = {\n coords: this._coords,\n colors: this._colors,\n offsetX: -offsetX,\n offsetY: -offsetY,\n scaleX: 1 / scaleX,\n scaleY: 1 / scaleY\n };\n const paddedWidth = width + BORDER_SIZE * 2;\n const paddedHeight = height + BORDER_SIZE * 2;\n const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight);\n const tmpCtx = tmpCanvas.context;\n const data = tmpCtx.createImageData(width, height);\n if (backgroundColor) {\n const bytes = data.data;\n for (let i = 0, ii = bytes.length; i < ii; i += 4) {\n bytes[i] = backgroundColor[0];\n bytes[i + 1] = backgroundColor[1];\n bytes[i + 2] = backgroundColor[2];\n bytes[i + 3] = 255;\n }\n }\n for (const figure of this._figures) {\n drawFigure(data, figure, context);\n }\n tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);\n const canvas = tmpCanvas.canvas;\n return {\n canvas,\n offsetX: offsetX - BORDER_SIZE * scaleX,\n offsetY: offsetY - BORDER_SIZE * scaleY,\n scaleX,\n scaleY\n };\n }\n isModifyingCurrentTransform() {\n return true;\n }\n getPattern(ctx, owner, inverse, pathType) {\n applyBoundingBox(ctx, this._bbox);\n const scale = new Float32Array(2);\n if (pathType === PathType.SHADING) {\n Util.singularValueDecompose2dScale(getCurrentTransform(ctx), scale);\n } else if (this.matrix) {\n Util.singularValueDecompose2dScale(this.matrix, scale);\n const [matrixScaleX, matrixScaleY] = scale;\n Util.singularValueDecompose2dScale(owner.baseTransform, scale);\n scale[0] *= matrixScaleX;\n scale[1] *= matrixScaleY;\n } else {\n Util.singularValueDecompose2dScale(owner.baseTransform, scale);\n }\n const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);\n if (pathType !== PathType.SHADING) {\n ctx.setTransform(...owner.baseTransform);\n if (this.matrix) {\n ctx.transform(...this.matrix);\n }\n }\n ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);\n ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);\n return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");\n }\n}\nclass DummyShadingPattern extends BaseShadingPattern {\n getPattern() {\n return "hotpink";\n }\n}\nfunction getShadingPattern(IR) {\n switch (IR[0]) {\n case "RadialAxial":\n return new RadialAxialShadingPattern(IR);\n case "Mesh":\n return new MeshShadingPattern(IR);\n case "Dummy":\n return new DummyShadingPattern();\n }\n throw new Error(`Unknown IR type: ${IR[0]}`);\n}\nconst PaintType = {\n COLORED: 1,\n UNCOLORED: 2\n};\nclass TilingPattern {\n static MAX_PATTERN_SIZE = 3000;\n constructor(IR, ctx, canvasGraphicsFactory, baseTransform) {\n this.color = IR[1];\n this.operatorList = IR[2];\n this.matrix = IR[3];\n this.bbox = IR[4];\n this.xstep = IR[5];\n this.ystep = IR[6];\n this.paintType = IR[7];\n this.tilingType = IR[8];\n this.ctx = ctx;\n this.canvasGraphicsFactory = canvasGraphicsFactory;\n this.baseTransform = baseTransform;\n }\n createPatternCanvas(owner, opIdx) {\n const {\n bbox,\n operatorList,\n paintType,\n tilingType,\n color,\n canvasGraphicsFactory\n } = this;\n let {\n xstep,\n ystep\n } = this;\n xstep = Math.abs(xstep);\n ystep = Math.abs(ystep);\n info("TilingType: " + tilingType);\n const x0 = bbox[0],\n y0 = bbox[1],\n x1 = bbox[2],\n y1 = bbox[3];\n const width = x1 - x0;\n const height = y1 - y0;\n const scale = new Float32Array(2);\n Util.singularValueDecompose2dScale(this.matrix, scale);\n const [matrixScaleX, matrixScaleY] = scale;\n Util.singularValueDecompose2dScale(this.baseTransform, scale);\n const combinedScaleX = matrixScaleX * scale[0];\n const combinedScaleY = matrixScaleY * scale[1];\n let canvasWidth = width,\n canvasHeight = height,\n redrawHorizontally = false,\n redrawVertically = false;\n const xScaledStep = Math.ceil(xstep * combinedScaleX);\n const yScaledStep = Math.ceil(ystep * combinedScaleY);\n const xScaledWidth = Math.ceil(width * combinedScaleX);\n const yScaledHeight = Math.ceil(height * combinedScaleY);\n if (xScaledStep >= xScaledWidth) {\n canvasWidth = xstep;\n } else {\n redrawHorizontally = true;\n }\n if (yScaledStep >= yScaledHeight) {\n canvasHeight = ystep;\n } else {\n redrawVertically = true;\n }\n const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);\n const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);\n const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size);\n const tmpCtx = tmpCanvas.context;\n const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx, opIdx);\n graphics.groupLevel = owner.groupLevel;\n this.setFillAndStrokeStyleToContext(graphics, paintType, color);\n tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0);\n graphics.transform(0, dimx.scale, 0, 0, dimy.scale, 0, 0);\n tmpCtx.save();\n graphics.dependencyTracker?.save();\n this.clipBbox(graphics, x0, y0, x1, y1);\n graphics.baseTransform = getCurrentTransform(graphics.ctx);\n graphics.executeOperatorList(operatorList);\n graphics.endDrawing();\n graphics.dependencyTracker?.restore();\n tmpCtx.restore();\n if (redrawHorizontally || redrawVertically) {\n const image = tmpCanvas.canvas;\n if (redrawHorizontally) {\n canvasWidth = xstep;\n }\n if (redrawVertically) {\n canvasHeight = ystep;\n }\n const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);\n const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);\n const xSize = dimx2.size;\n const ySize = dimy2.size;\n const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize);\n const tmpCtx2 = tmpCanvas2.context;\n const ii = redrawHorizontally ? Math.floor(width / xstep) : 0;\n const jj = redrawVertically ? Math.floor(height / ystep) : 0;\n for (let i = 0; i <= ii; i++) {\n for (let j = 0; j <= jj; j++) {\n tmpCtx2.drawImage(image, xSize * i, ySize * j, xSize, ySize, 0, 0, xSize, ySize);\n }\n }\n return {\n canvas: tmpCanvas2.canvas,\n scaleX: dimx2.scale,\n scaleY: dimy2.scale,\n offsetX: x0,\n offsetY: y0\n };\n }\n return {\n canvas: tmpCanvas.canvas,\n scaleX: dimx.scale,\n scaleY: dimy.scale,\n offsetX: x0,\n offsetY: y0\n };\n }\n getSizeAndScale(step, realOutputSize, scale) {\n const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);\n let size = Math.ceil(step * scale);\n if (size >= maxSize) {\n size = maxSize;\n } else {\n scale = size / step;\n }\n return {\n scale,\n size\n };\n }\n clipBbox(graphics, x0, y0, x1, y1) {\n const bboxWidth = x1 - x0;\n const bboxHeight = y1 - y0;\n graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);\n Util.axialAlignedBoundingBox([x0, y0, x1, y1], getCurrentTransform(graphics.ctx), graphics.current.minMax);\n graphics.clip();\n graphics.endPath();\n }\n setFillAndStrokeStyleToContext(graphics, paintType, color) {\n const context = graphics.ctx,\n current = graphics.current;\n switch (paintType) {\n case PaintType.COLORED:\n const {\n fillStyle,\n strokeStyle\n } = this.ctx;\n context.fillStyle = current.fillColor = fillStyle;\n context.strokeStyle = current.strokeColor = strokeStyle;\n break;\n case PaintType.UNCOLORED:\n context.fillStyle = context.strokeStyle = color;\n current.fillColor = current.strokeColor = color;\n break;\n default:\n throw new FormatError(`Unsupported paint type: ${paintType}`);\n }\n }\n isModifyingCurrentTransform() {\n return false;\n }\n getPattern(ctx, owner, inverse, pathType, opIdx) {\n let matrix = inverse;\n if (pathType !== PathType.SHADING) {\n matrix = Util.transform(matrix, owner.baseTransform);\n if (this.matrix) {\n matrix = Util.transform(matrix, this.matrix);\n }\n }\n const temporaryPatternCanvas = this.createPatternCanvas(owner, opIdx);\n let domMatrix = new DOMMatrix(matrix);\n domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);\n domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);\n const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");\n pattern.setTransform(domMatrix);\n return pattern;\n }\n}\n\n;// ./src/shared/image_utils.js\n/* unused harmony import specifier */ var image_utils_ImageKind;\n/* unused harmony import specifier */ var image_utils_FeatureTest;\n\n\n\n\n\nfunction convertToRGBA(params) {\n switch (params.kind) {\n case image_utils_ImageKind.GRAYSCALE_1BPP:\n return convertBlackAndWhiteToRGBA(params);\n case image_utils_ImageKind.RGB_24BPP:\n return convertRGBToRGBA(params);\n }\n return null;\n}\nfunction convertBlackAndWhiteToRGBA({\n src,\n srcPos = 0,\n dest,\n width,\n height,\n nonBlackColor = 0xffffffff,\n inverseDecode = false\n}) {\n const black = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;\n const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];\n const widthInSource = width >> 3;\n const widthRemainder = width & 7;\n const xorMask = zeroMapping ^ oneMapping;\n const srcLength = src.length;\n dest = new Uint32Array(dest.buffer);\n let destPos = 0;\n for (let i = 0; i < height; ++i) {\n for (const max = srcPos + widthInSource; srcPos < max; ++srcPos, destPos += 8) {\n const elem = src[srcPos];\n dest[destPos] = zeroMapping ^ -(elem >> 7 & 1) & xorMask;\n dest[destPos + 1] = zeroMapping ^ -(elem >> 6 & 1) & xorMask;\n dest[destPos + 2] = zeroMapping ^ -(elem >> 5 & 1) & xorMask;\n dest[destPos + 3] = zeroMapping ^ -(elem >> 4 & 1) & xorMask;\n dest[destPos + 4] = zeroMapping ^ -(elem >> 3 & 1) & xorMask;\n dest[destPos + 5] = zeroMapping ^ -(elem >> 2 & 1) & xorMask;\n dest[destPos + 6] = zeroMapping ^ -(elem >> 1 & 1) & xorMask;\n dest[destPos + 7] = zeroMapping ^ -(elem & 1) & xorMask;\n }\n if (widthRemainder === 0) {\n continue;\n }\n const elem = srcPos < srcLength ? src[srcPos++] : 255;\n for (let j = 0; j < widthRemainder; ++j, ++destPos) {\n dest[destPos] = zeroMapping ^ -(elem >> 7 - j & 1) & xorMask;\n }\n }\n return {\n srcPos,\n destPos\n };\n}\nfunction convertRGBToRGBA({\n src,\n srcPos = 0,\n dest,\n destPos = 0,\n width,\n height\n}) {\n let i = 0;\n const len = width * height * 3;\n const len32 = len >> 2;\n const src32 = new Uint32Array(src.buffer, srcPos, len32);\n const alphaMask = image_utils_FeatureTest.isLittleEndian ? 0xff000000 : 0xff;\n if (image_utils_FeatureTest.isLittleEndian) {\n for (; i < len32 - 2; i += 3, destPos += 4) {\n const s1 = src32[i],\n s2 = src32[i + 1],\n s3 = src32[i + 2];\n dest[destPos] = s1 | alphaMask;\n dest[destPos + 1] = s1 >>> 24 | s2 << 8 | alphaMask;\n dest[destPos + 2] = s2 >>> 16 | s3 << 16 | alphaMask;\n dest[destPos + 3] = s3 >>> 8 | alphaMask;\n }\n for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) {\n dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | alphaMask;\n }\n } else {\n for (; i < len32 - 2; i += 3, destPos += 4) {\n const s1 = src32[i],\n s2 = src32[i + 1],\n s3 = src32[i + 2];\n dest[destPos] = s1 | alphaMask;\n dest[destPos + 1] = s1 << 24 | s2 >>> 8 | alphaMask;\n dest[destPos + 2] = s2 << 16 | s3 >>> 16 | alphaMask;\n dest[destPos + 3] = s3 << 8 | alphaMask;\n }\n for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) {\n dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | alphaMask;\n }\n }\n return {\n srcPos: srcPos + len,\n destPos\n };\n}\nfunction grayToRGBA(src, dest) {\n if (image_utils_FeatureTest.isLittleEndian) {\n for (let i = 0, ii = src.length; i < ii; i++) {\n dest[i] = src[i] * 0x10101 | 0xff000000;\n }\n } else {\n for (let i = 0, ii = src.length; i < ii; i++) {\n dest[i] = src[i] * 0x1010100 | 0x000000ff;\n }\n }\n}\n\n;// ./src/display/canvas.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst MIN_FONT_SIZE = 16;\nconst MAX_FONT_SIZE = 100;\nconst EXECUTION_TIME = 15;\nconst EXECUTION_STEPS = 10;\nconst FULL_CHUNK_HEIGHT = 16;\nconst SCALE_MATRIX = new DOMMatrix();\nconst XY = new Float32Array(2);\nconst MIN_MAX_INIT = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);\nfunction mirrorContextOperations(ctx, destCtx) {\n if (ctx._removeMirroring) {\n throw new Error("Context is already forwarding operations.");\n }\n ctx.__originalSave = ctx.save;\n ctx.__originalRestore = ctx.restore;\n ctx.__originalRotate = ctx.rotate;\n ctx.__originalScale = ctx.scale;\n ctx.__originalTranslate = ctx.translate;\n ctx.__originalTransform = ctx.transform;\n ctx.__originalSetTransform = ctx.setTransform;\n ctx.__originalResetTransform = ctx.resetTransform;\n ctx.__originalClip = ctx.clip;\n ctx.__originalMoveTo = ctx.moveTo;\n ctx.__originalLineTo = ctx.lineTo;\n ctx.__originalBezierCurveTo = ctx.bezierCurveTo;\n ctx.__originalRect = ctx.rect;\n ctx.__originalClosePath = ctx.closePath;\n ctx.__originalBeginPath = ctx.beginPath;\n ctx._removeMirroring = () => {\n ctx.save = ctx.__originalSave;\n ctx.restore = ctx.__originalRestore;\n ctx.rotate = ctx.__originalRotate;\n ctx.scale = ctx.__originalScale;\n ctx.translate = ctx.__originalTranslate;\n ctx.transform = ctx.__originalTransform;\n ctx.setTransform = ctx.__originalSetTransform;\n ctx.resetTransform = ctx.__originalResetTransform;\n ctx.clip = ctx.__originalClip;\n ctx.moveTo = ctx.__originalMoveTo;\n ctx.lineTo = ctx.__originalLineTo;\n ctx.bezierCurveTo = ctx.__originalBezierCurveTo;\n ctx.rect = ctx.__originalRect;\n ctx.closePath = ctx.__originalClosePath;\n ctx.beginPath = ctx.__originalBeginPath;\n delete ctx._removeMirroring;\n };\n ctx.save = function () {\n destCtx.save();\n this.__originalSave();\n };\n ctx.restore = function () {\n destCtx.restore();\n this.__originalRestore();\n };\n ctx.translate = function (x, y) {\n destCtx.translate(x, y);\n this.__originalTranslate(x, y);\n };\n ctx.scale = function (x, y) {\n destCtx.scale(x, y);\n this.__originalScale(x, y);\n };\n ctx.transform = function (a, b, c, d, e, f) {\n destCtx.transform(a, b, c, d, e, f);\n this.__originalTransform(a, b, c, d, e, f);\n };\n ctx.setTransform = function (a, b, c, d, e, f) {\n destCtx.setTransform(a, b, c, d, e, f);\n this.__originalSetTransform(a, b, c, d, e, f);\n };\n ctx.resetTransform = function () {\n destCtx.resetTransform();\n this.__originalResetTransform();\n };\n ctx.rotate = function (angle) {\n destCtx.rotate(angle);\n this.__originalRotate(angle);\n };\n ctx.clip = function (rule) {\n destCtx.clip(rule);\n this.__originalClip(rule);\n };\n ctx.moveTo = function (x, y) {\n destCtx.moveTo(x, y);\n this.__originalMoveTo(x, y);\n };\n ctx.lineTo = function (x, y) {\n destCtx.lineTo(x, y);\n this.__originalLineTo(x, y);\n };\n ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {\n destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);\n this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);\n };\n ctx.rect = function (x, y, width, height) {\n destCtx.rect(x, y, width, height);\n this.__originalRect(x, y, width, height);\n };\n ctx.closePath = function () {\n destCtx.closePath();\n this.__originalClosePath();\n };\n ctx.beginPath = function () {\n destCtx.beginPath();\n this.__originalBeginPath();\n };\n}\nclass CachedCanvases {\n constructor(canvasFactory) {\n this.canvasFactory = canvasFactory;\n this.cache = Object.create(null);\n }\n getCanvas(id, width, height) {\n let canvasEntry;\n if (this.cache[id] !== undefined) {\n canvasEntry = this.cache[id];\n this.canvasFactory.reset(canvasEntry, width, height);\n } else {\n canvasEntry = this.canvasFactory.create(width, height);\n this.cache[id] = canvasEntry;\n }\n return canvasEntry;\n }\n delete(id) {\n delete this.cache[id];\n }\n clear() {\n for (const id in this.cache) {\n const canvasEntry = this.cache[id];\n this.canvasFactory.destroy(canvasEntry);\n delete this.cache[id];\n }\n }\n}\nfunction drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {\n const [a, b, c, d, tx, ty] = getCurrentTransform(ctx);\n if (b === 0 && c === 0) {\n const tlX = destX * a + tx;\n const rTlX = Math.round(tlX);\n const tlY = destY * d + ty;\n const rTlY = Math.round(tlY);\n const brX = (destX + destW) * a + tx;\n const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;\n const brY = (destY + destH) * d + ty;\n const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;\n ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);\n ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);\n ctx.setTransform(a, b, c, d, tx, ty);\n return [rWidth, rHeight];\n }\n if (a === 0 && d === 0) {\n const tlX = destY * c + tx;\n const rTlX = Math.round(tlX);\n const tlY = destX * b + ty;\n const rTlY = Math.round(tlY);\n const brX = (destY + destH) * c + tx;\n const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;\n const brY = (destX + destW) * b + ty;\n const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;\n ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);\n ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);\n ctx.setTransform(a, b, c, d, tx, ty);\n return [rHeight, rWidth];\n }\n ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);\n const scaleX = Math.hypot(a, b);\n const scaleY = Math.hypot(c, d);\n return [scaleX * destW, scaleY * destH];\n}\nclass CanvasExtraState {\n alphaIsShape = false;\n fontSize = 0;\n fontSizeScale = 1;\n textMatrix = null;\n textMatrixScale = 1;\n fontMatrix = FONT_IDENTITY_MATRIX;\n leading = 0;\n x = 0;\n y = 0;\n lineX = 0;\n lineY = 0;\n charSpacing = 0;\n wordSpacing = 0;\n textHScale = 1;\n textRenderingMode = TextRenderingMode.FILL;\n textRise = 0;\n fillColor = "#000000";\n strokeColor = "#000000";\n patternFill = false;\n patternStroke = false;\n fillAlpha = 1;\n strokeAlpha = 1;\n lineWidth = 1;\n activeSMask = null;\n transferMaps = "none";\n constructor(width, height, preInit) {\n preInit?.(this);\n this.clipBox = new Float32Array([0, 0, width, height]);\n this.minMax = MIN_MAX_INIT.slice();\n }\n clone() {\n const clone = Object.create(this);\n clone.clipBox = this.clipBox.slice();\n clone.minMax = this.minMax.slice();\n return clone;\n }\n getPathBoundingBox(pathType = PathType.FILL, transform = null) {\n const box = this.minMax.slice();\n if (pathType === PathType.STROKE) {\n if (!transform) {\n unreachable("Stroke bounding box must include transform.");\n }\n Util.singularValueDecompose2dScale(transform, XY);\n const xStrokePad = XY[0] * this.lineWidth / 2;\n const yStrokePad = XY[1] * this.lineWidth / 2;\n box[0] -= xStrokePad;\n box[1] -= yStrokePad;\n box[2] += xStrokePad;\n box[3] += yStrokePad;\n }\n return box;\n }\n updateClipFromPath() {\n const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());\n this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);\n }\n isEmptyClip() {\n return this.minMax[0] === Infinity;\n }\n startNewPathAndClipBox(box) {\n this.clipBox.set(box, 0);\n this.minMax.set(MIN_MAX_INIT, 0);\n }\n getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {\n return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));\n }\n}\nfunction putBinaryImageData(ctx, imgData) {\n if (imgData instanceof ImageData) {\n ctx.putImageData(imgData, 0, 0);\n return;\n }\n const height = imgData.height,\n width = imgData.width;\n const partialChunkHeight = height % FULL_CHUNK_HEIGHT;\n const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;\n const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;\n const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);\n let srcPos = 0,\n destPos;\n const src = imgData.data;\n const dest = chunkImgData.data;\n let i, j, thisChunkHeight, elemsInThisChunk;\n if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {\n const srcLength = src.byteLength;\n const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);\n const dest32DataLength = dest32.length;\n const fullSrcDiff = width + 7 >> 3;\n const white = 0xffffffff;\n const black = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;\n for (i = 0; i < totalChunks; i++) {\n thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;\n destPos = 0;\n for (j = 0; j < thisChunkHeight; j++) {\n const srcDiff = srcLength - srcPos;\n let k = 0;\n const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;\n const kEndUnrolled = kEnd & ~7;\n let mask = 0;\n let srcByte = 0;\n for (; k < kEndUnrolled; k += 8) {\n srcByte = src[srcPos++];\n dest32[destPos++] = srcByte & 128 ? white : black;\n dest32[destPos++] = srcByte & 64 ? white : black;\n dest32[destPos++] = srcByte & 32 ? white : black;\n dest32[destPos++] = srcByte & 16 ? white : black;\n dest32[destPos++] = srcByte & 8 ? white : black;\n dest32[destPos++] = srcByte & 4 ? white : black;\n dest32[destPos++] = srcByte & 2 ? white : black;\n dest32[destPos++] = srcByte & 1 ? white : black;\n }\n for (; k < kEnd; k++) {\n if (mask === 0) {\n srcByte = src[srcPos++];\n mask = 128;\n }\n dest32[destPos++] = srcByte & mask ? white : black;\n mask >>= 1;\n }\n }\n while (destPos < dest32DataLength) {\n dest32[destPos++] = 0;\n }\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n } else if (imgData.kind === ImageKind.RGBA_32BPP) {\n j = 0;\n elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;\n for (i = 0; i < fullChunks; i++) {\n dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));\n srcPos += elemsInThisChunk;\n ctx.putImageData(chunkImgData, 0, j);\n j += FULL_CHUNK_HEIGHT;\n }\n if (i < totalChunks) {\n elemsInThisChunk = width * partialChunkHeight * 4;\n dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));\n ctx.putImageData(chunkImgData, 0, j);\n }\n } else if (imgData.kind === ImageKind.RGB_24BPP) {\n thisChunkHeight = FULL_CHUNK_HEIGHT;\n elemsInThisChunk = width * thisChunkHeight;\n for (i = 0; i < totalChunks; i++) {\n if (i >= fullChunks) {\n thisChunkHeight = partialChunkHeight;\n elemsInThisChunk = width * thisChunkHeight;\n }\n destPos = 0;\n for (j = elemsInThisChunk; j--;) {\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = 255;\n }\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n } else {\n throw new Error(`bad image kind: ${imgData.kind}`);\n }\n}\nfunction putBinaryImageMask(ctx, imgData) {\n if (imgData.bitmap) {\n ctx.drawImage(imgData.bitmap, 0, 0);\n return;\n }\n const height = imgData.height,\n width = imgData.width;\n const partialChunkHeight = height % FULL_CHUNK_HEIGHT;\n const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;\n const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;\n const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);\n let srcPos = 0;\n const src = imgData.data;\n const dest = chunkImgData.data;\n for (let i = 0; i < totalChunks; i++) {\n const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;\n ({\n srcPos\n } = convertBlackAndWhiteToRGBA({\n src,\n srcPos,\n dest,\n width,\n height: thisChunkHeight,\n nonBlackColor: 0\n }));\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n}\nfunction copyCtxState(sourceCtx, destCtx) {\n const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];\n for (const property of properties) {\n if (sourceCtx[property] !== undefined) {\n destCtx[property] = sourceCtx[property];\n }\n }\n if (sourceCtx.setLineDash !== undefined) {\n destCtx.setLineDash(sourceCtx.getLineDash());\n destCtx.lineDashOffset = sourceCtx.lineDashOffset;\n }\n}\nfunction resetCtxToDefault(ctx) {\n ctx.strokeStyle = ctx.fillStyle = "#000000";\n ctx.fillRule = "nonzero";\n ctx.globalAlpha = 1;\n ctx.lineWidth = 1;\n ctx.lineCap = "butt";\n ctx.lineJoin = "miter";\n ctx.miterLimit = 10;\n ctx.globalCompositeOperation = "source-over";\n ctx.font = "10px sans-serif";\n if (ctx.setLineDash !== undefined) {\n ctx.setLineDash([]);\n ctx.lineDashOffset = 0;\n }\n const {\n filter\n } = ctx;\n if (filter !== "none" && filter !== "") {\n ctx.filter = "none";\n }\n}\nfunction getImageSmoothingEnabled(transform, interpolate) {\n if (interpolate) {\n return true;\n }\n Util.singularValueDecompose2dScale(transform, XY);\n const actualScale = Math.fround(OutputScale.pixelRatio * PixelsPerInch.PDF_TO_CSS_UNITS);\n return XY[0] <= actualScale && XY[1] <= actualScale;\n}\nconst LINE_CAP_STYLES = ["butt", "round", "square"];\nconst LINE_JOIN_STYLES = ["miter", "round", "bevel"];\nconst NORMAL_CLIP = {};\nconst EO_CLIP = {};\nclass CanvasGraphics {\n constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {\n optionalContentConfig,\n markedContentStack = null\n }, annotationCanvasMap, pageColors, dependencyTracker) {\n this.ctx = canvasCtx;\n this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);\n this.stateStack = [];\n this.pendingClip = null;\n this.pendingEOFill = false;\n this.commonObjs = commonObjs;\n this.objs = objs;\n this.canvasFactory = canvasFactory;\n this.filterFactory = filterFactory;\n this.groupStack = [];\n this.baseTransform = null;\n this.baseTransformStack = [];\n this.groupLevel = 0;\n this.smaskStack = [];\n this.smaskCounter = 0;\n this.tempSMask = null;\n this.suspendedCtx = null;\n this.contentVisible = true;\n this.markedContentStack = markedContentStack || [];\n this.optionalContentConfig = optionalContentConfig;\n this.cachedCanvases = new CachedCanvases(this.canvasFactory);\n this.cachedPatterns = new Map();\n this.annotationCanvasMap = annotationCanvasMap;\n this.viewportScale = 1;\n this.outputScaleX = 1;\n this.outputScaleY = 1;\n this.pageColors = pageColors;\n this._cachedScaleForStroking = [-1, 0];\n this._cachedGetSinglePixelWidth = null;\n this._cachedBitmapsMap = new Map();\n this.dependencyTracker = dependencyTracker ?? null;\n }\n getObject(opIdx, data, fallback = null) {\n if (typeof data === "string") {\n this.dependencyTracker?.recordNamedDependency(opIdx, data);\n return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);\n }\n return fallback;\n }\n beginDrawing({\n transform,\n viewport,\n transparency = false,\n background = null\n }) {\n const width = this.ctx.canvas.width;\n const height = this.ctx.canvas.height;\n const savedFillStyle = this.ctx.fillStyle;\n this.ctx.fillStyle = background || "#ffffff";\n this.ctx.fillRect(0, 0, width, height);\n this.ctx.fillStyle = savedFillStyle;\n if (transparency) {\n const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);\n this.compositeCtx = this.ctx;\n this.transparentCanvas = transparentCanvas.canvas;\n this.ctx = transparentCanvas.context;\n this.ctx.save();\n this.ctx.transform(...getCurrentTransform(this.compositeCtx));\n }\n this.ctx.save();\n resetCtxToDefault(this.ctx);\n if (transform) {\n this.ctx.transform(...transform);\n this.outputScaleX = transform[0];\n this.outputScaleY = transform[0];\n }\n this.ctx.transform(...viewport.transform);\n this.viewportScale = viewport.scale;\n this.baseTransform = getCurrentTransform(this.ctx);\n }\n executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper, operationsFilter) {\n const argsArray = operatorList.argsArray;\n const fnArray = operatorList.fnArray;\n let i = executionStartIdx || 0;\n const argsArrayLen = argsArray.length;\n if (argsArrayLen === i) {\n return i;\n }\n const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";\n const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;\n let steps = 0;\n const commonObjs = this.commonObjs;\n const objs = this.objs;\n let fnId, fnArgs;\n while (true) {\n if (stepper !== undefined && i === stepper.nextBreakPoint) {\n stepper.breakIt(i, continueCallback);\n return i;\n }\n if (!operationsFilter || operationsFilter(i)) {\n fnId = fnArray[i];\n fnArgs = argsArray[i] ?? null;\n if (fnId !== OPS.dependency) {\n if (fnArgs === null) {\n this[fnId](i);\n } else {\n this[fnId](i, ...fnArgs);\n }\n } else {\n for (const depObjId of fnArgs) {\n this.dependencyTracker?.recordNamedData(depObjId, i);\n const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;\n if (!objsPool.has(depObjId)) {\n objsPool.get(depObjId, continueCallback);\n return i;\n }\n }\n }\n }\n i++;\n if (i === argsArrayLen) {\n return i;\n }\n if (chunkOperations && ++steps > EXECUTION_STEPS) {\n if (Date.now() > endTime) {\n continueCallback();\n return i;\n }\n steps = 0;\n }\n }\n }\n #restoreInitialState() {\n while (this.stateStack.length || this.inSMaskMode) {\n this.restore();\n }\n this.current.activeSMask = null;\n this.ctx.restore();\n if (this.transparentCanvas) {\n this.ctx = this.compositeCtx;\n this.ctx.save();\n this.ctx.setTransform(1, 0, 0, 1, 0, 0);\n this.ctx.drawImage(this.transparentCanvas, 0, 0);\n this.ctx.restore();\n this.transparentCanvas = null;\n }\n }\n endDrawing() {\n this.#restoreInitialState();\n this.cachedCanvases.clear();\n this.cachedPatterns.clear();\n for (const cache of this._cachedBitmapsMap.values()) {\n for (const canvas of cache.values()) {\n if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {\n canvas.width = canvas.height = 0;\n }\n }\n cache.clear();\n }\n this._cachedBitmapsMap.clear();\n this.#drawFilter();\n }\n #drawFilter() {\n if (this.pageColors) {\n const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background);\n if (hcmFilterId !== "none") {\n const savedFilter = this.ctx.filter;\n this.ctx.filter = hcmFilterId;\n this.ctx.drawImage(this.ctx.canvas, 0, 0);\n this.ctx.filter = savedFilter;\n }\n }\n }\n _scaleImage(img, inverseTransform) {\n const width = img.width ?? img.displayWidth;\n const height = img.height ?? img.displayHeight;\n let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);\n let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);\n let paintWidth = width,\n paintHeight = height;\n let tmpCanvasId = "prescale1";\n let tmpCanvas, tmpCtx;\n while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {\n let newWidth = paintWidth,\n newHeight = paintHeight;\n if (widthScale > 2 && paintWidth > 1) {\n newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);\n widthScale /= paintWidth / newWidth;\n }\n if (heightScale > 2 && paintHeight > 1) {\n newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;\n heightScale /= paintHeight / newHeight;\n }\n tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);\n tmpCtx = tmpCanvas.context;\n tmpCtx.clearRect(0, 0, newWidth, newHeight);\n tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);\n img = tmpCanvas.canvas;\n paintWidth = newWidth;\n paintHeight = newHeight;\n tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";\n }\n return {\n img,\n paintWidth,\n paintHeight\n };\n }\n _createMaskCanvas(opIdx, img) {\n const ctx = this.ctx;\n const {\n width,\n height\n } = img;\n const fillColor = this.current.fillColor;\n const isPatternFill = this.current.patternFill;\n const currentTransform = getCurrentTransform(ctx);\n let cache, cacheKey, scaled, maskCanvas;\n if ((img.bitmap || img.data) && img.count > 1) {\n const mainKey = img.bitmap || img.data.buffer;\n cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);\n cache = this._cachedBitmapsMap.getOrInsertComputed(mainKey, makeMap);\n const cachedImage = cache.get(cacheKey);\n if (cachedImage && !isPatternFill) {\n const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);\n const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);\n this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill);\n return {\n canvas: cachedImage,\n offsetX,\n offsetY\n };\n }\n scaled = cachedImage;\n }\n if (!scaled) {\n maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);\n putBinaryImageMask(maskCanvas.context, img);\n }\n let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);\n maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);\n const minMax = MIN_MAX_INIT.slice();\n Util.axialAlignedBoundingBox([0, 0, width, height], maskToCanvas, minMax);\n const [minX, minY, maxX, maxY] = minMax;\n const drawnWidth = Math.round(maxX - minX) || 1;\n const drawnHeight = Math.round(maxY - minY) || 1;\n const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);\n const fillCtx = fillCanvas.context;\n const offsetX = minX;\n const offsetY = minY;\n fillCtx.translate(-offsetX, -offsetY);\n fillCtx.transform(...maskToCanvas);\n if (!scaled) {\n scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx));\n scaled = scaled.img;\n if (cache && isPatternFill) {\n cache.set(cacheKey, scaled);\n }\n }\n fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate);\n drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);\n fillCtx.globalCompositeOperation = "source-in";\n const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);\n fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL, opIdx) : fillColor;\n fillCtx.fillRect(0, 0, width, height);\n if (cache && !isPatternFill) {\n this.cachedCanvases.delete("fillCanvas");\n cache.set(cacheKey, fillCanvas.canvas);\n }\n this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill);\n return {\n canvas: fillCanvas.canvas,\n offsetX: Math.round(offsetX),\n offsetY: Math.round(offsetY)\n };\n }\n setLineWidth(opIdx, width) {\n this.dependencyTracker?.recordSimpleData("lineWidth", opIdx);\n if (width !== this.current.lineWidth) {\n this._cachedScaleForStroking[0] = -1;\n }\n this.current.lineWidth = width;\n this.ctx.lineWidth = width;\n }\n setLineCap(opIdx, style) {\n this.dependencyTracker?.recordSimpleData("lineCap", opIdx);\n this.ctx.lineCap = LINE_CAP_STYLES[style];\n }\n setLineJoin(opIdx, style) {\n this.dependencyTracker?.recordSimpleData("lineJoin", opIdx);\n this.ctx.lineJoin = LINE_JOIN_STYLES[style];\n }\n setMiterLimit(opIdx, limit) {\n this.dependencyTracker?.recordSimpleData("miterLimit", opIdx);\n this.ctx.miterLimit = limit;\n }\n setDash(opIdx, dashArray, dashPhase) {\n this.dependencyTracker?.recordSimpleData("dash", opIdx);\n const ctx = this.ctx;\n if (ctx.setLineDash !== undefined) {\n ctx.setLineDash(dashArray);\n ctx.lineDashOffset = dashPhase;\n }\n }\n setRenderingIntent(opIdx, intent) {}\n setFlatness(opIdx, flatness) {}\n setGState(opIdx, states) {\n for (const [key, value] of states) {\n switch (key) {\n case "LW":\n this.setLineWidth(opIdx, value);\n break;\n case "LC":\n this.setLineCap(opIdx, value);\n break;\n case "LJ":\n this.setLineJoin(opIdx, value);\n break;\n case "ML":\n this.setMiterLimit(opIdx, value);\n break;\n case "D":\n this.setDash(opIdx, value[0], value[1]);\n break;\n case "RI":\n this.setRenderingIntent(opIdx, value);\n break;\n case "FL":\n this.setFlatness(opIdx, value);\n break;\n case "Font":\n this.setFont(opIdx, value[0], value[1]);\n break;\n case "CA":\n this.dependencyTracker?.recordSimpleData("strokeAlpha", opIdx);\n this.current.strokeAlpha = value;\n break;\n case "ca":\n this.dependencyTracker?.recordSimpleData("fillAlpha", opIdx);\n this.ctx.globalAlpha = this.current.fillAlpha = value;\n break;\n case "BM":\n this.dependencyTracker?.recordSimpleData("globalCompositeOperation", opIdx);\n this.ctx.globalCompositeOperation = value;\n break;\n case "SMask":\n this.dependencyTracker?.recordSimpleData("SMask", opIdx);\n this.current.activeSMask = value ? this.tempSMask : null;\n this.tempSMask = null;\n this.checkSMaskState();\n break;\n case "TR":\n this.dependencyTracker?.recordSimpleData("filter", opIdx);\n this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);\n break;\n }\n }\n }\n get inSMaskMode() {\n return !!this.suspendedCtx;\n }\n checkSMaskState() {\n const inSMaskMode = this.inSMaskMode;\n if (this.current.activeSMask && !inSMaskMode) {\n this.beginSMaskMode();\n } else if (!this.current.activeSMask && inSMaskMode) {\n this.endSMaskMode();\n }\n }\n beginSMaskMode(opIdx) {\n if (this.inSMaskMode) {\n throw new Error("beginSMaskMode called while already in smask mode");\n }\n const drawnWidth = this.ctx.canvas.width;\n const drawnHeight = this.ctx.canvas.height;\n const cacheId = "smaskGroupAt" + this.groupLevel;\n const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);\n this.suspendedCtx = this.ctx;\n const ctx = this.ctx = scratchCanvas.context;\n ctx.setTransform(this.suspendedCtx.getTransform());\n copyCtxState(this.suspendedCtx, ctx);\n mirrorContextOperations(ctx, this.suspendedCtx);\n this.setGState(opIdx, [["BM", "source-over"]]);\n }\n endSMaskMode() {\n if (!this.inSMaskMode) {\n throw new Error("endSMaskMode called while not in smask mode");\n }\n this.ctx._removeMirroring();\n copyCtxState(this.ctx, this.suspendedCtx);\n this.ctx = this.suspendedCtx;\n this.suspendedCtx = null;\n }\n compose(dirtyBox) {\n if (!this.current.activeSMask) {\n return;\n }\n if (!dirtyBox) {\n dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];\n } else {\n dirtyBox[0] = Math.floor(dirtyBox[0]);\n dirtyBox[1] = Math.floor(dirtyBox[1]);\n dirtyBox[2] = Math.ceil(dirtyBox[2]);\n dirtyBox[3] = Math.ceil(dirtyBox[3]);\n }\n const smask = this.current.activeSMask;\n const suspendedCtx = this.suspendedCtx;\n this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);\n this.ctx.save();\n this.ctx.setTransform(1, 0, 0, 1, 0, 0);\n this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);\n this.ctx.restore();\n }\n composeSMask(ctx, smask, layerCtx, layerBox) {\n const layerOffsetX = layerBox[0];\n const layerOffsetY = layerBox[1];\n const layerWidth = layerBox[2] - layerOffsetX;\n const layerHeight = layerBox[3] - layerOffsetY;\n if (layerWidth === 0 || layerHeight === 0) {\n return;\n }\n this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);\n ctx.save();\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = "source-over";\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.drawImage(layerCtx.canvas, 0, 0);\n ctx.restore();\n }\n genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {\n let maskCanvas = maskCtx.canvas;\n let maskX = layerOffsetX - maskOffsetX;\n let maskY = layerOffsetY - maskOffsetY;\n if (backdrop) {\n if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) {\n const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height);\n const ctx = canvas.context;\n ctx.drawImage(maskCanvas, -maskX, -maskY);\n ctx.globalCompositeOperation = "destination-atop";\n ctx.fillStyle = backdrop;\n ctx.fillRect(0, 0, width, height);\n ctx.globalCompositeOperation = "source-over";\n maskCanvas = canvas.canvas;\n maskX = maskY = 0;\n } else {\n maskCtx.save();\n maskCtx.globalAlpha = 1;\n maskCtx.setTransform(1, 0, 0, 1, 0, 0);\n const clip = new Path2D();\n clip.rect(maskX, maskY, width, height);\n maskCtx.clip(clip);\n maskCtx.globalCompositeOperation = "destination-atop";\n maskCtx.fillStyle = backdrop;\n maskCtx.fillRect(maskX, maskY, width, height);\n maskCtx.restore();\n }\n }\n layerCtx.save();\n layerCtx.globalAlpha = 1;\n layerCtx.setTransform(1, 0, 0, 1, 0, 0);\n if (subtype === "Alpha" && transferMap) {\n layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);\n } else if (subtype === "Luminosity") {\n layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);\n }\n const clip = new Path2D();\n clip.rect(layerOffsetX, layerOffsetY, width, height);\n layerCtx.clip(clip);\n layerCtx.globalCompositeOperation = "destination-in";\n layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height);\n layerCtx.restore();\n }\n save(opIdx) {\n if (this.inSMaskMode) {\n copyCtxState(this.ctx, this.suspendedCtx);\n }\n this.ctx.save();\n const old = this.current;\n this.stateStack.push(old);\n this.current = old.clone();\n this.dependencyTracker?.save(opIdx);\n }\n restore(opIdx) {\n this.dependencyTracker?.restore(opIdx);\n if (this.stateStack.length === 0) {\n if (this.inSMaskMode) {\n this.endSMaskMode();\n }\n return;\n }\n this.current = this.stateStack.pop();\n this.ctx.restore();\n if (this.inSMaskMode) {\n copyCtxState(this.suspendedCtx, this.ctx);\n }\n this.checkSMaskState();\n this.pendingClip = null;\n this._cachedScaleForStroking[0] = -1;\n this._cachedGetSinglePixelWidth = null;\n }\n transform(opIdx, a, b, c, d, e, f) {\n this.dependencyTracker?.recordIncrementalData("transform", opIdx);\n this.ctx.transform(a, b, c, d, e, f);\n this._cachedScaleForStroking[0] = -1;\n this._cachedGetSinglePixelWidth = null;\n }\n constructPath(opIdx, op, data, minMax) {\n let [path] = data;\n if (!minMax) {\n path ||= data[0] = new Path2D();\n this[op](opIdx, path);\n return;\n }\n if (this.dependencyTracker !== null) {\n const outerExtraSize = op === OPS.stroke ? this.current.lineWidth / 2 : 0;\n this.dependencyTracker.resetBBox(opIdx).recordBBox(opIdx, this.ctx, minMax[0] - outerExtraSize, minMax[2] + outerExtraSize, minMax[1] - outerExtraSize, minMax[3] + outerExtraSize).recordDependencies(opIdx, ["transform"]);\n }\n if (!(path instanceof Path2D)) {\n path = data[0] = makePathFromDrawOPS(path);\n }\n Util.axialAlignedBoundingBox(minMax, getCurrentTransform(this.ctx), this.current.minMax);\n this[op](opIdx, path);\n this._pathStartIdx = opIdx;\n }\n closePath(opIdx) {\n this.ctx.closePath();\n }\n stroke(opIdx, path, consumePath = true) {\n const ctx = this.ctx;\n const strokeColor = this.current.strokeColor;\n ctx.globalAlpha = this.current.strokeAlpha;\n if (this.contentVisible) {\n if (typeof strokeColor === "object" && strokeColor?.getPattern) {\n const baseTransform = strokeColor.isModifyingCurrentTransform() ? ctx.getTransform() : null;\n ctx.save();\n ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx);\n if (baseTransform) {\n const newPath = new Path2D();\n newPath.addPath(path, ctx.getTransform().invertSelf().multiplySelf(baseTransform));\n path = newPath;\n }\n this.rescaleAndStroke(path, false);\n ctx.restore();\n } else {\n this.rescaleAndStroke(path, true);\n }\n }\n this.dependencyTracker?.recordDependencies(opIdx, Dependencies.stroke);\n if (consumePath) {\n this.consumePath(opIdx, path, this.current.getClippedPathBoundingBox(PathType.STROKE, getCurrentTransform(this.ctx)));\n }\n ctx.globalAlpha = this.current.fillAlpha;\n }\n closeStroke(opIdx, path) {\n this.stroke(opIdx, path);\n }\n fill(opIdx, path, consumePath = true) {\n const ctx = this.ctx;\n const fillColor = this.current.fillColor;\n const isPatternFill = this.current.patternFill;\n let needRestore = false;\n if (isPatternFill) {\n const baseTransform = fillColor.isModifyingCurrentTransform() ? ctx.getTransform() : null;\n this.dependencyTracker?.save(opIdx);\n ctx.save();\n ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx);\n if (baseTransform) {\n const newPath = new Path2D();\n newPath.addPath(path, ctx.getTransform().invertSelf().multiplySelf(baseTransform));\n path = newPath;\n }\n needRestore = true;\n }\n const intersect = this.current.getClippedPathBoundingBox();\n if (this.contentVisible && intersect !== null) {\n if (this.pendingEOFill) {\n ctx.fill(path, "evenodd");\n this.pendingEOFill = false;\n } else {\n ctx.fill(path);\n }\n }\n this.dependencyTracker?.recordDependencies(opIdx, Dependencies.fill);\n if (needRestore) {\n ctx.restore();\n this.dependencyTracker?.restore(opIdx);\n }\n if (consumePath) {\n this.consumePath(opIdx, path, intersect);\n }\n }\n eoFill(opIdx, path) {\n this.pendingEOFill = true;\n this.fill(opIdx, path);\n }\n fillStroke(opIdx, path) {\n this.fill(opIdx, path, false);\n this.stroke(opIdx, path, false);\n this.consumePath(opIdx, path);\n }\n eoFillStroke(opIdx, path) {\n this.pendingEOFill = true;\n this.fillStroke(opIdx, path);\n }\n closeFillStroke(opIdx, path) {\n this.fillStroke(opIdx, path);\n }\n closeEOFillStroke(opIdx, path) {\n this.pendingEOFill = true;\n this.fillStroke(opIdx, path);\n }\n endPath(opIdx, path) {\n this.consumePath(opIdx, path);\n }\n rawFillPath(opIdx, path) {\n this.ctx.fill(path);\n this.dependencyTracker?.recordDependencies(opIdx, Dependencies.rawFillPath).recordOperation(opIdx);\n }\n clip(opIdx) {\n this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx);\n this.pendingClip = NORMAL_CLIP;\n }\n eoClip(opIdx) {\n this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx);\n this.pendingClip = EO_CLIP;\n }\n beginText(opIdx) {\n this.current.textMatrix = null;\n this.current.textMatrixScale = 1;\n this.current.x = this.current.lineX = 0;\n this.current.y = this.current.lineY = 0;\n this.dependencyTracker?.recordOpenMarker(opIdx).resetIncrementalData("sameLineText").resetIncrementalData("moveText", opIdx);\n }\n endText(opIdx) {\n const paths = this.pendingTextPaths;\n const ctx = this.ctx;\n if (this.dependencyTracker) {\n const {\n dependencyTracker\n } = this;\n if (paths !== undefined) {\n dependencyTracker.recordFutureForcedDependency("textClip", dependencyTracker.getOpenMarker()).recordFutureForcedDependency("textClip", opIdx);\n }\n dependencyTracker.recordCloseMarker(opIdx);\n }\n if (paths !== undefined) {\n const newPath = new Path2D();\n const invTransf = ctx.getTransform().invertSelf();\n for (const {\n transform,\n x,\n y,\n fontSize,\n path\n } of paths) {\n if (!path) {\n continue;\n }\n newPath.addPath(path, new DOMMatrix(transform).preMultiplySelf(invTransf).translate(x, y).scale(fontSize, -fontSize));\n }\n ctx.clip(newPath);\n }\n delete this.pendingTextPaths;\n }\n setCharSpacing(opIdx, spacing) {\n this.dependencyTracker?.recordSimpleData("charSpacing", opIdx);\n this.current.charSpacing = spacing;\n }\n setWordSpacing(opIdx, spacing) {\n this.dependencyTracker?.recordSimpleData("wordSpacing", opIdx);\n this.current.wordSpacing = spacing;\n }\n setHScale(opIdx, scale) {\n this.dependencyTracker?.recordSimpleData("hScale", opIdx);\n this.current.textHScale = scale / 100;\n }\n setLeading(opIdx, leading) {\n this.dependencyTracker?.recordSimpleData("leading", opIdx);\n this.current.leading = -leading;\n }\n setFont(opIdx, fontRefName, size) {\n this.dependencyTracker?.recordSimpleData("font", opIdx).recordSimpleDataFromNamed("fontObj", fontRefName, opIdx);\n const fontObj = this.commonObjs.get(fontRefName);\n const current = this.current;\n if (!fontObj) {\n throw new Error(`Can\'t find font for ${fontRefName}`);\n }\n current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;\n if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {\n warn("Invalid font matrix for font " + fontRefName);\n }\n if (size < 0) {\n size = -size;\n current.fontDirection = -1;\n } else {\n current.fontDirection = 1;\n }\n this.current.font = fontObj;\n this.current.fontSize = size;\n if (fontObj.isType3Font) {\n return;\n }\n const name = fontObj.loadedName || "sans-serif";\n const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`;\n let bold = "normal";\n if (fontObj.black) {\n bold = "900";\n } else if (fontObj.bold) {\n bold = "bold";\n }\n const italic = fontObj.italic ? "italic" : "normal";\n let browserFontSize = size;\n if (size < MIN_FONT_SIZE) {\n browserFontSize = MIN_FONT_SIZE;\n } else if (size > MAX_FONT_SIZE) {\n browserFontSize = MAX_FONT_SIZE;\n }\n this.current.fontSizeScale = size / browserFontSize;\n this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;\n }\n setTextRenderingMode(opIdx, mode) {\n this.dependencyTracker?.recordSimpleData("textRenderingMode", opIdx);\n this.current.textRenderingMode = mode;\n }\n setTextRise(opIdx, rise) {\n this.dependencyTracker?.recordSimpleData("textRise", opIdx);\n this.current.textRise = rise;\n }\n moveText(opIdx, x, y) {\n this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText", opIdx);\n this.current.x = this.current.lineX += x;\n this.current.y = this.current.lineY += y;\n }\n setLeadingMoveText(opIdx, x, y) {\n this.setLeading(opIdx, -y);\n this.moveText(opIdx, x, y);\n }\n setTextMatrix(opIdx, matrix) {\n this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix", opIdx);\n const {\n current\n } = this;\n current.textMatrix = matrix;\n current.textMatrixScale = Math.hypot(matrix[0], matrix[1]);\n current.x = current.lineX = 0;\n current.y = current.lineY = 0;\n }\n nextLine(opIdx) {\n this.moveText(opIdx, 0, this.current.leading);\n this.dependencyTracker?.recordIncrementalData("moveText", this.dependencyTracker.getSimpleIndex("leading") ?? opIdx);\n }\n #getScaledPath(path, currentTransform, transform) {\n const newPath = new Path2D();\n newPath.addPath(path, new DOMMatrix(transform).invertSelf().multiplySelf(currentTransform));\n return newPath;\n }\n paintChar(opIdx, character, x, y, patternFillTransform, patternStrokeTransform) {\n const ctx = this.ctx;\n const current = this.current;\n const font = current.font;\n const textRenderingMode = current.textRenderingMode;\n const fontSize = current.fontSize / current.fontSizeScale;\n const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;\n const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);\n const patternFill = current.patternFill && !font.missingFile;\n const patternStroke = current.patternStroke && !font.missingFile;\n let path;\n if ((font.disableFontFace || isAddToPathSet || patternFill || patternStroke) && !font.missingFile) {\n path = font.getPathGenerator(this.commonObjs, character);\n }\n if (path && (font.disableFontFace || patternFill || patternStroke)) {\n ctx.save();\n ctx.translate(x, y);\n ctx.scale(fontSize, -fontSize);\n this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font);\n let currentTransform;\n if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {\n if (patternFillTransform) {\n currentTransform = ctx.getTransform();\n ctx.setTransform(...patternFillTransform);\n const scaledPath = this.#getScaledPath(path, currentTransform, patternFillTransform);\n ctx.fill(scaledPath);\n } else {\n ctx.fill(path);\n }\n }\n if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {\n if (patternStrokeTransform) {\n currentTransform ||= ctx.getTransform();\n ctx.setTransform(...patternStrokeTransform);\n const {\n a,\n b,\n c,\n d\n } = currentTransform;\n const invPatternTransform = Util.inverseTransform(patternStrokeTransform);\n const transf = Util.transform([a, b, c, d, 0, 0], invPatternTransform);\n Util.singularValueDecompose2dScale(transf, XY);\n ctx.lineWidth *= Math.max(XY[0], XY[1]) / fontSize;\n ctx.stroke(this.#getScaledPath(path, currentTransform, patternStrokeTransform));\n } else {\n ctx.lineWidth /= fontSize;\n ctx.stroke(path);\n }\n }\n ctx.restore();\n } else {\n if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {\n ctx.fillText(character, x, y);\n this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x, y, () => ctx.measureText(character));\n }\n if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {\n if (this.dependencyTracker) {\n this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x, y, () => ctx.measureText(character)).recordDependencies(opIdx, Dependencies.stroke);\n }\n ctx.strokeText(character, x, y);\n }\n }\n if (isAddToPathSet) {\n const paths = this.pendingTextPaths ||= [];\n paths.push({\n transform: getCurrentTransform(ctx),\n x,\n y,\n fontSize,\n path\n });\n this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x, y);\n }\n }\n get isFontSubpixelAAEnabled() {\n const {\n context: ctx\n } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);\n ctx.scale(1.5, 1);\n ctx.fillText("I", 0, 10);\n const data = ctx.getImageData(0, 0, 10, 10).data;\n let enabled = false;\n for (let i = 3; i < data.length; i += 4) {\n if (data[i] > 0 && data[i] < 255) {\n enabled = true;\n break;\n }\n }\n return shadow(this, "isFontSubpixelAAEnabled", enabled);\n }\n showText(opIdx, glyphs) {\n if (this.dependencyTracker) {\n this.dependencyTracker.recordDependencies(opIdx, Dependencies.showText).resetBBox(opIdx);\n if (this.current.textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG) {\n this.dependencyTracker.recordFutureForcedDependency("textClip", opIdx).inheritPendingDependenciesAsFutureForcedDependencies();\n }\n }\n const current = this.current;\n const font = current.font;\n if (font.isType3Font) {\n this.showType3Text(opIdx, glyphs);\n this.dependencyTracker?.recordShowTextOperation(opIdx);\n return undefined;\n }\n const fontSize = current.fontSize;\n if (fontSize === 0) {\n this.dependencyTracker?.recordOperation(opIdx);\n return undefined;\n }\n const ctx = this.ctx;\n const fontSizeScale = current.fontSizeScale;\n const charSpacing = current.charSpacing;\n const wordSpacing = current.wordSpacing;\n const fontDirection = current.fontDirection;\n const textHScale = current.textHScale * fontDirection;\n const glyphsLength = glyphs.length;\n const vertical = font.vertical;\n const spacingDir = vertical ? 1 : -1;\n const defaultVMetrics = font.defaultVMetrics;\n const widthAdvanceScale = fontSize * current.fontMatrix[0];\n const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;\n ctx.save();\n if (current.textMatrix) {\n ctx.transform(...current.textMatrix);\n }\n ctx.translate(current.x, current.y + current.textRise);\n if (fontDirection > 0) {\n ctx.scale(textHScale, -1);\n } else {\n ctx.scale(textHScale, 1);\n }\n let patternFillTransform, patternStrokeTransform;\n const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;\n const needsFill = fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE;\n const needsStroke = fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE;\n if (needsFill && current.patternFill) {\n ctx.save();\n const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx);\n patternFillTransform = getCurrentTransform(ctx);\n ctx.restore();\n ctx.fillStyle = pattern;\n }\n if (needsStroke && current.patternStroke) {\n ctx.save();\n const pattern = current.strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx);\n patternStrokeTransform = getCurrentTransform(ctx);\n ctx.restore();\n ctx.strokeStyle = pattern;\n }\n let lineWidth = current.lineWidth;\n const scale = current.textMatrixScale;\n if (scale === 0 || lineWidth === 0) {\n if (needsStroke) {\n lineWidth = this.getSinglePixelWidth();\n }\n } else {\n lineWidth /= scale;\n }\n if (fontSizeScale !== 1.0) {\n ctx.scale(fontSizeScale, fontSizeScale);\n lineWidth /= fontSizeScale;\n }\n ctx.lineWidth = lineWidth;\n if (font.isInvalidPDFjsFont) {\n const chars = [];\n let width = 0;\n for (const glyph of glyphs) {\n chars.push(glyph.unicode);\n width += glyph.width;\n }\n const joinedChars = chars.join("");\n ctx.fillText(joinedChars, 0, 0);\n if (this.dependencyTracker !== null) {\n const measure = ctx.measureText(joinedChars);\n this.dependencyTracker.recordBBox(opIdx, this.ctx, -measure.actualBoundingBoxLeft, measure.actualBoundingBoxRight, -measure.actualBoundingBoxAscent, measure.actualBoundingBoxDescent).recordShowTextOperation(opIdx);\n }\n current.x += width * widthAdvanceScale * textHScale;\n ctx.restore();\n this.compose();\n return undefined;\n }\n let x = 0,\n i;\n for (i = 0; i < glyphsLength; ++i) {\n const glyph = glyphs[i];\n if (typeof glyph === "number") {\n x += spacingDir * glyph * fontSize / 1000;\n continue;\n }\n let restoreNeeded = false;\n const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;\n const character = glyph.fontChar;\n const accent = glyph.accent;\n let scaledX, scaledY;\n let width = glyph.width;\n if (vertical) {\n const vmetric = glyph.vmetric || defaultVMetrics;\n const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;\n const vy = vmetric[2] * widthAdvanceScale;\n width = vmetric ? -vmetric[0] : width;\n scaledX = vx / fontSizeScale;\n scaledY = (x + vy) / fontSizeScale;\n } else {\n scaledX = x / fontSizeScale;\n scaledY = 0;\n }\n let measure;\n if (font.remeasure && width > 0) {\n measure = ctx.measureText(character);\n const measuredWidth = measure.width * 1000 / fontSize * fontSizeScale;\n if (width < measuredWidth && this.isFontSubpixelAAEnabled) {\n const characterScaleX = width / measuredWidth;\n restoreNeeded = true;\n ctx.save();\n ctx.scale(characterScaleX, 1);\n scaledX /= characterScaleX;\n } else if (width !== measuredWidth) {\n scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;\n }\n }\n if (this.contentVisible && (glyph.isInFont || font.missingFile)) {\n if (simpleFillText && !accent) {\n ctx.fillText(character, scaledX, scaledY);\n this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, measure ? {\n bbox: null\n } : font, fontSize / fontSizeScale, scaledX, scaledY, () => measure ?? ctx.measureText(character));\n } else {\n this.paintChar(opIdx, character, scaledX, scaledY, patternFillTransform, patternStrokeTransform);\n if (accent) {\n const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;\n const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;\n this.paintChar(opIdx, accent.fontChar, scaledAccentX, scaledAccentY, patternFillTransform, patternStrokeTransform);\n }\n }\n }\n const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection;\n x += charWidth;\n if (restoreNeeded) {\n ctx.restore();\n }\n }\n if (vertical) {\n current.y -= x;\n } else {\n current.x += x * textHScale;\n }\n ctx.restore();\n this.compose();\n this.dependencyTracker?.recordShowTextOperation(opIdx);\n return undefined;\n }\n showType3Text(opIdx, glyphs) {\n const ctx = this.ctx;\n const current = this.current;\n const font = current.font;\n const fontSize = current.fontSize;\n const fontDirection = current.fontDirection;\n const spacingDir = font.vertical ? 1 : -1;\n const charSpacing = current.charSpacing;\n const wordSpacing = current.wordSpacing;\n const textHScale = current.textHScale * fontDirection;\n const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;\n const glyphsLength = glyphs.length;\n const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;\n let i, glyph, width, spacingLength;\n if (isTextInvisible || fontSize === 0) {\n return;\n }\n this._cachedScaleForStroking[0] = -1;\n this._cachedGetSinglePixelWidth = null;\n ctx.save();\n if (current.textMatrix) {\n ctx.transform(...current.textMatrix);\n }\n ctx.translate(current.x, current.y + current.textRise);\n ctx.scale(textHScale, fontDirection);\n const dependencyTracker = this.dependencyTracker;\n this.dependencyTracker = dependencyTracker ? new CanvasNestedDependencyTracker(dependencyTracker, opIdx) : null;\n for (i = 0; i < glyphsLength; ++i) {\n glyph = glyphs[i];\n if (typeof glyph === "number") {\n spacingLength = spacingDir * glyph * fontSize / 1000;\n this.ctx.translate(spacingLength, 0);\n current.x += spacingLength * textHScale;\n continue;\n }\n const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;\n const operatorList = font.charProcOperatorList[glyph.operatorListId];\n if (!operatorList) {\n warn(`Type3 character "${glyph.operatorListId}" is not available.`);\n } else if (this.contentVisible) {\n this.save();\n ctx.scale(fontSize, fontSize);\n ctx.transform(...fontMatrix);\n this.executeOperatorList(operatorList);\n this.restore();\n }\n const p = [glyph.width, 0];\n Util.applyTransform(p, fontMatrix);\n width = p[0] * fontSize + spacing;\n ctx.translate(width, 0);\n current.x += width * textHScale;\n }\n ctx.restore();\n if (dependencyTracker) {\n this.dependencyTracker = dependencyTracker;\n }\n }\n setCharWidth(opIdx, xWidth, yWidth) {}\n setCharWidthAndBounds(opIdx, xWidth, yWidth, llx, lly, urx, ury) {\n const clip = new Path2D();\n clip.rect(llx, lly, urx - llx, ury - lly);\n this.ctx.clip(clip);\n this.dependencyTracker?.recordBBox(opIdx, this.ctx, llx, urx, lly, ury).recordClipBox(opIdx, this.ctx, llx, urx, lly, ury);\n this.endPath(opIdx);\n }\n getColorN_Pattern(opIdx, IR) {\n let pattern;\n if (IR[0] === "TilingPattern") {\n const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);\n const canvasGraphicsFactory = {\n createCanvasGraphics: (ctx, renderingOpIdx) => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {\n optionalContentConfig: this.optionalContentConfig,\n markedContentStack: this.markedContentStack\n }, undefined, undefined, this.dependencyTracker ? new CanvasNestedDependencyTracker(this.dependencyTracker, renderingOpIdx, true) : null)\n };\n pattern = new TilingPattern(IR, this.ctx, canvasGraphicsFactory, baseTransform);\n } else {\n pattern = this._getPattern(opIdx, IR[1], IR[2]);\n }\n return pattern;\n }\n setStrokeColorN(opIdx, ...args) {\n this.dependencyTracker?.recordSimpleData("strokeColor", opIdx);\n this.current.strokeColor = this.getColorN_Pattern(opIdx, args);\n this.current.patternStroke = true;\n }\n setFillColorN(opIdx, ...args) {\n this.dependencyTracker?.recordSimpleData("fillColor", opIdx);\n this.current.fillColor = this.getColorN_Pattern(opIdx, args);\n this.current.patternFill = true;\n }\n setStrokeRGBColor(opIdx, color) {\n this.dependencyTracker?.recordSimpleData("strokeColor", opIdx);\n this.ctx.strokeStyle = this.current.strokeColor = color;\n this.current.patternStroke = false;\n }\n setStrokeTransparent(opIdx) {\n this.dependencyTracker?.recordSimpleData("strokeColor", opIdx);\n this.ctx.strokeStyle = this.current.strokeColor = "transparent";\n this.current.patternStroke = false;\n }\n setFillRGBColor(opIdx, color) {\n this.dependencyTracker?.recordSimpleData("fillColor", opIdx);\n this.ctx.fillStyle = this.current.fillColor = color;\n this.current.patternFill = false;\n }\n setFillTransparent(opIdx) {\n this.dependencyTracker?.recordSimpleData("fillColor", opIdx);\n this.ctx.fillStyle = this.current.fillColor = "transparent";\n this.current.patternFill = false;\n }\n _getPattern(opIdx, objId, matrix = null) {\n let pattern;\n if (this.cachedPatterns.has(objId)) {\n pattern = this.cachedPatterns.get(objId);\n } else {\n pattern = getShadingPattern(this.getObject(opIdx, objId));\n this.cachedPatterns.set(objId, pattern);\n }\n if (matrix) {\n pattern.matrix = matrix;\n }\n return pattern;\n }\n shadingFill(opIdx, objId) {\n if (!this.contentVisible) {\n return;\n }\n const ctx = this.ctx;\n this.save(opIdx);\n const pattern = this._getPattern(opIdx, objId);\n ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING, opIdx);\n const inv = getCurrentTransformInverse(ctx);\n if (inv) {\n const {\n width,\n height\n } = ctx.canvas;\n const minMax = MIN_MAX_INIT.slice();\n Util.axialAlignedBoundingBox([0, 0, width, height], inv, minMax);\n const [x0, y0, x1, y1] = minMax;\n this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);\n } else {\n this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);\n }\n this.dependencyTracker?.resetBBox(opIdx).recordFullPageBBox(opIdx).recordDependencies(opIdx, Dependencies.transform).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx);\n this.compose(this.current.getClippedPathBoundingBox());\n this.restore(opIdx);\n }\n beginInlineImage() {\n unreachable("Should not call beginInlineImage");\n }\n beginImageData() {\n unreachable("Should not call beginImageData");\n }\n paintFormXObjectBegin(opIdx, matrix, bbox) {\n if (!this.contentVisible) {\n return;\n }\n this.save(opIdx);\n this.baseTransformStack.push(this.baseTransform);\n if (matrix) {\n this.transform(opIdx, ...matrix);\n }\n this.baseTransform = getCurrentTransform(this.ctx);\n if (bbox) {\n Util.axialAlignedBoundingBox(bbox, this.baseTransform, this.current.minMax);\n const [x0, y0, x1, y1] = bbox;\n const clip = new Path2D();\n clip.rect(x0, y0, x1 - x0, y1 - y0);\n this.ctx.clip(clip);\n this.dependencyTracker?.recordClipBox(opIdx, this.ctx, x0, x1, y0, y1);\n this.endPath(opIdx);\n }\n }\n paintFormXObjectEnd(opIdx) {\n if (!this.contentVisible) {\n return;\n }\n this.restore(opIdx);\n this.baseTransform = this.baseTransformStack.pop();\n }\n beginGroup(opIdx, group) {\n if (!this.contentVisible) {\n return;\n }\n this.save(opIdx);\n if (this.inSMaskMode) {\n this.endSMaskMode();\n this.current.activeSMask = null;\n }\n const currentCtx = this.ctx;\n if (!group.isolated) {\n info("TODO: Support non-isolated groups.");\n }\n if (group.knockout) {\n warn("Knockout groups not supported.");\n }\n const currentTransform = getCurrentTransform(currentCtx);\n if (group.matrix) {\n currentCtx.transform(...group.matrix);\n }\n if (!group.bbox) {\n throw new Error("Bounding box is required.");\n }\n let bounds = MIN_MAX_INIT.slice();\n Util.axialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx), bounds);\n const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];\n bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];\n const offsetX = Math.floor(bounds[0]);\n const offsetY = Math.floor(bounds[1]);\n const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);\n const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);\n this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);\n let cacheId = "groupAt" + this.groupLevel;\n if (group.smask) {\n cacheId += "_smask_" + this.smaskCounter++ % 2;\n }\n const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);\n const groupCtx = scratchCanvas.context;\n groupCtx.translate(-offsetX, -offsetY);\n groupCtx.transform(...currentTransform);\n let clip = new Path2D();\n const [x0, y0, x1, y1] = group.bbox;\n clip.rect(x0, y0, x1 - x0, y1 - y0);\n if (group.matrix) {\n const path = new Path2D();\n path.addPath(clip, new DOMMatrix(group.matrix));\n clip = path;\n }\n groupCtx.clip(clip);\n if (group.smask) {\n this.smaskStack.push({\n canvas: scratchCanvas.canvas,\n context: groupCtx,\n offsetX,\n offsetY,\n subtype: group.smask.subtype,\n backdrop: group.smask.backdrop,\n transferMap: group.smask.transferMap || null,\n startTransformInverse: null\n });\n }\n if (!group.smask || this.dependencyTracker) {\n currentCtx.setTransform(1, 0, 0, 1, 0, 0);\n currentCtx.translate(offsetX, offsetY);\n currentCtx.save();\n }\n copyCtxState(currentCtx, groupCtx);\n this.ctx = groupCtx;\n this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha", "strokeAlpha", "globalCompositeOperation"]).pushBaseTransform(currentCtx);\n this.setGState(opIdx, [["BM", "source-over"], ["ca", 1], ["CA", 1], ["TR", null]]);\n this.groupStack.push(currentCtx);\n this.groupLevel++;\n }\n endGroup(opIdx, group) {\n if (!this.contentVisible) {\n return;\n }\n this.groupLevel--;\n const groupCtx = this.ctx;\n const ctx = this.groupStack.pop();\n this.ctx = ctx;\n this.ctx.imageSmoothingEnabled = false;\n this.dependencyTracker?.popBaseTransform();\n if (group.smask) {\n this.tempSMask = this.smaskStack.pop();\n this.restore(opIdx);\n if (this.dependencyTracker) {\n this.ctx.restore();\n }\n } else {\n this.ctx.restore();\n const currentMtx = getCurrentTransform(this.ctx);\n this.restore(opIdx);\n this.ctx.save();\n this.ctx.setTransform(...currentMtx);\n const dirtyBox = MIN_MAX_INIT.slice();\n Util.axialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx, dirtyBox);\n this.ctx.drawImage(groupCtx.canvas, 0, 0);\n this.ctx.restore();\n this.compose(dirtyBox);\n }\n }\n beginAnnotation(opIdx, id, rect, transform, matrix, hasOwnCanvas) {\n this.#restoreInitialState();\n resetCtxToDefault(this.ctx);\n this.ctx.save();\n this.save(opIdx);\n if (this.baseTransform) {\n this.ctx.setTransform(...this.baseTransform);\n }\n if (rect) {\n const width = rect[2] - rect[0];\n const height = rect[3] - rect[1];\n if (hasOwnCanvas && this.annotationCanvasMap) {\n transform = transform.slice();\n transform[4] -= rect[0];\n transform[5] -= rect[1];\n rect = rect.slice();\n rect[0] = rect[1] = 0;\n rect[2] = width;\n rect[3] = height;\n Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx), XY);\n const {\n viewportScale\n } = this;\n const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);\n const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);\n this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);\n const {\n canvas,\n context\n } = this.annotationCanvas;\n this.annotationCanvasMap.set(id, canvas);\n this.annotationCanvas.savedCtx = this.ctx;\n this.ctx = context;\n this.ctx.save();\n this.ctx.setTransform(XY[0], 0, 0, -XY[1], 0, height * XY[1]);\n resetCtxToDefault(this.ctx);\n } else {\n resetCtxToDefault(this.ctx);\n this.endPath(opIdx);\n const clip = new Path2D();\n clip.rect(rect[0], rect[1], width, height);\n this.ctx.clip(clip);\n }\n }\n this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);\n this.transform(opIdx, ...transform);\n this.transform(opIdx, ...matrix);\n }\n endAnnotation(opIdx) {\n if (this.annotationCanvas) {\n this.ctx.restore();\n this.#drawFilter();\n this.ctx = this.annotationCanvas.savedCtx;\n delete this.annotationCanvas.savedCtx;\n delete this.annotationCanvas;\n }\n }\n paintImageMaskXObject(opIdx, img) {\n if (!this.contentVisible) {\n return;\n }\n const count = img.count;\n img = this.getObject(opIdx, img.data, img);\n img.count = count;\n const ctx = this.ctx;\n const mask = this._createMaskCanvas(opIdx, img);\n const maskCanvas = mask.canvas;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);\n this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, mask.offsetX, mask.offsetX + maskCanvas.width, mask.offsetY, mask.offsetY + maskCanvas.height).recordOperation(opIdx);\n ctx.restore();\n this.compose();\n }\n paintImageMaskXObjectRepeat(opIdx, img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {\n if (!this.contentVisible) {\n return;\n }\n img = this.getObject(opIdx, img.data, img);\n const ctx = this.ctx;\n ctx.save();\n const currentTransform = getCurrentTransform(ctx);\n ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);\n const mask = this._createMaskCanvas(opIdx, img);\n ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);\n this.dependencyTracker?.resetBBox(opIdx);\n for (let i = 0, ii = positions.length; i < ii; i += 2) {\n const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);\n ctx.drawImage(mask.canvas, trans[4], trans[5]);\n this.dependencyTracker?.recordBBox(opIdx, this.ctx, trans[4], trans[4] + mask.canvas.width, trans[5], trans[5] + mask.canvas.height);\n }\n ctx.restore();\n this.compose();\n this.dependencyTracker?.recordOperation(opIdx);\n }\n paintImageMaskXObjectGroup(opIdx, images) {\n if (!this.contentVisible) {\n return;\n }\n const ctx = this.ctx;\n const fillColor = this.current.fillColor;\n const isPatternFill = this.current.patternFill;\n this.dependencyTracker?.resetBBox(opIdx).recordDependencies(opIdx, Dependencies.transformAndFill);\n for (const image of images) {\n const {\n data,\n width,\n height,\n transform\n } = image;\n const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);\n const maskCtx = maskCanvas.context;\n maskCtx.save();\n const img = this.getObject(opIdx, data, image);\n putBinaryImageMask(maskCtx, img);\n maskCtx.globalCompositeOperation = "source-in";\n maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx) : fillColor;\n maskCtx.fillRect(0, 0, width, height);\n maskCtx.restore();\n ctx.save();\n ctx.transform(...transform);\n ctx.scale(1, -1);\n drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);\n this.dependencyTracker?.recordBBox(opIdx, ctx, 0, width, 0, height);\n ctx.restore();\n }\n this.compose();\n this.dependencyTracker?.recordOperation(opIdx);\n }\n paintImageXObject(opIdx, objId) {\n if (!this.contentVisible) {\n return;\n }\n const imgData = this.getObject(opIdx, objId);\n if (!imgData) {\n warn("Dependent image isn\'t ready yet");\n return;\n }\n this.paintInlineImageXObject(opIdx, imgData);\n }\n paintImageXObjectRepeat(opIdx, objId, scaleX, scaleY, positions) {\n if (!this.contentVisible) {\n return;\n }\n const imgData = this.getObject(opIdx, objId);\n if (!imgData) {\n warn("Dependent image isn\'t ready yet");\n return;\n }\n const width = imgData.width;\n const height = imgData.height;\n const map = [];\n for (let i = 0, ii = positions.length; i < ii; i += 2) {\n map.push({\n transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],\n x: 0,\n y: 0,\n w: width,\n h: height\n });\n }\n this.paintInlineImageXObjectGroup(opIdx, imgData, map);\n }\n applyTransferMapsToCanvas(ctx) {\n if (this.current.transferMaps !== "none") {\n ctx.filter = this.current.transferMaps;\n ctx.drawImage(ctx.canvas, 0, 0);\n ctx.filter = "none";\n }\n return ctx.canvas;\n }\n applyTransferMapsToBitmap(imgData) {\n if (this.current.transferMaps === "none") {\n return imgData.bitmap;\n }\n const {\n bitmap,\n width,\n height\n } = imgData;\n const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);\n const tmpCtx = tmpCanvas.context;\n tmpCtx.filter = this.current.transferMaps;\n tmpCtx.drawImage(bitmap, 0, 0);\n tmpCtx.filter = "none";\n return tmpCanvas.canvas;\n }\n paintInlineImageXObject(opIdx, imgData) {\n if (!this.contentVisible) {\n return;\n }\n const width = imgData.width;\n const height = imgData.height;\n const ctx = this.ctx;\n this.save(opIdx);\n const {\n filter\n } = ctx;\n if (filter !== "none" && filter !== "") {\n ctx.filter = "none";\n }\n ctx.scale(1 / width, -1 / height);\n let imgToPaint;\n if (imgData.bitmap) {\n imgToPaint = this.applyTransferMapsToBitmap(imgData);\n } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {\n imgToPaint = imgData;\n } else {\n const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);\n const tmpCtx = tmpCanvas.context;\n putBinaryImageData(tmpCtx, imgData);\n imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);\n }\n const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx));\n ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate);\n this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, ctx, 0, width, -height, 0).recordDependencies(opIdx, Dependencies.imageXObject).recordOperation(opIdx);\n drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);\n this.compose();\n this.restore(opIdx);\n }\n paintInlineImageXObjectGroup(opIdx, imgData, map) {\n if (!this.contentVisible) {\n return;\n }\n const ctx = this.ctx;\n let imgToPaint;\n if (imgData.bitmap) {\n imgToPaint = imgData.bitmap;\n } else {\n const w = imgData.width;\n const h = imgData.height;\n const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);\n const tmpCtx = tmpCanvas.context;\n putBinaryImageData(tmpCtx, imgData);\n imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);\n }\n this.dependencyTracker?.resetBBox(opIdx);\n for (const entry of map) {\n ctx.save();\n ctx.transform(...entry.transform);\n ctx.scale(1, -1);\n drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);\n this.dependencyTracker?.recordBBox(opIdx, ctx, 0, 1, -1, 0);\n ctx.restore();\n }\n this.dependencyTracker?.recordOperation(opIdx);\n this.compose();\n }\n paintSolidColorImageMask(opIdx) {\n if (!this.contentVisible) {\n return;\n }\n this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, 0, 1, 0, 1).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx);\n this.ctx.fillRect(0, 0, 1, 1);\n this.compose();\n }\n markPoint(opIdx, tag) {}\n markPointProps(opIdx, tag, properties) {}\n beginMarkedContent(opIdx, tag) {\n this.dependencyTracker?.beginMarkedContent(opIdx);\n this.markedContentStack.push({\n visible: true\n });\n }\n beginMarkedContentProps(opIdx, tag, properties) {\n this.dependencyTracker?.beginMarkedContent(opIdx);\n if (tag === "OC") {\n this.markedContentStack.push({\n visible: this.optionalContentConfig.isVisible(properties)\n });\n } else {\n this.markedContentStack.push({\n visible: true\n });\n }\n this.contentVisible = this.isContentVisible();\n }\n endMarkedContent(opIdx) {\n this.dependencyTracker?.endMarkedContent(opIdx);\n this.markedContentStack.pop();\n this.contentVisible = this.isContentVisible();\n }\n beginCompat(opIdx) {}\n endCompat(opIdx) {}\n consumePath(opIdx, path, clipBox) {\n const isEmpty = this.current.isEmptyClip();\n if (this.pendingClip) {\n this.current.updateClipFromPath();\n }\n if (!this.pendingClip) {\n this.compose(clipBox);\n }\n const ctx = this.ctx;\n if (this.pendingClip) {\n if (!isEmpty) {\n if (this.pendingClip === EO_CLIP) {\n ctx.clip(path, "evenodd");\n } else {\n ctx.clip(path);\n }\n }\n this.pendingClip = null;\n this.dependencyTracker?.bboxToClipBoxDropOperation(opIdx).recordFutureForcedDependency("clipPath", opIdx);\n } else {\n this.dependencyTracker?.recordOperation(opIdx);\n }\n this.current.startNewPathAndClipBox(this.current.clipBox);\n }\n getSinglePixelWidth() {\n if (!this._cachedGetSinglePixelWidth) {\n const m = getCurrentTransform(this.ctx);\n if (m[1] === 0 && m[2] === 0) {\n this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));\n } else {\n const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);\n const normX = Math.hypot(m[0], m[2]);\n const normY = Math.hypot(m[1], m[3]);\n this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;\n }\n }\n return this._cachedGetSinglePixelWidth;\n }\n getScaleForStroking() {\n if (this._cachedScaleForStroking[0] === -1) {\n const {\n lineWidth\n } = this.current;\n const {\n a,\n b,\n c,\n d\n } = this.ctx.getTransform();\n let scaleX, scaleY;\n if (b === 0 && c === 0) {\n const normX = Math.abs(a);\n const normY = Math.abs(d);\n if (normX === normY) {\n if (lineWidth === 0) {\n scaleX = scaleY = 1 / normX;\n } else {\n const scaledLineWidth = normX * lineWidth;\n scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;\n }\n } else if (lineWidth === 0) {\n scaleX = 1 / normX;\n scaleY = 1 / normY;\n } else {\n const scaledXLineWidth = normX * lineWidth;\n const scaledYLineWidth = normY * lineWidth;\n scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;\n scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;\n }\n } else {\n const absDet = Math.abs(a * d - b * c);\n const normX = Math.hypot(a, b);\n const normY = Math.hypot(c, d);\n if (lineWidth === 0) {\n scaleX = normY / absDet;\n scaleY = normX / absDet;\n } else {\n const baseArea = lineWidth * absDet;\n scaleX = normY > baseArea ? normY / baseArea : 1;\n scaleY = normX > baseArea ? normX / baseArea : 1;\n }\n }\n this._cachedScaleForStroking[0] = scaleX;\n this._cachedScaleForStroking[1] = scaleY;\n }\n return this._cachedScaleForStroking;\n }\n rescaleAndStroke(path, saveRestore) {\n const {\n ctx,\n current: {\n lineWidth\n }\n } = this;\n const [scaleX, scaleY] = this.getScaleForStroking();\n if (scaleX === scaleY) {\n ctx.lineWidth = (lineWidth || 1) * scaleX;\n ctx.stroke(path);\n return;\n }\n const dashes = ctx.getLineDash();\n if (saveRestore) {\n ctx.save();\n }\n ctx.scale(scaleX, scaleY);\n SCALE_MATRIX.a = 1 / scaleX;\n SCALE_MATRIX.d = 1 / scaleY;\n const newPath = new Path2D();\n newPath.addPath(path, SCALE_MATRIX);\n if (dashes.length > 0) {\n const scale = Math.max(scaleX, scaleY);\n ctx.setLineDash(dashes.map(x => x / scale));\n ctx.lineDashOffset /= scale;\n }\n ctx.lineWidth = lineWidth || 1;\n ctx.stroke(newPath);\n if (saveRestore) {\n ctx.restore();\n }\n }\n isContentVisible() {\n for (let i = this.markedContentStack.length - 1; i >= 0; i--) {\n if (!this.markedContentStack[i].visible) {\n return false;\n }\n }\n return true;\n }\n}\nfor (const op in OPS) {\n if (CanvasGraphics.prototype[op] !== undefined) {\n CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];\n }\n}\n\n;// ./src/display/worker_options.js\nclass GlobalWorkerOptions {\n static #port = null;\n static #src = "";\n static get workerPort() {\n return this.#port;\n }\n static set workerPort(val) {\n if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) {\n throw new Error("Invalid `workerPort` type.");\n }\n this.#port = val;\n }\n static get workerSrc() {\n return this.#src;\n }\n static set workerSrc(val) {\n if (typeof val !== "string") {\n throw new Error("Invalid `workerSrc` type.");\n }\n this.#src = val;\n }\n}\n\n;// ./src/display/metadata.js\nclass Metadata {\n #map;\n #data;\n constructor({\n parsedData,\n rawData\n }) {\n this.#map = parsedData;\n this.#data = rawData;\n }\n getRaw() {\n return this.#data;\n }\n get(name) {\n return this.#map.get(name) ?? null;\n }\n [Symbol.iterator]() {\n return this.#map.entries();\n }\n}\n\n;// ./src/display/optional_content_config.js\n\n\n\n\nconst INTERNAL = Symbol("INTERNAL");\nclass OptionalContentGroup {\n #isDisplay = false;\n #isPrint = false;\n #userSet = false;\n #visible = true;\n constructor(renderingIntent, {\n name,\n intent,\n usage,\n rbGroups\n }) {\n this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);\n this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);\n this.name = name;\n this.intent = intent;\n this.usage = usage;\n this.rbGroups = rbGroups;\n }\n get visible() {\n if (this.#userSet) {\n return this.#visible;\n }\n if (!this.#visible) {\n return false;\n }\n const {\n print,\n view\n } = this.usage;\n if (this.#isDisplay) {\n return view?.viewState !== "OFF";\n } else if (this.#isPrint) {\n return print?.printState !== "OFF";\n }\n return true;\n }\n _setVisible(internal, visible, userSet = false) {\n if (internal !== INTERNAL) {\n unreachable("Internal method `_setVisible` called.");\n }\n this.#userSet = userSet;\n this.#visible = visible;\n }\n}\nclass OptionalContentConfig {\n #cachedGetHash = null;\n #groups = new Map();\n #initialHash = null;\n #order = null;\n constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {\n this.renderingIntent = renderingIntent;\n this.name = null;\n this.creator = null;\n if (data === null) {\n return;\n }\n this.name = data.name;\n this.creator = data.creator;\n this.#order = data.order;\n for (const group of data.groups) {\n this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group));\n }\n if (data.baseState === "OFF") {\n for (const group of this.#groups.values()) {\n group._setVisible(INTERNAL, false);\n }\n }\n for (const on of data.on) {\n this.#groups.get(on)._setVisible(INTERNAL, true);\n }\n for (const off of data.off) {\n this.#groups.get(off)._setVisible(INTERNAL, false);\n }\n this.#initialHash = this.getHash();\n }\n #evaluateVisibilityExpression(array) {\n const length = array.length;\n if (length < 2) {\n return true;\n }\n const operator = array[0];\n for (let i = 1; i < length; i++) {\n const element = array[i];\n let state;\n if (Array.isArray(element)) {\n state = this.#evaluateVisibilityExpression(element);\n } else if (this.#groups.has(element)) {\n state = this.#groups.get(element).visible;\n } else {\n warn(`Optional content group not found: ${element}`);\n return true;\n }\n switch (operator) {\n case "And":\n if (!state) {\n return false;\n }\n break;\n case "Or":\n if (state) {\n return true;\n }\n break;\n case "Not":\n return !state;\n default:\n return true;\n }\n }\n return operator === "And";\n }\n isVisible(group) {\n if (this.#groups.size === 0) {\n return true;\n }\n if (!group) {\n info("Optional content group not defined.");\n return true;\n }\n if (group.type === "OCG") {\n if (!this.#groups.has(group.id)) {\n warn(`Optional content group not found: ${group.id}`);\n return true;\n }\n return this.#groups.get(group.id).visible;\n } else if (group.type === "OCMD") {\n if (group.expression) {\n return this.#evaluateVisibilityExpression(group.expression);\n }\n if (!group.policy || group.policy === "AnyOn") {\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (this.#groups.get(id).visible) {\n return true;\n }\n }\n return false;\n } else if (group.policy === "AllOn") {\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (!this.#groups.get(id).visible) {\n return false;\n }\n }\n return true;\n } else if (group.policy === "AnyOff") {\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (!this.#groups.get(id).visible) {\n return true;\n }\n }\n return false;\n } else if (group.policy === "AllOff") {\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (this.#groups.get(id).visible) {\n return false;\n }\n }\n return true;\n }\n warn(`Unknown optional content policy ${group.policy}.`);\n return true;\n }\n warn(`Unknown group type ${group.type}.`);\n return true;\n }\n setVisibility(id, visible = true, preserveRB = true) {\n const group = this.#groups.get(id);\n if (!group) {\n warn(`Optional content group not found: ${id}`);\n return;\n }\n if (preserveRB && visible && group.rbGroups.length) {\n for (const rbGroup of group.rbGroups) {\n for (const otherId of rbGroup) {\n if (otherId !== id) {\n this.#groups.get(otherId)?._setVisible(INTERNAL, false, true);\n }\n }\n }\n }\n group._setVisible(INTERNAL, !!visible, true);\n this.#cachedGetHash = null;\n }\n setOCGState({\n state,\n preserveRB\n }) {\n let operator;\n for (const elem of state) {\n switch (elem) {\n case "ON":\n case "OFF":\n case "Toggle":\n operator = elem;\n continue;\n }\n const group = this.#groups.get(elem);\n if (!group) {\n continue;\n }\n switch (operator) {\n case "ON":\n this.setVisibility(elem, true, preserveRB);\n break;\n case "OFF":\n this.setVisibility(elem, false, preserveRB);\n break;\n case "Toggle":\n this.setVisibility(elem, !group.visible, preserveRB);\n break;\n }\n }\n this.#cachedGetHash = null;\n }\n get hasInitialVisibility() {\n return this.#initialHash === null || this.getHash() === this.#initialHash;\n }\n getOrder() {\n if (!this.#groups.size) {\n return null;\n }\n if (this.#order) {\n return this.#order.slice();\n }\n return [...this.#groups.keys()];\n }\n getGroup(id) {\n return this.#groups.get(id) || null;\n }\n getHash() {\n if (this.#cachedGetHash !== null) {\n return this.#cachedGetHash;\n }\n const hash = new MurmurHash3_64();\n for (const [id, group] of this.#groups) {\n hash.update(`${id}:${group.visible}`);\n }\n return this.#cachedGetHash = hash.hexdigest();\n }\n [Symbol.iterator]() {\n return this.#groups.entries();\n }\n}\n\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.find.js\nvar es_iterator_find = __webpack_require__(116);\n;// ./src/shared/base_pdf_stream.js\n\n\n\n\n\n\n\n\n\nclass BasePDFStream {\n #PDFStreamReader = null;\n #PDFStreamRangeReader = null;\n _fullReader = null;\n _rangeReaders = new Set();\n _source = null;\n constructor(source, PDFStreamReader, PDFStreamRangeReader) {\n this._source = source;\n this.#PDFStreamReader = PDFStreamReader;\n this.#PDFStreamRangeReader = PDFStreamRangeReader;\n }\n get _progressiveDataLength() {\n return this._fullReader?._loaded ?? 0;\n }\n getFullReader() {\n assert(!this._fullReader, "BasePDFStream.getFullReader can only be called once.");\n return this._fullReader = new this.#PDFStreamReader(this);\n }\n getRangeReader(begin, end) {\n if (end <= this._progressiveDataLength) {\n return null;\n }\n const reader = new this.#PDFStreamRangeReader(this, begin, end);\n this._rangeReaders.add(reader);\n return reader;\n }\n cancelAllRequests(reason) {\n this._fullReader?.cancel(reason);\n for (const reader of new Set(this._rangeReaders)) {\n reader.cancel(reason);\n }\n }\n}\nclass BasePDFStreamReader {\n onProgress = null;\n _contentLength = 0;\n _filename = null;\n _headersCapability = Promise.withResolvers();\n _isRangeSupported = false;\n _isStreamingSupported = false;\n _loaded = 0;\n _stream = null;\n constructor(stream) {\n this._stream = stream;\n }\n _callOnProgress() {\n this.onProgress?.({\n loaded: this._loaded,\n total: this._contentLength\n });\n }\n get headersReady() {\n return this._headersCapability.promise;\n }\n get filename() {\n return this._filename;\n }\n get contentLength() {\n return this._contentLength;\n }\n get isRangeSupported() {\n return this._isRangeSupported;\n }\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n async read() {\n unreachable("Abstract method `read` called");\n }\n cancel(reason) {\n unreachable("Abstract method `cancel` called");\n }\n}\nclass BasePDFStreamRangeReader {\n _stream = null;\n constructor(stream, begin, end) {\n this._stream = stream;\n }\n async read() {\n unreachable("Abstract method `read` called");\n }\n cancel(reason) {\n unreachable("Abstract method `cancel` called");\n }\n}\n\n;// ./src/display/transport_stream.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction getArrayBuffer(val) {\n return val instanceof Uint8Array && val.byteLength === val.buffer.byteLength ? val.buffer : new Uint8Array(val).buffer;\n}\nfunction endRequests() {\n for (const capability of this._requests) {\n capability.resolve({\n value: undefined,\n done: true\n });\n }\n this._requests.length = 0;\n}\nclass PDFDataTransportStream extends BasePDFStream {\n _progressiveDone = false;\n _queuedChunks = [];\n constructor(source) {\n super(source, PDFDataTransportStreamReader, PDFDataTransportStreamRangeReader);\n const {\n pdfDataRangeTransport\n } = source;\n const {\n initialData,\n progressiveDone\n } = pdfDataRangeTransport;\n if (initialData?.length > 0) {\n const buffer = getArrayBuffer(initialData);\n this._queuedChunks.push(buffer);\n }\n this._progressiveDone = progressiveDone;\n pdfDataRangeTransport.addRangeListener((begin, chunk) => {\n this.#onReceiveData(begin, chunk);\n });\n pdfDataRangeTransport.addProgressiveReadListener(chunk => {\n this.#onReceiveData(undefined, chunk);\n });\n pdfDataRangeTransport.addProgressiveDoneListener(() => {\n this._fullReader?.progressiveDone();\n this._progressiveDone = true;\n });\n pdfDataRangeTransport.transportReady();\n }\n #onReceiveData(begin, chunk) {\n const buffer = getArrayBuffer(chunk);\n if (begin === undefined) {\n if (this._fullReader) {\n this._fullReader._enqueue(buffer);\n } else {\n this._queuedChunks.push(buffer);\n }\n } else {\n const rangeReader = this._rangeReaders.keys().find(r => r._begin === begin);\n assert(rangeReader, "#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");\n rangeReader._enqueue(buffer);\n }\n }\n getFullReader() {\n const reader = super.getFullReader();\n this._queuedChunks = null;\n return reader;\n }\n getRangeReader(begin, end) {\n const reader = super.getRangeReader(begin, end);\n if (reader) {\n reader.onDone = () => this._rangeReaders.delete(reader);\n this._source.pdfDataRangeTransport.requestDataRange(begin, end);\n }\n return reader;\n }\n cancelAllRequests(reason) {\n super.cancelAllRequests(reason);\n this._source.pdfDataRangeTransport.abort();\n }\n}\nclass PDFDataTransportStreamReader extends BasePDFStreamReader {\n #endRequests = endRequests.bind(this);\n _done = false;\n _queuedChunks = null;\n _requests = [];\n constructor(stream) {\n super(stream);\n const {\n pdfDataRangeTransport,\n disableRange,\n disableStream\n } = stream._source;\n const {\n length,\n contentDispositionFilename\n } = pdfDataRangeTransport;\n this._queuedChunks = stream._queuedChunks || [];\n for (const chunk of this._queuedChunks) {\n this._loaded += chunk.byteLength;\n }\n this._done = stream._progressiveDone;\n this._contentLength = length;\n this._isStreamingSupported = !disableStream;\n this._isRangeSupported = !disableRange;\n if (isPdfFile(contentDispositionFilename)) {\n this._filename = contentDispositionFilename;\n }\n this._headersCapability.resolve();\n const loaded = this._loaded;\n Promise.resolve().then(() => {\n if (loaded > 0 && this._loaded === loaded) {\n this._callOnProgress();\n }\n });\n }\n _enqueue(chunk) {\n if (this._done) {\n return;\n }\n if (this._requests.length > 0) {\n const capability = this._requests.shift();\n capability.resolve({\n value: chunk,\n done: false\n });\n } else {\n this._queuedChunks.push(chunk);\n }\n this._loaded += chunk.byteLength;\n this._callOnProgress();\n }\n async read() {\n if (this._queuedChunks.length > 0) {\n const chunk = this._queuedChunks.shift();\n return {\n value: chunk,\n done: false\n };\n }\n if (this._done) {\n return {\n value: undefined,\n done: true\n };\n }\n const capability = Promise.withResolvers();\n this._requests.push(capability);\n return capability.promise;\n }\n cancel(reason) {\n this._done = true;\n this.#endRequests();\n }\n progressiveDone() {\n this._done ||= true;\n if (this._queuedChunks.length === 0) {\n this.#endRequests();\n }\n }\n}\nclass PDFDataTransportStreamRangeReader extends BasePDFStreamRangeReader {\n #endRequests = endRequests.bind(this);\n onDone = null;\n _begin = -1;\n _done = false;\n _queuedChunk = null;\n _requests = [];\n constructor(stream, begin, end) {\n super(stream, begin, end);\n this._begin = begin;\n }\n _enqueue(chunk) {\n if (this._done) {\n return;\n }\n if (this._requests.length === 0) {\n this._queuedChunk = chunk;\n } else {\n const capability = this._requests.shift();\n capability.resolve({\n value: chunk,\n done: false\n });\n this.#endRequests();\n }\n this._done = true;\n this.onDone?.();\n }\n async read() {\n if (this._queuedChunk) {\n const chunk = this._queuedChunk;\n this._queuedChunk = null;\n return {\n value: chunk,\n done: false\n };\n }\n if (this._done) {\n return {\n value: undefined,\n done: true\n };\n }\n const capability = Promise.withResolvers();\n this._requests.push(capability);\n return capability.promise;\n }\n cancel(reason) {\n this._done = true;\n this.#endRequests();\n this.onDone?.();\n }\n}\n\n;// ./src/display/content_disposition.js\n\n\n\nfunction getFilenameFromContentDispositionHeader(contentDisposition) {\n let needsEncodingFixup = true;\n let tmp = toParamRegExp("filename\\\\*", "i").exec(contentDisposition);\n if (tmp) {\n tmp = tmp[1];\n let filename = rfc2616unquote(tmp);\n filename = unescape(filename);\n filename = rfc5987decode(filename);\n filename = rfc2047decode(filename);\n return fixupEncoding(filename);\n }\n tmp = rfc2231getparam(contentDisposition);\n if (tmp) {\n const filename = rfc2047decode(tmp);\n return fixupEncoding(filename);\n }\n tmp = toParamRegExp("filename", "i").exec(contentDisposition);\n if (tmp) {\n tmp = tmp[1];\n let filename = rfc2616unquote(tmp);\n filename = rfc2047decode(filename);\n return fixupEncoding(filename);\n }\n function toParamRegExp(attributePattern, flags) {\n return new RegExp("(?:^|;)\\\\s*" + attributePattern + "\\\\s*=\\\\s*" + "(" + \'[^";\\\\s][^;\\\\s]*\' + "|" + \'"(?:[^"\\\\\\\\]|\\\\\\\\"?)+"?\' + ")", flags);\n }\n function textdecode(encoding, value) {\n if (encoding) {\n if (!/^[\\x00-\\xFF]+$/.test(value)) {\n return value;\n }\n try {\n const decoder = new TextDecoder(encoding, {\n fatal: true\n });\n const buffer = stringToBytes(value);\n value = decoder.decode(buffer);\n needsEncodingFixup = false;\n } catch {}\n }\n return value;\n }\n function fixupEncoding(value) {\n if (needsEncodingFixup && /[\\x80-\\xff]/.test(value)) {\n value = textdecode("utf-8", value);\n if (needsEncodingFixup) {\n value = textdecode("iso-8859-1", value);\n }\n }\n return value;\n }\n function rfc2231getparam(contentDispositionStr) {\n const matches = [];\n let match;\n const iter = toParamRegExp("filename\\\\*((?!0\\\\d)\\\\d+)(\\\\*?)", "ig");\n while ((match = iter.exec(contentDispositionStr)) !== null) {\n let [, n, quot, part] = match;\n n = parseInt(n, 10);\n if (n in matches) {\n if (n === 0) {\n break;\n }\n continue;\n }\n matches[n] = [quot, part];\n }\n const parts = [];\n for (let n = 0; n < matches.length; ++n) {\n if (!(n in matches)) {\n break;\n }\n let [quot, part] = matches[n];\n part = rfc2616unquote(part);\n if (quot) {\n part = unescape(part);\n if (n === 0) {\n part = rfc5987decode(part);\n }\n }\n parts.push(part);\n }\n return parts.join("");\n }\n function rfc2616unquote(value) {\n if (value.startsWith(\'"\')) {\n const parts = value.slice(1).split(\'\\\\"\');\n for (let i = 0; i < parts.length; ++i) {\n const quotindex = parts[i].indexOf(\'"\');\n if (quotindex !== -1) {\n parts[i] = parts[i].slice(0, quotindex);\n parts.length = i + 1;\n }\n parts[i] = parts[i].replaceAll(/\\\\(.)/g, "$1");\n }\n value = parts.join(\'"\');\n }\n return value;\n }\n function rfc5987decode(extvalue) {\n const encodingend = extvalue.indexOf("\'");\n if (encodingend === -1) {\n return extvalue;\n }\n const encoding = extvalue.slice(0, encodingend);\n const langvalue = extvalue.slice(encodingend + 1);\n const value = langvalue.replace(/^[^\']*\'/, "");\n return textdecode(encoding, value);\n }\n function rfc2047decode(value) {\n if (!value.startsWith("=?") || /[\\x00-\\x19\\x80-\\xff]/.test(value)) {\n return value;\n }\n return value.replaceAll(/=\\?([\\w-]*)\\?([QqBb])\\?((?:[^?]|\\?(?!=))*)\\?=/g, function (matches, charset, encoding, text) {\n if (encoding === "q" || encoding === "Q") {\n text = text.replaceAll("_", " ");\n text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {\n return String.fromCharCode(parseInt(hex, 16));\n });\n return textdecode(charset, text);\n }\n try {\n text = atob(text);\n } catch {}\n return textdecode(charset, text);\n });\n }\n return "";\n}\n\n;// ./src/display/network_utils.js\n\n\n\n\nfunction createHeaders(isHttp, httpHeaders) {\n const headers = new Headers();\n if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") {\n return headers;\n }\n for (const key in httpHeaders) {\n const val = httpHeaders[key];\n if (val !== undefined) {\n headers.append(key, val);\n }\n }\n return headers;\n}\nfunction getResponseOrigin(url) {\n return URL.parse(url)?.origin ?? null;\n}\nfunction validateRangeRequestCapabilities({\n responseHeaders,\n isHttp,\n rangeChunkSize,\n disableRange\n}) {\n const returnValues = {\n allowRangeRequests: false,\n suggestedLength: undefined\n };\n const length = parseInt(responseHeaders.get("Content-Length"), 10);\n if (!Number.isInteger(length)) {\n return returnValues;\n }\n returnValues.suggestedLength = length;\n if (length <= 2 * rangeChunkSize) {\n return returnValues;\n }\n if (disableRange || !isHttp) {\n return returnValues;\n }\n if (responseHeaders.get("Accept-Ranges") !== "bytes") {\n return returnValues;\n }\n const contentEncoding = responseHeaders.get("Content-Encoding") || "identity";\n if (contentEncoding !== "identity") {\n return returnValues;\n }\n returnValues.allowRangeRequests = true;\n return returnValues;\n}\nfunction extractFilenameFromHeader(responseHeaders) {\n const contentDisposition = responseHeaders.get("Content-Disposition");\n if (contentDisposition) {\n let filename = getFilenameFromContentDispositionHeader(contentDisposition);\n if (filename.includes("%")) {\n try {\n filename = decodeURIComponent(filename);\n } catch {}\n }\n if (isPdfFile(filename)) {\n return filename;\n }\n }\n return null;\n}\nfunction createResponseError(status, url) {\n return new ResponseException(`Unexpected server response (${status}) while retrieving PDF "${url.href}".`, status, status === 404 || status === 0 && url.protocol === "file:");\n}\nfunction ensureResponseOrigin(rangeOrigin, origin) {\n if (rangeOrigin !== origin) {\n throw new Error(`Expected range response-origin "${rangeOrigin}" to match "${origin}".`);\n }\n}\n\n;// ./src/display/fetch_stream.js\n\n\n\n\n\n\n\n\n\n\n\n\nfunction fetchUrl(url, headers, withCredentials, abortController) {\n return fetch(url, {\n method: "GET",\n headers,\n signal: abortController.signal,\n mode: "cors",\n credentials: withCredentials ? "include" : "same-origin",\n redirect: "follow"\n });\n}\nfunction ensureResponseStatus(status, url) {\n if (status !== 200 && status !== 206) {\n throw createResponseError(status, url);\n }\n}\nfunction fetch_stream_getArrayBuffer(val) {\n if (val instanceof Uint8Array) {\n return val.buffer;\n }\n if (val instanceof ArrayBuffer) {\n return val;\n }\n throw new Error(`getArrayBuffer - unexpected data: ${val}`);\n}\nclass PDFFetchStream extends BasePDFStream {\n _responseOrigin = null;\n constructor(source) {\n super(source, PDFFetchStreamReader, PDFFetchStreamRangeReader);\n const {\n httpHeaders,\n url\n } = source;\n assert(/https?:/.test(url.protocol), "PDFFetchStream only supports http(s):// URLs.");\n this.headers = createHeaders(true, httpHeaders);\n }\n}\nclass PDFFetchStreamReader extends BasePDFStreamReader {\n _abortController = new AbortController();\n _reader = null;\n constructor(stream) {\n super(stream);\n const {\n disableRange,\n disableStream,\n length,\n rangeChunkSize,\n url,\n withCredentials\n } = stream._source;\n this._contentLength = length;\n this._isStreamingSupported = !disableStream;\n this._isRangeSupported = !disableRange;\n const headers = new Headers(stream.headers);\n fetchUrl(url, headers, withCredentials, this._abortController).then(response => {\n stream._responseOrigin = getResponseOrigin(response.url);\n ensureResponseStatus(response.status, url);\n this._reader = response.body.getReader();\n const responseHeaders = response.headers;\n const {\n allowRangeRequests,\n suggestedLength\n } = validateRangeRequestCapabilities({\n responseHeaders,\n isHttp: true,\n rangeChunkSize,\n disableRange\n });\n this._isRangeSupported = allowRangeRequests;\n this._contentLength = suggestedLength || this._contentLength;\n this._filename = extractFilenameFromHeader(responseHeaders);\n if (!this._isStreamingSupported && this._isRangeSupported) {\n this.cancel(new AbortException("Streaming is disabled."));\n }\n this._headersCapability.resolve();\n }).catch(this._headersCapability.reject);\n }\n async read() {\n await this._headersCapability.promise;\n const {\n value,\n done\n } = await this._reader.read();\n if (done) {\n return {\n value,\n done\n };\n }\n this._loaded += value.byteLength;\n this._callOnProgress();\n return {\n value: fetch_stream_getArrayBuffer(value),\n done: false\n };\n }\n cancel(reason) {\n this._reader?.cancel(reason);\n this._abortController.abort();\n }\n}\nclass PDFFetchStreamRangeReader extends BasePDFStreamRangeReader {\n _abortController = new AbortController();\n _readCapability = Promise.withResolvers();\n _reader = null;\n constructor(stream, begin, end) {\n super(stream, begin, end);\n const {\n url,\n withCredentials\n } = stream._source;\n const headers = new Headers(stream.headers);\n headers.append("Range", `bytes=${begin}-${end - 1}`);\n fetchUrl(url, headers, withCredentials, this._abortController).then(response => {\n const responseOrigin = getResponseOrigin(response.url);\n ensureResponseOrigin(responseOrigin, stream._responseOrigin);\n ensureResponseStatus(response.status, url);\n this._reader = response.body.getReader();\n this._readCapability.resolve();\n }).catch(this._readCapability.reject);\n }\n async read() {\n await this._readCapability.promise;\n const {\n value,\n done\n } = await this._reader.read();\n if (done) {\n return {\n value,\n done\n };\n }\n return {\n value: fetch_stream_getArrayBuffer(value),\n done: false\n };\n }\n cancel(reason) {\n this._reader?.cancel(reason);\n this._abortController.abort();\n }\n}\n\n;// ./src/display/network.js\n\n\n\n\n\n\n\n\n\n\nconst OK_RESPONSE = 200;\nconst PARTIAL_CONTENT_RESPONSE = 206;\nfunction network_getArrayBuffer(val) {\n return typeof val !== "string" ? val : stringToBytes(val).buffer;\n}\nclass PDFNetworkStream extends BasePDFStream {\n #pendingRequests = new WeakMap();\n _responseOrigin = null;\n constructor(source) {\n super(source, PDFNetworkStreamReader, PDFNetworkStreamRangeReader);\n const {\n httpHeaders,\n url\n } = source;\n this.url = url;\n this.isHttp = /https?:/.test(url.protocol);\n this.headers = createHeaders(this.isHttp, httpHeaders);\n }\n _request(args) {\n const xhr = new XMLHttpRequest();\n const pendingRequest = {\n validateStatus: null,\n onHeadersReceived: args.onHeadersReceived,\n onDone: args.onDone,\n onError: args.onError,\n onProgress: args.onProgress\n };\n this.#pendingRequests.set(xhr, pendingRequest);\n xhr.open("GET", this.url);\n xhr.withCredentials = this._source.withCredentials;\n for (const [key, val] of this.headers) {\n xhr.setRequestHeader(key, val);\n }\n if (this.isHttp && "begin" in args && "end" in args) {\n xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);\n pendingRequest.validateStatus = status => status === PARTIAL_CONTENT_RESPONSE || status === OK_RESPONSE;\n } else {\n pendingRequest.validateStatus = status => status === OK_RESPONSE;\n }\n xhr.responseType = "arraybuffer";\n assert(args.onError, "Expected `onError` callback to be provided.");\n xhr.onerror = () => args.onError(xhr.status);\n xhr.onreadystatechange = this.#onStateChange.bind(this, xhr);\n xhr.onprogress = this.#onProgress.bind(this, xhr);\n xhr.send(null);\n return xhr;\n }\n #onProgress(xhr, evt) {\n const pendingRequest = this.#pendingRequests.get(xhr);\n pendingRequest?.onProgress?.(evt);\n }\n #onStateChange(xhr, evt) {\n const pendingRequest = this.#pendingRequests.get(xhr);\n if (!pendingRequest) {\n return;\n }\n if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {\n pendingRequest.onHeadersReceived();\n delete pendingRequest.onHeadersReceived;\n }\n if (xhr.readyState !== 4) {\n return;\n }\n if (!this.#pendingRequests.has(xhr)) {\n return;\n }\n this.#pendingRequests.delete(xhr);\n if (xhr.status === 0 && this.isHttp) {\n pendingRequest.onError(xhr.status);\n return;\n }\n const xhrStatus = xhr.status || OK_RESPONSE;\n if (!pendingRequest.validateStatus(xhrStatus)) {\n pendingRequest.onError(xhr.status);\n return;\n }\n const chunk = network_getArrayBuffer(xhr.response);\n if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {\n const rangeHeader = xhr.getResponseHeader("Content-Range");\n if (/bytes (\\d+)-(\\d+)\\/(\\d+)/.test(rangeHeader)) {\n pendingRequest.onDone(chunk);\n } else {\n warn(`Missing or invalid "Content-Range" header.`);\n pendingRequest.onError(0);\n }\n } else if (chunk) {\n pendingRequest.onDone(chunk);\n } else {\n pendingRequest.onError(xhr.status);\n }\n }\n _abortRequest(xhr) {\n if (this.#pendingRequests.has(xhr)) {\n this.#pendingRequests.delete(xhr);\n xhr.abort();\n }\n }\n getRangeReader(begin, end) {\n const reader = super.getRangeReader(begin, end);\n if (reader) {\n reader.onClosed = () => this._rangeReaders.delete(reader);\n }\n return reader;\n }\n}\nclass PDFNetworkStreamReader extends BasePDFStreamReader {\n #endRequests = endRequests.bind(this);\n _cachedChunks = [];\n _done = false;\n _requests = [];\n _storedError = null;\n constructor(stream) {\n super(stream);\n const {\n length\n } = stream._source;\n this._contentLength = length;\n this._fullRequestXhr = stream._request({\n onHeadersReceived: this.#onHeadersReceived.bind(this),\n onDone: this.#onDone.bind(this),\n onError: this.#onError.bind(this),\n onProgress: this.#onProgress.bind(this)\n });\n }\n #onHeadersReceived() {\n const stream = this._stream;\n const {\n disableRange,\n rangeChunkSize\n } = stream._source;\n const fullRequestXhr = this._fullRequestXhr;\n stream._responseOrigin = getResponseOrigin(fullRequestXhr.responseURL);\n const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders();\n const responseHeaders = new Headers(rawResponseHeaders ? rawResponseHeaders.trimStart().replace(/[^\\S ]+$/, "").split(/[\\r\\n]+/).map(x => {\n const [key, ...val] = x.split(": ");\n return [key, val.join(": ")];\n }) : []);\n const {\n allowRangeRequests,\n suggestedLength\n } = validateRangeRequestCapabilities({\n responseHeaders,\n isHttp: stream.isHttp,\n rangeChunkSize,\n disableRange\n });\n if (allowRangeRequests) {\n this._isRangeSupported = true;\n }\n this._contentLength = suggestedLength || this._contentLength;\n this._filename = extractFilenameFromHeader(responseHeaders);\n if (this._isRangeSupported) {\n stream._abortRequest(fullRequestXhr);\n }\n this._headersCapability.resolve();\n }\n #onDone(chunk) {\n if (this._requests.length > 0) {\n const capability = this._requests.shift();\n capability.resolve({\n value: chunk,\n done: false\n });\n } else {\n this._cachedChunks.push(chunk);\n }\n this._done = true;\n if (this._cachedChunks.length === 0) {\n this.#endRequests();\n }\n }\n #onError(status) {\n this._storedError = createResponseError(status, this._stream.url);\n this._headersCapability.reject(this._storedError);\n for (const capability of this._requests) {\n capability.reject(this._storedError);\n }\n this._requests.length = 0;\n this._cachedChunks.length = 0;\n }\n #onProgress(evt) {\n this.onProgress?.({\n loaded: evt.loaded,\n total: evt.lengthComputable ? evt.total : this._contentLength\n });\n }\n async read() {\n await this._headersCapability.promise;\n if (this._storedError) {\n throw this._storedError;\n }\n if (this._cachedChunks.length > 0) {\n const chunk = this._cachedChunks.shift();\n return {\n value: chunk,\n done: false\n };\n }\n if (this._done) {\n return {\n value: undefined,\n done: true\n };\n }\n const capability = Promise.withResolvers();\n this._requests.push(capability);\n return capability.promise;\n }\n cancel(reason) {\n this._done = true;\n this._headersCapability.reject(reason);\n this.#endRequests();\n this._stream._abortRequest(this._fullRequestXhr);\n this._fullRequestXhr = null;\n }\n}\nclass PDFNetworkStreamRangeReader extends BasePDFStreamRangeReader {\n #endRequests = endRequests.bind(this);\n onClosed = null;\n _done = false;\n _queuedChunk = null;\n _requests = [];\n _storedError = null;\n constructor(stream, begin, end) {\n super(stream, begin, end);\n this._requestXhr = stream._request({\n begin,\n end,\n onHeadersReceived: this.#onHeadersReceived.bind(this),\n onDone: this.#onDone.bind(this),\n onError: this.#onError.bind(this),\n onProgress: null\n });\n }\n #onHeadersReceived() {\n const responseOrigin = getResponseOrigin(this._requestXhr?.responseURL);\n try {\n ensureResponseOrigin(responseOrigin, this._stream._responseOrigin);\n } catch (ex) {\n this._storedError = ex;\n this.#onError(0);\n }\n }\n #onDone(chunk) {\n if (this._requests.length > 0) {\n const capability = this._requests.shift();\n capability.resolve({\n value: chunk,\n done: false\n });\n } else {\n this._queuedChunk = chunk;\n }\n this._done = true;\n this.#endRequests();\n this.onClosed?.();\n }\n #onError(status) {\n this._storedError ??= createResponseError(status, this._stream.url);\n for (const capability of this._requests) {\n capability.reject(this._storedError);\n }\n this._requests.length = 0;\n this._queuedChunk = null;\n }\n async read() {\n if (this._storedError) {\n throw this._storedError;\n }\n if (this._queuedChunk !== null) {\n const chunk = this._queuedChunk;\n this._queuedChunk = null;\n return {\n value: chunk,\n done: false\n };\n }\n if (this._done) {\n return {\n value: undefined,\n done: true\n };\n }\n const capability = Promise.withResolvers();\n this._requests.push(capability);\n return capability.promise;\n }\n cancel(reason) {\n this._done = true;\n this.#endRequests();\n this._stream._abortRequest(this._requestXhr);\n this.onClosed?.();\n }\n}\n\n;// ./src/display/node_stream.js\n\n\n\n\n\nfunction getReadableStream(readStream) {\n const {\n Readable\n } = process.getBuiltinModule("stream");\n if (typeof Readable.toWeb === "function") {\n return Readable.toWeb(readStream);\n }\n const require = process.getBuiltinModule("module").createRequire(import.meta.url);\n const polyfill = require("node-readable-to-web-readable-stream");\n return polyfill.makeDefaultReadableStreamFromNodeReadable(readStream);\n}\nclass PDFNodeStream extends BasePDFStream {\n constructor(source) {\n super(source, PDFNodeStreamReader, PDFNodeStreamRangeReader);\n const {\n url\n } = source;\n assert(url.protocol === "file:", "PDFNodeStream only supports file:// URLs.");\n }\n}\nclass PDFNodeStreamReader extends BasePDFStreamReader {\n _reader = null;\n constructor(stream) {\n super(stream);\n const {\n disableRange,\n disableStream,\n length,\n rangeChunkSize,\n url\n } = stream._source;\n this._contentLength = length;\n this._isStreamingSupported = !disableStream;\n this._isRangeSupported = !disableRange;\n const fs = process.getBuiltinModule("fs");\n fs.promises.lstat(url).then(stat => {\n const readStream = fs.createReadStream(url);\n const readableStream = getReadableStream(readStream);\n this._reader = readableStream.getReader();\n const {\n size\n } = stat;\n if (size <= 2 * rangeChunkSize) {\n this._isRangeSupported = false;\n }\n this._contentLength = size;\n if (!this._isStreamingSupported && this._isRangeSupported) {\n this.cancel(new AbortException("Streaming is disabled."));\n }\n this._headersCapability.resolve();\n }).catch(error => {\n if (error.code === "ENOENT") {\n error = createResponseError(0, url);\n }\n this._headersCapability.reject(error);\n });\n }\n async read() {\n await this._headersCapability.promise;\n const {\n value,\n done\n } = await this._reader.read();\n if (done) {\n return {\n value,\n done\n };\n }\n this._loaded += value.byteLength;\n this._callOnProgress();\n return {\n value: fetch_stream_getArrayBuffer(value),\n done: false\n };\n }\n cancel(reason) {\n this._reader?.cancel(reason);\n }\n}\nclass PDFNodeStreamRangeReader extends BasePDFStreamRangeReader {\n _readCapability = Promise.withResolvers();\n _reader = null;\n constructor(stream, begin, end) {\n super(stream, begin, end);\n const {\n url\n } = stream._source;\n const fs = process.getBuiltinModule("fs");\n try {\n const readStream = fs.createReadStream(url, {\n start: begin,\n end: end - 1\n });\n const readableStream = getReadableStream(readStream);\n this._reader = readableStream.getReader();\n this._readCapability.resolve();\n } catch (error) {\n this._readCapability.reject(error);\n }\n }\n async read() {\n await this._readCapability.promise;\n const {\n value,\n done\n } = await this._reader.read();\n if (done) {\n return {\n value,\n done\n };\n }\n return {\n value: fetch_stream_getArrayBuffer(value),\n done: false\n };\n }\n cancel(reason) {\n this._reader?.cancel(reason);\n }\n}\n\n;// ./src/display/pdf_objects.js\n\n\n\nconst INITIAL_DATA = Symbol("INITIAL_DATA");\nconst dataObj = () => ({\n ...Promise.withResolvers(),\n data: INITIAL_DATA\n});\nclass PDFObjects {\n #objs = new Map();\n #ensureObj(objId) {\n return this.#objs.getOrInsertComputed(objId, dataObj);\n }\n get(objId, callback = null) {\n if (callback) {\n const obj = this.#ensureObj(objId);\n obj.promise.then(() => callback(obj.data));\n return null;\n }\n const obj = this.#objs.get(objId);\n if (!obj || obj.data === INITIAL_DATA) {\n throw new Error(`Requesting object that isn\'t resolved yet ${objId}.`);\n }\n return obj.data;\n }\n has(objId) {\n const obj = this.#objs.get(objId);\n return !!obj && obj.data !== INITIAL_DATA;\n }\n delete(objId) {\n const obj = this.#objs.get(objId);\n if (!obj || obj.data === INITIAL_DATA) {\n return false;\n }\n this.#objs.delete(objId);\n return true;\n }\n resolve(objId, data = null) {\n const obj = this.#ensureObj(objId);\n obj.data = data;\n obj.resolve();\n }\n clear() {\n for (const {\n data\n } of this.#objs.values()) {\n data?.bitmap?.close();\n }\n this.#objs.clear();\n }\n *[Symbol.iterator]() {\n for (const [objId, {\n data\n }] of this.#objs) {\n if (data !== INITIAL_DATA) {\n yield [objId, data];\n }\n }\n }\n}\n\n;// ./src/display/text_layer.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst MAX_TEXT_DIVS_TO_RENDER = 100000;\nconst DEFAULT_FONT_SIZE = 30;\nclass TextLayer {\n #capability = Promise.withResolvers();\n #container = null;\n #disableProcessItems = false;\n #fontInspectorEnabled = !!globalThis.FontInspector?.enabled;\n #lang = null;\n #layoutTextParams = null;\n #pageHeight = 0;\n #pageWidth = 0;\n #reader = null;\n #rootContainer = null;\n #rotation = 0;\n #scale = 0;\n #styleCache = Object.create(null);\n #textContentItemsStr = [];\n #textContentSource = null;\n #textDivs = [];\n #textDivProperties = new WeakMap();\n #transform = null;\n static #ascentCache = new Map();\n static #canvasContexts = new Map();\n static #canvasCtxFonts = new WeakMap();\n static #minFontSize = null;\n static #pendingTextLayers = new Set();\n constructor({\n textContentSource,\n container,\n viewport\n }) {\n if (textContentSource instanceof ReadableStream) {\n this.#textContentSource = textContentSource;\n } else if (typeof textContentSource === "object") {\n this.#textContentSource = new ReadableStream({\n start(controller) {\n controller.enqueue(textContentSource);\n controller.close();\n }\n });\n } else {\n throw new Error(\'No "textContentSource" parameter specified.\');\n }\n this.#container = this.#rootContainer = container;\n this.#scale = viewport.scale * OutputScale.pixelRatio;\n this.#rotation = viewport.rotation;\n this.#layoutTextParams = {\n div: null,\n properties: null,\n ctx: null\n };\n const {\n pageWidth,\n pageHeight,\n pageX,\n pageY\n } = viewport.rawDims;\n this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];\n this.#pageWidth = pageWidth;\n this.#pageHeight = pageHeight;\n TextLayer.#ensureMinFontSizeComputed();\n container.style.setProperty("--min-font-size", TextLayer.#minFontSize);\n setLayerDimensions(container, viewport);\n this.#capability.promise.finally(() => {\n TextLayer.#pendingTextLayers.delete(this);\n this.#layoutTextParams = null;\n this.#styleCache = null;\n }).catch(() => {});\n }\n static get fontFamilyMap() {\n const {\n isWindows,\n isFirefox\n } = FeatureTest.platform;\n return shadow(this, "fontFamilyMap", new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]]));\n }\n render() {\n const pump = () => {\n this.#reader.read().then(({\n value,\n done\n }) => {\n if (done) {\n this.#capability.resolve();\n return;\n }\n this.#lang ??= value.lang;\n Object.assign(this.#styleCache, value.styles);\n this.#processItems(value.items);\n pump();\n }, this.#capability.reject);\n };\n this.#reader = this.#textContentSource.getReader();\n TextLayer.#pendingTextLayers.add(this);\n pump();\n return this.#capability.promise;\n }\n update({\n viewport,\n onBefore = null\n }) {\n const scale = viewport.scale * OutputScale.pixelRatio;\n const rotation = viewport.rotation;\n if (rotation !== this.#rotation) {\n onBefore?.();\n this.#rotation = rotation;\n setLayerDimensions(this.#rootContainer, {\n rotation\n });\n }\n if (scale !== this.#scale) {\n onBefore?.();\n this.#scale = scale;\n const params = {\n div: null,\n properties: null,\n ctx: TextLayer.#getCtx(this.#lang)\n };\n for (const div of this.#textDivs) {\n params.properties = this.#textDivProperties.get(div);\n params.div = div;\n this.#layout(params);\n }\n }\n }\n cancel() {\n const abortEx = new AbortException("TextLayer task cancelled.");\n this.#reader?.cancel(abortEx).catch(() => {});\n this.#reader = null;\n this.#capability.reject(abortEx);\n }\n get textDivs() {\n return this.#textDivs;\n }\n get textContentItemsStr() {\n return this.#textContentItemsStr;\n }\n #processItems(items) {\n if (this.#disableProcessItems) {\n return;\n }\n this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang);\n const textDivs = this.#textDivs,\n textContentItemsStr = this.#textContentItemsStr;\n for (const item of items) {\n if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {\n warn("Ignoring additional textDivs for performance reasons.");\n this.#disableProcessItems = true;\n return;\n }\n if (item.str === undefined) {\n if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {\n const parent = this.#container;\n this.#container = document.createElement("span");\n this.#container.classList.add("markedContent");\n if (item.id) {\n this.#container.setAttribute("id", `${item.id}`);\n }\n if (item.tag === "Artifact") {\n this.#container.ariaHidden = true;\n }\n parent.append(this.#container);\n } else if (item.type === "endMarkedContent") {\n this.#container = this.#container.parentNode;\n }\n continue;\n }\n textContentItemsStr.push(item.str);\n this.#appendText(item);\n }\n }\n #appendText(geom) {\n const textDiv = document.createElement("span");\n const textDivProperties = {\n angle: 0,\n canvasWidth: 0,\n hasText: geom.str !== "",\n hasEOL: geom.hasEOL,\n fontSize: 0\n };\n this.#textDivs.push(textDiv);\n const tx = Util.transform(this.#transform, geom.transform);\n let angle = Math.atan2(tx[1], tx[0]);\n const style = this.#styleCache[geom.fontName];\n if (style.vertical) {\n angle += Math.PI / 2;\n }\n let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily;\n fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily;\n const fontHeight = Math.hypot(tx[2], tx[3]);\n const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, style, this.#lang);\n let left, top;\n if (angle === 0) {\n left = tx[4];\n top = tx[5] - fontAscent;\n } else {\n left = tx[4] + fontAscent * Math.sin(angle);\n top = tx[5] - fontAscent * Math.cos(angle);\n }\n const divStyle = textDiv.style;\n divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`;\n divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`;\n divStyle.setProperty("--font-height", `${fontHeight.toFixed(2)}px`);\n divStyle.fontFamily = fontFamily;\n textDivProperties.fontSize = fontHeight;\n textDiv.setAttribute("role", "presentation");\n textDiv.textContent = geom.str;\n textDiv.dir = geom.dir;\n if (this.#fontInspectorEnabled) {\n textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName;\n }\n if (angle !== 0) {\n textDivProperties.angle = angle * (180 / Math.PI);\n }\n let shouldScaleText = false;\n if (geom.str.length > 1) {\n shouldScaleText = true;\n } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {\n const absScaleX = Math.abs(geom.transform[0]),\n absScaleY = Math.abs(geom.transform[3]);\n if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {\n shouldScaleText = true;\n }\n }\n if (shouldScaleText) {\n textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;\n }\n this.#textDivProperties.set(textDiv, textDivProperties);\n this.#layoutTextParams.div = textDiv;\n this.#layoutTextParams.properties = textDivProperties;\n this.#layout(this.#layoutTextParams);\n if (textDivProperties.hasText) {\n this.#container.append(textDiv);\n }\n if (textDivProperties.hasEOL) {\n const br = document.createElement("br");\n br.setAttribute("role", "presentation");\n this.#container.append(br);\n }\n }\n #layout(params) {\n const {\n div,\n properties,\n ctx\n } = params;\n const {\n style\n } = div;\n if (properties.canvasWidth !== 0 && properties.hasText) {\n const {\n fontFamily\n } = style;\n const {\n canvasWidth,\n fontSize\n } = properties;\n TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily);\n const {\n width\n } = ctx.measureText(div.textContent);\n if (width > 0) {\n style.setProperty("--scale-x", canvasWidth * this.#scale / width);\n }\n }\n if (properties.angle !== 0) {\n style.setProperty("--rotate", `${properties.angle}deg`);\n }\n }\n static cleanup() {\n if (this.#pendingTextLayers.size > 0) {\n return;\n }\n this.#ascentCache.clear();\n for (const {\n canvas\n } of this.#canvasContexts.values()) {\n canvas.remove();\n }\n this.#canvasContexts.clear();\n }\n static #getCtx(lang = null) {\n let ctx = this.#canvasContexts.get(lang ||= "");\n if (!ctx) {\n const canvas = document.createElement("canvas");\n canvas.className = "hiddenCanvasElement";\n canvas.lang = lang;\n document.body.append(canvas);\n ctx = canvas.getContext("2d", {\n alpha: false,\n willReadFrequently: true\n });\n this.#canvasContexts.set(lang, ctx);\n this.#canvasCtxFonts.set(ctx, {\n size: 0,\n family: ""\n });\n }\n return ctx;\n }\n static #ensureCtxFont(ctx, size, family) {\n const cached = this.#canvasCtxFonts.get(ctx);\n if (size === cached.size && family === cached.family) {\n return;\n }\n ctx.font = `${size}px ${family}`;\n cached.size = size;\n cached.family = family;\n }\n static #ensureMinFontSizeComputed() {\n if (this.#minFontSize !== null) {\n return;\n }\n const div = document.createElement("div");\n div.style.opacity = 0;\n div.style.lineHeight = 1;\n div.style.fontSize = "1px";\n div.style.position = "absolute";\n div.textContent = "X";\n document.body.append(div);\n this.#minFontSize = div.getBoundingClientRect().height;\n div.remove();\n }\n static #getAscent(fontFamily, style, lang) {\n const cachedAscent = this.#ascentCache.get(fontFamily);\n if (cachedAscent) {\n return cachedAscent;\n }\n const ctx = this.#getCtx(lang);\n ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;\n this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily);\n const metrics = ctx.measureText("");\n const ascent = metrics.fontBoundingBoxAscent;\n const descent = Math.abs(metrics.fontBoundingBoxDescent);\n ctx.canvas.width = ctx.canvas.height = 0;\n let ratio = 0.8;\n if (ascent) {\n ratio = ascent / (ascent + descent);\n } else {\n if (FeatureTest.platform.isFirefox) {\n warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference " + "in `about:config` to improve TextLayer rendering.");\n }\n if (style.ascent) {\n ratio = style.ascent;\n } else if (style.descent) {\n ratio = 1 + style.descent;\n }\n }\n this.#ascentCache.set(fontFamily, ratio);\n return ratio;\n }\n}\n\n;// ./src/display/api.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst RENDERING_CANCELLED_TIMEOUT = 100;\nfunction getDocument(src = {}) {\n if (typeof src === "string" || src instanceof URL) {\n src = {\n url: src\n };\n } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {\n src = {\n data: src\n };\n }\n const task = new PDFDocumentLoadingTask();\n const {\n docId\n } = task;\n const url = src.url ? getUrlProp(src.url) : null;\n const data = src.data ? getDataProp(src.data) : null;\n const httpHeaders = src.httpHeaders || null;\n const withCredentials = src.withCredentials === true;\n const password = src.password ?? null;\n const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;\n const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : 2 ** 16;\n let worker = src.worker instanceof PDFWorker ? src.worker : null;\n const verbosity = src.verbosity;\n const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null;\n const cMapUrl = getFactoryUrlProp(src.cMapUrl);\n const cMapPacked = src.cMapPacked !== false;\n const CMapReaderFactory = src.CMapReaderFactory || (isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory);\n const iccUrl = getFactoryUrlProp(src.iccUrl);\n const standardFontDataUrl = getFactoryUrlProp(src.standardFontDataUrl);\n const StandardFontDataFactory = src.StandardFontDataFactory || (isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory);\n const wasmUrl = getFactoryUrlProp(src.wasmUrl);\n const WasmFactory = src.WasmFactory || (isNodeJS ? NodeWasmFactory : DOMWasmFactory);\n const ignoreErrors = src.stopAtErrors !== true;\n const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;\n const isEvalSupported = src.isEvalSupported !== false;\n const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS;\n const isImageDecoderSupported = typeof src.isImageDecoderSupported === "boolean" ? src.isImageDecoderSupported : !isNodeJS && (FeatureTest.platform.isFirefox || !globalThis.chrome);\n const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;\n const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS;\n const fontExtraProperties = src.fontExtraProperties === true;\n const enableXfa = src.enableXfa === true;\n const ownerDocument = src.ownerDocument || globalThis.document;\n const disableRange = src.disableRange === true;\n const disableStream = src.disableStream === true;\n const disableAutoFetch = src.disableAutoFetch === true;\n const pdfBug = src.pdfBug === true;\n const CanvasFactory = src.CanvasFactory || (isNodeJS ? NodeCanvasFactory : DOMCanvasFactory);\n const FilterFactory = src.FilterFactory || (isNodeJS ? NodeFilterFactory : DOMFilterFactory);\n const enableHWA = src.enableHWA === true;\n const useWasm = src.useWasm !== false;\n const pagesMapper = src.pagesMapper || new PagesMapper();\n const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;\n const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace;\n const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : !!(CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && WasmFactory === DOMWasmFactory && cMapUrl && standardFontDataUrl && wasmUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI) && isValidFetchUrl(wasmUrl, document.baseURI));\n const styleElement = null;\n setVerbosityLevel(verbosity);\n const transportFactory = {\n canvasFactory: new CanvasFactory({\n ownerDocument,\n enableHWA\n }),\n filterFactory: new FilterFactory({\n docId,\n ownerDocument\n }),\n cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({\n baseUrl: cMapUrl,\n isCompressed: cMapPacked\n }),\n standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({\n baseUrl: standardFontDataUrl\n }),\n wasmFactory: useWorkerFetch ? null : new WasmFactory({\n baseUrl: wasmUrl\n })\n };\n if (!worker) {\n worker = PDFWorker.create({\n verbosity,\n port: GlobalWorkerOptions.workerPort\n });\n task._worker = worker;\n }\n const docParams = {\n docId,\n apiVersion: "5.5.207",\n data,\n password,\n disableAutoFetch,\n rangeChunkSize,\n length,\n docBaseUrl,\n enableXfa,\n evaluatorOptions: {\n maxImageSize,\n disableFontFace,\n ignoreErrors,\n isEvalSupported,\n isOffscreenCanvasSupported,\n isImageDecoderSupported,\n canvasMaxAreaInBytes,\n fontExtraProperties,\n useSystemFonts,\n useWasm,\n useWorkerFetch,\n cMapUrl,\n iccUrl,\n standardFontDataUrl,\n wasmUrl\n }\n };\n const transportParams = {\n ownerDocument,\n pdfBug,\n styleElement,\n enableHWA,\n loadingParams: {\n disableAutoFetch,\n enableXfa\n }\n };\n worker.promise.then(function () {\n if (task.destroyed) {\n throw new Error("Loading aborted");\n }\n if (worker.destroyed) {\n throw new Error("Worker was destroyed");\n }\n const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null);\n let networkStream;\n if (rangeTransport) {\n networkStream = new PDFDataTransportStream({\n pdfDataRangeTransport: rangeTransport,\n disableRange,\n disableStream\n });\n } else if (!data) {\n if (!url) {\n throw new Error("getDocument - no `url` parameter provided.");\n }\n const NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : isNodeJS ? PDFNodeStream : PDFNetworkStream;\n networkStream = new NetworkStream({\n url,\n length,\n httpHeaders,\n withCredentials,\n rangeChunkSize,\n disableRange,\n disableStream\n });\n }\n return workerIdPromise.then(workerId => {\n if (task.destroyed) {\n throw new Error("Loading aborted");\n }\n if (worker.destroyed) {\n throw new Error("Worker was destroyed");\n }\n const messageHandler = new MessageHandler(docId, workerId, worker.port);\n const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory, pagesMapper);\n task._transport = transport;\n messageHandler.send("Ready", null);\n });\n }).catch(task._capability.reject);\n return task;\n}\nclass PDFDocumentLoadingTask {\n static #docId = 0;\n _capability = Promise.withResolvers();\n _transport = null;\n _worker = null;\n docId = `d${PDFDocumentLoadingTask.#docId++}`;\n destroyed = false;\n onPassword = null;\n onProgress = null;\n get promise() {\n return this._capability.promise;\n }\n async destroy() {\n this.destroyed = true;\n try {\n if (this._worker?.port) {\n this._worker._pendingDestroy = true;\n }\n await this._transport?.destroy();\n } catch (ex) {\n if (this._worker?.port) {\n delete this._worker._pendingDestroy;\n }\n throw ex;\n }\n this._transport = null;\n this._worker?.destroy();\n this._worker = null;\n }\n async getData() {\n return this._transport.getData();\n }\n}\nclass PDFDataRangeTransport {\n #capability = Promise.withResolvers();\n #progressiveDoneListeners = [];\n #progressiveReadListeners = [];\n #rangeListeners = [];\n constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {\n this.length = length;\n this.initialData = initialData;\n this.progressiveDone = progressiveDone;\n this.contentDispositionFilename = contentDispositionFilename;\n Object.defineProperty(this, "onDataProgress", {\n value: () => {\n deprecated("`PDFDataRangeTransport.prototype.onDataProgress` - method was " + "removed, since loading progress is now reported automatically " + "through the `PDFDataTransportStream` class (and related code).");\n }\n });\n }\n addRangeListener(listener) {\n this.#rangeListeners.push(listener);\n }\n addProgressiveReadListener(listener) {\n this.#progressiveReadListeners.push(listener);\n }\n addProgressiveDoneListener(listener) {\n this.#progressiveDoneListeners.push(listener);\n }\n onDataRange(begin, chunk) {\n for (const listener of this.#rangeListeners) {\n listener(begin, chunk);\n }\n }\n onDataProgressiveRead(chunk) {\n this.#capability.promise.then(() => {\n for (const listener of this.#progressiveReadListeners) {\n listener(chunk);\n }\n });\n }\n onDataProgressiveDone() {\n this.#capability.promise.then(() => {\n for (const listener of this.#progressiveDoneListeners) {\n listener();\n }\n });\n }\n transportReady() {\n this.#capability.resolve();\n }\n requestDataRange(begin, end) {\n unreachable("Abstract method PDFDataRangeTransport.requestDataRange");\n }\n abort() {}\n}\nclass PDFDocumentProxy {\n constructor(pdfInfo, transport) {\n this._pdfInfo = pdfInfo;\n this._transport = transport;\n }\n get pagesMapper() {\n return this._transport.pagesMapper;\n }\n get annotationStorage() {\n return this._transport.annotationStorage;\n }\n get canvasFactory() {\n return this._transport.canvasFactory;\n }\n get filterFactory() {\n return this._transport.filterFactory;\n }\n get numPages() {\n return this._pdfInfo.numPages;\n }\n get fingerprints() {\n return this._pdfInfo.fingerprints;\n }\n get isPureXfa() {\n return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);\n }\n get allXfaHtml() {\n return this._transport._htmlForXfa;\n }\n getPage(pageNumber) {\n return this._transport.getPage(pageNumber);\n }\n getPageIndex(ref) {\n return this._transport.getPageIndex(ref);\n }\n getDestinations() {\n return this._transport.getDestinations();\n }\n getDestination(id) {\n return this._transport.getDestination(id);\n }\n getPageLabels() {\n return this._transport.getPageLabels();\n }\n getPageLayout() {\n return this._transport.getPageLayout();\n }\n getPageMode() {\n return this._transport.getPageMode();\n }\n getViewerPreferences() {\n return this._transport.getViewerPreferences();\n }\n getOpenAction() {\n return this._transport.getOpenAction();\n }\n getAttachments() {\n return this._transport.getAttachments();\n }\n getAnnotationsByType(types, pageIndexesToSkip) {\n return this._transport.getAnnotationsByType(types, pageIndexesToSkip);\n }\n getJSActions() {\n return this._transport.getDocJSActions();\n }\n getOutline() {\n return this._transport.getOutline();\n }\n getOptionalContentConfig({\n intent = "display"\n } = {}) {\n const {\n renderingIntent\n } = this._transport.getRenderingIntent(intent);\n return this._transport.getOptionalContentConfig(renderingIntent);\n }\n getPermissions() {\n return this._transport.getPermissions();\n }\n getMetadata() {\n return this._transport.getMetadata();\n }\n getMarkInfo() {\n return this._transport.getMarkInfo();\n }\n getData() {\n return this._transport.getData();\n }\n saveDocument() {\n return this._transport.saveDocument();\n }\n extractPages(pageInfos) {\n return this._transport.extractPages(pageInfos);\n }\n getDownloadInfo() {\n return this._transport.downloadInfoCapability.promise;\n }\n cleanup(keepLoadedFonts = false) {\n return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);\n }\n destroy() {\n return this.loadingTask.destroy();\n }\n cachedPageNumber(ref) {\n return this._transport.cachedPageNumber(ref);\n }\n get loadingParams() {\n return this._transport.loadingParams;\n }\n get loadingTask() {\n return this._transport.loadingTask;\n }\n getFieldObjects() {\n return this._transport.getFieldObjects();\n }\n hasJSActions() {\n return this._transport.hasJSActions();\n }\n getCalculationOrderIds() {\n return this._transport.getCalculationOrderIds();\n }\n}\nclass PDFPageProxy {\n #pendingCleanup = false;\n #pagesMapper = null;\n constructor(pageIndex, pageInfo, transport, pagesMapper, pdfBug = false) {\n this._pageIndex = pageIndex;\n this._pageInfo = pageInfo;\n this._transport = transport;\n this._stats = pdfBug ? new StatTimer() : null;\n this._pdfBug = pdfBug;\n this.commonObjs = transport.commonObjs;\n this.objs = new PDFObjects();\n this._intentStates = new Map();\n this.destroyed = false;\n this.recordedBBoxes = null;\n this.#pagesMapper = pagesMapper;\n }\n get pageNumber() {\n return this._pageIndex + 1;\n }\n set pageNumber(value) {\n this._pageIndex = value - 1;\n }\n get rotate() {\n return this._pageInfo.rotate;\n }\n get ref() {\n return this._pageInfo.ref;\n }\n get userUnit() {\n return this._pageInfo.userUnit;\n }\n get view() {\n return this._pageInfo.view;\n }\n getViewport({\n scale,\n rotation = this.rotate,\n offsetX = 0,\n offsetY = 0,\n dontFlip = false\n } = {}) {\n return new PageViewport({\n viewBox: this.view,\n userUnit: this.userUnit,\n scale,\n rotation,\n offsetX,\n offsetY,\n dontFlip\n });\n }\n getAnnotations({\n intent = "display"\n } = {}) {\n const {\n renderingIntent\n } = this._transport.getRenderingIntent(intent);\n return this._transport.getAnnotations(this._pageIndex, renderingIntent);\n }\n getJSActions() {\n return this._transport.getPageJSActions(this._pageIndex);\n }\n get filterFactory() {\n return this._transport.filterFactory;\n }\n get isPureXfa() {\n return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);\n }\n async getXfa() {\n return this._transport._htmlForXfa?.children[this._pageIndex] || null;\n }\n render({\n canvasContext,\n canvas = canvasContext.canvas,\n viewport,\n intent = "display",\n annotationMode = AnnotationMode.ENABLE,\n transform = null,\n background = null,\n optionalContentConfigPromise = null,\n annotationCanvasMap = null,\n pageColors = null,\n printAnnotationStorage = null,\n isEditing = false,\n recordOperations = false,\n operationsFilter = null\n }) {\n this._stats?.time("Overall");\n const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing);\n const {\n renderingIntent,\n cacheKey\n } = intentArgs;\n this.#pendingCleanup = false;\n optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent);\n const intentState = this._intentStates.getOrInsertComputed(cacheKey, makeObj);\n if (intentState.streamReaderCancelTimeout) {\n clearTimeout(intentState.streamReaderCancelTimeout);\n intentState.streamReaderCancelTimeout = null;\n }\n const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);\n if (!intentState.displayReadyCapability) {\n intentState.displayReadyCapability = Promise.withResolvers();\n intentState.operatorList = {\n fnArray: [],\n argsArray: [],\n lastChunk: false,\n separateAnnots: null\n };\n this._stats?.time("Page Request");\n this._pumpOperatorList(intentArgs);\n }\n const recordForDebugger = Boolean(this._pdfBug && globalThis.StepperManager?.enabled);\n const shouldRecordOperations = !this.recordedBBoxes && (recordOperations || recordForDebugger);\n const complete = error => {\n intentState.renderTasks.delete(internalRenderTask);\n if (shouldRecordOperations) {\n const recordedBBoxes = internalRenderTask.gfx?.dependencyTracker.take();\n if (recordedBBoxes) {\n if (internalRenderTask.stepper) {\n internalRenderTask.stepper.setOperatorBBoxes(recordedBBoxes, internalRenderTask.gfx.dependencyTracker.takeDebugMetadata());\n }\n if (recordOperations) {\n this.recordedBBoxes = recordedBBoxes;\n }\n }\n }\n if (intentPrint) {\n this.#pendingCleanup = true;\n }\n this.#tryCleanup();\n if (error) {\n internalRenderTask.capability.reject(error);\n this._abortOperatorList({\n intentState,\n reason: error instanceof Error ? error : new Error(error)\n });\n } else {\n internalRenderTask.capability.resolve();\n }\n if (this._stats) {\n this._stats.timeEnd("Rendering");\n this._stats.timeEnd("Overall");\n if (globalThis.Stats?.enabled) {\n globalThis.Stats.add(this.pageNumber, this._stats);\n }\n }\n };\n const internalRenderTask = new InternalRenderTask({\n callback: complete,\n params: {\n canvas,\n canvasContext,\n dependencyTracker: shouldRecordOperations ? new CanvasDependencyTracker(canvas, intentState.operatorList.length, recordForDebugger) : null,\n viewport,\n transform,\n background\n },\n objs: this.objs,\n commonObjs: this.commonObjs,\n annotationCanvasMap,\n operatorList: intentState.operatorList,\n pageIndex: this._pageIndex,\n canvasFactory: this._transport.canvasFactory,\n filterFactory: this._transport.filterFactory,\n useRequestAnimationFrame: !intentPrint,\n pdfBug: this._pdfBug,\n pageColors,\n enableHWA: this._transport.enableHWA,\n operationsFilter\n });\n (intentState.renderTasks ||= new Set()).add(internalRenderTask);\n const renderTask = internalRenderTask.task;\n Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {\n if (this.destroyed) {\n complete();\n return;\n }\n this._stats?.time("Rendering");\n if (!(optionalContentConfig.renderingIntent & renderingIntent)) {\n throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods.");\n }\n internalRenderTask.initializeGraphics({\n transparency,\n optionalContentConfig\n });\n internalRenderTask.operatorListChanged();\n }).catch(complete);\n return renderTask;\n }\n getOperatorList({\n intent = "display",\n annotationMode = AnnotationMode.ENABLE,\n printAnnotationStorage = null,\n isEditing = false\n } = {}) {\n function operatorListChanged() {\n if (intentState.operatorList.lastChunk) {\n intentState.opListReadCapability.resolve(intentState.operatorList);\n intentState.renderTasks.delete(opListTask);\n }\n }\n const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true);\n const intentState = this._intentStates.getOrInsertComputed(intentArgs.cacheKey, makeObj);\n let opListTask;\n if (!intentState.opListReadCapability) {\n opListTask = Object.create(null);\n opListTask.operatorListChanged = operatorListChanged;\n intentState.opListReadCapability = Promise.withResolvers();\n (intentState.renderTasks ||= new Set()).add(opListTask);\n intentState.operatorList = {\n fnArray: [],\n argsArray: [],\n lastChunk: false,\n separateAnnots: null\n };\n this._stats?.time("Page Request");\n this._pumpOperatorList(intentArgs);\n }\n return intentState.opListReadCapability.promise;\n }\n streamTextContent({\n includeMarkedContent = false,\n disableNormalization = false\n } = {}) {\n const TEXT_CONTENT_CHUNK_SIZE = 100;\n return this._transport.messageHandler.sendWithStream("GetTextContent", {\n pageId: this.#pagesMapper.getPageId(this._pageIndex + 1) - 1,\n pageIndex: this._pageIndex,\n includeMarkedContent: includeMarkedContent === true,\n disableNormalization: disableNormalization === true\n }, {\n highWaterMark: TEXT_CONTENT_CHUNK_SIZE,\n size(textContent) {\n return textContent.items.length;\n }\n });\n }\n async getTextContent(params = {}) {\n if (this._transport._htmlForXfa) {\n return this.getXfa().then(xfa => XfaText.textContent(xfa));\n }\n const readableStream = this.streamTextContent(params);\n const textContent = {\n items: [],\n styles: Object.create(null),\n lang: null\n };\n for await (const value of readableStream) {\n textContent.lang ??= value.lang;\n Object.assign(textContent.styles, value.styles);\n textContent.items.push(...value.items);\n }\n return textContent;\n }\n getStructTree() {\n return this._transport.getStructTree(this._pageIndex);\n }\n _destroy() {\n this.destroyed = true;\n const waitOn = [];\n for (const intentState of this._intentStates.values()) {\n this._abortOperatorList({\n intentState,\n reason: new Error("Page was destroyed."),\n force: true\n });\n if (intentState.opListReadCapability) {\n continue;\n }\n for (const internalRenderTask of intentState.renderTasks) {\n waitOn.push(internalRenderTask.completed);\n internalRenderTask.cancel();\n }\n }\n this.objs.clear();\n this.#pendingCleanup = false;\n return Promise.all(waitOn);\n }\n cleanup(resetStats = false) {\n this.#pendingCleanup = true;\n const success = this.#tryCleanup();\n if (resetStats && success) {\n this._stats &&= new StatTimer();\n }\n return success;\n }\n #tryCleanup() {\n if (!this.#pendingCleanup || this.destroyed) {\n return false;\n }\n for (const {\n renderTasks,\n operatorList\n } of this._intentStates.values()) {\n if (renderTasks.size > 0 || !operatorList.lastChunk) {\n return false;\n }\n }\n this._intentStates.clear();\n this.objs.clear();\n this.#pendingCleanup = false;\n return true;\n }\n _startRenderPage(transparency, cacheKey) {\n const intentState = this._intentStates.get(cacheKey);\n if (!intentState) {\n return;\n }\n this._stats?.timeEnd("Page Request");\n intentState.displayReadyCapability?.resolve(transparency);\n }\n _renderPageChunk(operatorListChunk, intentState) {\n for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {\n intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);\n intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);\n }\n intentState.operatorList.lastChunk = operatorListChunk.lastChunk;\n intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;\n for (const internalRenderTask of intentState.renderTasks) {\n internalRenderTask.operatorListChanged();\n }\n if (operatorListChunk.lastChunk) {\n this.#tryCleanup();\n }\n }\n _pumpOperatorList({\n renderingIntent,\n cacheKey,\n annotationStorageSerializable,\n modifiedIds\n }) {\n const {\n map,\n transfer\n } = annotationStorageSerializable;\n const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {\n pageId: this.#pagesMapper.getPageId(this._pageIndex + 1) - 1,\n pageIndex: this._pageIndex,\n intent: renderingIntent,\n cacheKey,\n annotationStorage: map,\n modifiedIds\n }, undefined, transfer);\n const reader = readableStream.getReader();\n const intentState = this._intentStates.get(cacheKey);\n intentState.streamReader = reader;\n const pump = () => {\n reader.read().then(({\n value,\n done\n }) => {\n if (done) {\n intentState.streamReader = null;\n return;\n }\n if (this._transport.destroyed) {\n return;\n }\n this._renderPageChunk(value, intentState);\n pump();\n }, reason => {\n intentState.streamReader = null;\n if (this._transport.destroyed) {\n return;\n }\n if (intentState.operatorList) {\n intentState.operatorList.lastChunk = true;\n for (const internalRenderTask of intentState.renderTasks) {\n internalRenderTask.operatorListChanged();\n }\n this.#tryCleanup();\n }\n if (intentState.displayReadyCapability) {\n intentState.displayReadyCapability.reject(reason);\n } else if (intentState.opListReadCapability) {\n intentState.opListReadCapability.reject(reason);\n } else {\n throw reason;\n }\n });\n };\n pump();\n }\n _abortOperatorList({\n intentState,\n reason,\n force = false\n }) {\n if (!intentState.streamReader) {\n return;\n }\n if (intentState.streamReaderCancelTimeout) {\n clearTimeout(intentState.streamReaderCancelTimeout);\n intentState.streamReaderCancelTimeout = null;\n }\n if (!force) {\n if (intentState.renderTasks.size > 0) {\n return;\n }\n if (reason instanceof RenderingCancelledException) {\n let delay = RENDERING_CANCELLED_TIMEOUT;\n if (reason.extraDelay > 0 && reason.extraDelay < 1000) {\n delay += reason.extraDelay;\n }\n intentState.streamReaderCancelTimeout = setTimeout(() => {\n intentState.streamReaderCancelTimeout = null;\n this._abortOperatorList({\n intentState,\n reason,\n force: true\n });\n }, delay);\n return;\n }\n }\n intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {});\n intentState.streamReader = null;\n if (this._transport.destroyed) {\n return;\n }\n for (const [curCacheKey, curIntentState] of this._intentStates) {\n if (curIntentState === intentState) {\n this._intentStates.delete(curCacheKey);\n break;\n }\n }\n this.cleanup();\n }\n get stats() {\n return this._stats;\n }\n}\nclass PDFWorker {\n #capability = Promise.withResolvers();\n #messageHandler = null;\n #port = null;\n #webWorker = null;\n static #fakeWorkerId = 0;\n static #isWorkerDisabled = false;\n static #workerPorts = new WeakMap();\n static {\n if (isNodeJS) {\n this.#isWorkerDisabled = true;\n GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs";\n }\n this._isSameOrigin = (baseUrl, otherUrl) => {\n const base = URL.parse(baseUrl);\n if (!base?.origin || base.origin === "null") {\n return false;\n }\n const other = new URL(otherUrl, base);\n return base.origin === other.origin;\n };\n this._createCDNWrapper = url => {\n const wrapper = `await import("${url}");`;\n return URL.createObjectURL(new Blob([wrapper], {\n type: "text/javascript"\n }));\n };\n this.fromPort = params => {\n deprecated("`PDFWorker.fromPort` - please use `PDFWorker.create` instead.");\n if (!params?.port) {\n throw new Error("PDFWorker.fromPort - invalid method signature.");\n }\n return this.create(params);\n };\n }\n constructor({\n name = null,\n port = null,\n verbosity = getVerbosityLevel()\n } = {}) {\n this.name = name;\n this.destroyed = false;\n this.verbosity = verbosity;\n if (port) {\n if (PDFWorker.#workerPorts.has(port)) {\n throw new Error("Cannot use more than one PDFWorker per port.");\n }\n PDFWorker.#workerPorts.set(port, this);\n this.#initializeFromPort(port);\n } else {\n this.#initialize();\n }\n }\n get promise() {\n return this.#capability.promise;\n }\n #resolve() {\n this.#capability.resolve();\n this.#messageHandler.send("configure", {\n verbosity: this.verbosity\n });\n }\n get port() {\n return this.#port;\n }\n get messageHandler() {\n return this.#messageHandler;\n }\n #initializeFromPort(port) {\n this.#port = port;\n this.#messageHandler = new MessageHandler("main", "worker", port);\n this.#messageHandler.on("ready", () => {});\n this.#resolve();\n }\n #initialize() {\n if (PDFWorker.#isWorkerDisabled || PDFWorker.#mainThreadWorkerMessageHandler) {\n this.#setupFakeWorker();\n return;\n }\n let {\n workerSrc\n } = PDFWorker;\n try {\n if (!PDFWorker._isSameOrigin(window.location, workerSrc)) {\n workerSrc = PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href);\n }\n const worker = new Worker(workerSrc, {\n type: "module"\n });\n const messageHandler = new MessageHandler("main", "worker", worker);\n const terminateEarly = () => {\n ac.abort();\n messageHandler.destroy();\n worker.terminate();\n if (this.destroyed) {\n this.#capability.reject(new Error("Worker was destroyed"));\n } else {\n this.#setupFakeWorker();\n }\n };\n const ac = new AbortController();\n worker.addEventListener("error", () => {\n if (!this.#webWorker) {\n terminateEarly();\n }\n }, {\n signal: ac.signal\n });\n messageHandler.on("test", data => {\n ac.abort();\n if (this.destroyed || !data) {\n terminateEarly();\n return;\n }\n this.#messageHandler = messageHandler;\n this.#port = worker;\n this.#webWorker = worker;\n this.#resolve();\n });\n messageHandler.on("ready", data => {\n ac.abort();\n if (this.destroyed) {\n terminateEarly();\n return;\n }\n try {\n sendTest();\n } catch {\n this.#setupFakeWorker();\n }\n });\n const sendTest = () => {\n const testObj = new Uint8Array();\n messageHandler.send("test", testObj, [testObj.buffer]);\n };\n sendTest();\n return;\n } catch {\n info("The worker has been disabled.");\n }\n this.#setupFakeWorker();\n }\n #setupFakeWorker() {\n if (!PDFWorker.#isWorkerDisabled) {\n warn("Setting up fake worker.");\n PDFWorker.#isWorkerDisabled = true;\n }\n PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {\n if (this.destroyed) {\n this.#capability.reject(new Error("Worker was destroyed"));\n return;\n }\n const port = new LoopbackPort();\n this.#port = port;\n const id = `fake${PDFWorker.#fakeWorkerId++}`;\n const workerHandler = new MessageHandler(id + "_worker", id, port);\n WorkerMessageHandler.setup(workerHandler, port);\n this.#messageHandler = new MessageHandler(id, id + "_worker", port);\n this.#resolve();\n }).catch(reason => {\n this.#capability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));\n });\n }\n destroy() {\n this.destroyed = true;\n this.#webWorker?.terminate();\n this.#webWorker = null;\n PDFWorker.#workerPorts.delete(this.#port);\n this.#port = null;\n this.#messageHandler?.destroy();\n this.#messageHandler = null;\n }\n static create(params) {\n const cachedPort = this.#workerPorts.get(params?.port);\n if (cachedPort) {\n if (cachedPort._pendingDestroy) {\n throw new Error("PDFWorker.create - the worker is being destroyed.\\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls.");\n }\n return cachedPort;\n }\n return new PDFWorker(params);\n }\n static get workerSrc() {\n if (GlobalWorkerOptions.workerSrc) {\n return GlobalWorkerOptions.workerSrc;\n }\n throw new Error(\'No "GlobalWorkerOptions.workerSrc" specified.\');\n }\n static get #mainThreadWorkerMessageHandler() {\n try {\n return globalThis.pdfjsWorker?.WorkerMessageHandler || null;\n } catch {\n return null;\n }\n }\n static get _setupFakeWorkerGlobal() {\n const loader = async () => {\n if (this.#mainThreadWorkerMessageHandler) {\n return this.#mainThreadWorkerMessageHandler;\n }\n const worker = await import(\n /*webpackIgnore: true*/\n /*@vite-ignore*/\n this.workerSrc);\n return worker.WorkerMessageHandler;\n };\n return shadow(this, "_setupFakeWorkerGlobal", loader());\n }\n}\nclass WorkerTransport {\n downloadInfoCapability = Promise.withResolvers();\n #fullReader = null;\n #methodPromises = new Map();\n #networkStream = null;\n #pageCache = new Map();\n #pagePromises = new Map();\n #pageRefCache = new Map();\n #passwordCapability = null;\n #copiedPageInfo = null;\n constructor(messageHandler, loadingTask, networkStream, params, factory, pagesMapper) {\n this.messageHandler = messageHandler;\n this.loadingTask = loadingTask;\n this.#networkStream = networkStream;\n this.commonObjs = new PDFObjects();\n this.fontLoader = new FontLoader({\n ownerDocument: params.ownerDocument,\n styleElement: params.styleElement\n });\n this.enableHWA = params.enableHWA;\n this.loadingParams = params.loadingParams;\n this._params = params;\n this.canvasFactory = factory.canvasFactory;\n this.filterFactory = factory.filterFactory;\n this.cMapReaderFactory = factory.cMapReaderFactory;\n this.standardFontDataFactory = factory.standardFontDataFactory;\n this.wasmFactory = factory.wasmFactory;\n this.destroyed = false;\n this.destroyCapability = null;\n this.setupMessageHandler();\n this.pagesMapper = pagesMapper;\n this.pagesMapper.addListener(this.#updateCaches.bind(this));\n }\n #updateCaches({\n type,\n pageNumbers\n }) {\n if (type === "copy") {\n this.#copiedPageInfo = new Map();\n for (const pageNum of pageNumbers) {\n this.#copiedPageInfo.set(pageNum, {\n proxy: this.#pageCache.get(pageNum - 1) || null,\n promise: this.#pagePromises.get(pageNum - 1) || null\n });\n }\n return;\n }\n if (type === "delete") {\n for (const pageNum of pageNumbers) {\n this.#pageCache.delete(pageNum - 1);\n this.#pagePromises.delete(pageNum - 1);\n }\n }\n const newPageCache = new Map();\n const newPromiseCache = new Map();\n const {\n pagesMapper\n } = this;\n for (let i = 0, ii = pagesMapper.pagesNumber; i < ii; i++) {\n const prevPageNumber = pagesMapper.getPrevPageNumber(i + 1);\n if (prevPageNumber < 0) {\n const {\n proxy,\n promise\n } = this.#copiedPageInfo?.get(-prevPageNumber) || {};\n if (proxy) {\n newPageCache.set(i, proxy);\n }\n if (promise) {\n newPromiseCache.set(i, promise);\n }\n continue;\n }\n const prevPageIndex = prevPageNumber - 1;\n const page = this.#pageCache.get(prevPageIndex);\n if (page) {\n newPageCache.set(i, page);\n }\n const promise = this.#pagePromises.get(prevPageIndex);\n if (promise) {\n newPromiseCache.set(i, promise);\n }\n }\n this.#pageCache = newPageCache;\n this.#pagePromises = newPromiseCache;\n }\n #cacheSimpleMethod(name, data = null) {\n return this.#methodPromises.getOrInsertComputed(name, () => this.messageHandler.sendWithPromise(name, data));\n }\n #onProgress({\n loaded,\n total\n }) {\n this.loadingTask.onProgress?.({\n loaded,\n total,\n percent: MathClamp(Math.round(loaded / total * 100), 0, 100)\n });\n }\n get annotationStorage() {\n return shadow(this, "annotationStorage", new AnnotationStorage());\n }\n getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) {\n let renderingIntent = RenderingIntentFlag.DISPLAY;\n let annotationStorageSerializable = SerializableEmpty;\n switch (intent) {\n case "any":\n renderingIntent = RenderingIntentFlag.ANY;\n break;\n case "display":\n break;\n case "print":\n renderingIntent = RenderingIntentFlag.PRINT;\n break;\n default:\n warn(`getRenderingIntent - invalid intent: ${intent}`);\n }\n const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;\n switch (annotationMode) {\n case AnnotationMode.DISABLE:\n renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE;\n break;\n case AnnotationMode.ENABLE:\n break;\n case AnnotationMode.ENABLE_FORMS:\n renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS;\n break;\n case AnnotationMode.ENABLE_STORAGE:\n renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE;\n annotationStorageSerializable = annotationStorage.serializable;\n break;\n default:\n warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);\n }\n if (isEditing) {\n renderingIntent += RenderingIntentFlag.IS_EDITING;\n }\n if (isOpList) {\n renderingIntent += RenderingIntentFlag.OPLIST;\n }\n const {\n ids: modifiedIds,\n hash: modifiedIdsHash\n } = annotationStorage.modifiedIds;\n const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash];\n return {\n renderingIntent,\n cacheKey: cacheKeyBuf.join("_"),\n annotationStorageSerializable,\n modifiedIds\n };\n }\n destroy() {\n if (this.destroyCapability) {\n return this.destroyCapability.promise;\n }\n this.destroyed = true;\n this.destroyCapability = Promise.withResolvers();\n this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback"));\n const waitOn = [];\n for (const page of this.#pageCache.values()) {\n waitOn.push(page._destroy());\n }\n this.#pageCache.clear();\n this.#pagePromises.clear();\n this.#pageRefCache.clear();\n if (this.hasOwnProperty("annotationStorage")) {\n this.annotationStorage.resetModified();\n }\n const terminated = this.messageHandler.sendWithPromise("Terminate", null);\n waitOn.push(terminated);\n Promise.all(waitOn).then(() => {\n this.commonObjs.clear();\n this.fontLoader.clear();\n this.#methodPromises.clear();\n this.filterFactory.destroy();\n TextLayer.cleanup();\n this.#networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));\n this.messageHandler?.destroy();\n this.messageHandler = null;\n this.destroyCapability.resolve();\n }, this.destroyCapability.reject);\n return this.destroyCapability.promise;\n }\n setupMessageHandler() {\n const {\n messageHandler,\n loadingTask\n } = this;\n messageHandler.on("GetReader", (data, sink) => {\n assert(this.#networkStream, "GetReader - no `BasePDFStream` instance available.");\n this.#fullReader = this.#networkStream.getFullReader();\n this.#fullReader.onProgress = evt => this.#onProgress(evt);\n sink.onPull = () => {\n this.#fullReader.read().then(function ({\n value,\n done\n }) {\n if (done) {\n sink.close();\n return;\n }\n assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");\n sink.enqueue(new Uint8Array(value), 1, [value]);\n }).catch(reason => {\n sink.error(reason);\n });\n };\n sink.onCancel = reason => {\n this.#fullReader.cancel(reason);\n sink.ready.catch(readyReason => {\n if (this.destroyed) {\n return;\n }\n throw readyReason;\n });\n };\n });\n messageHandler.on("ReaderHeadersReady", async data => {\n await this.#fullReader.headersReady;\n const {\n isStreamingSupported,\n isRangeSupported,\n contentLength\n } = this.#fullReader;\n if (isStreamingSupported && isRangeSupported) {\n this.#fullReader.onProgress = null;\n }\n return {\n isStreamingSupported,\n isRangeSupported,\n contentLength\n };\n });\n messageHandler.on("GetRangeReader", (data, sink) => {\n assert(this.#networkStream, "GetRangeReader - no `BasePDFStream` instance available.");\n const rangeReader = this.#networkStream.getRangeReader(data.begin, data.end);\n if (!rangeReader) {\n sink.close();\n return;\n }\n sink.onPull = () => {\n rangeReader.read().then(function ({\n value,\n done\n }) {\n if (done) {\n sink.close();\n return;\n }\n assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");\n sink.enqueue(new Uint8Array(value), 1, [value]);\n }).catch(reason => {\n sink.error(reason);\n });\n };\n sink.onCancel = reason => {\n rangeReader.cancel(reason);\n sink.ready.catch(readyReason => {\n if (this.destroyed) {\n return;\n }\n throw readyReason;\n });\n };\n });\n messageHandler.on("GetDoc", ({\n pdfInfo\n }) => {\n this.pagesMapper.pagesNumber = pdfInfo.numPages;\n this._numPages = pdfInfo.numPages;\n this._htmlForXfa = pdfInfo.htmlForXfa;\n delete pdfInfo.htmlForXfa;\n loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));\n });\n messageHandler.on("DocException", ex => {\n loadingTask._capability.reject(wrapReason(ex));\n });\n messageHandler.on("PasswordRequest", ex => {\n this.#passwordCapability = Promise.withResolvers();\n try {\n if (!loadingTask.onPassword) {\n throw wrapReason(ex);\n }\n const updatePassword = password => {\n if (password instanceof Error) {\n this.#passwordCapability.reject(password);\n } else {\n this.#passwordCapability.resolve({\n password\n });\n }\n };\n loadingTask.onPassword(updatePassword, ex.code);\n } catch (err) {\n this.#passwordCapability.reject(err);\n }\n return this.#passwordCapability.promise;\n });\n messageHandler.on("DataLoaded", data => {\n this.#onProgress({\n loaded: data.length,\n total: data.length\n });\n this.downloadInfoCapability.resolve(data);\n });\n messageHandler.on("StartRenderPage", data => {\n if (this.destroyed) {\n return;\n }\n const page = this.#pageCache.get(data.pageIndex);\n page._startRenderPage(data.transparency, data.cacheKey);\n });\n messageHandler.on("commonobj", ([id, type, exportedData]) => {\n if (this.destroyed) {\n return null;\n }\n if (this.commonObjs.has(id)) {\n return null;\n }\n switch (type) {\n case "Font":\n if ("error" in exportedData) {\n const exportedError = exportedData.error;\n warn(`Error during font loading: ${exportedError}`);\n this.commonObjs.resolve(id, exportedError);\n break;\n }\n const fontData = new FontInfo(exportedData);\n const inspectFont = this._params.pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null;\n const font = new FontFaceObject(fontData, inspectFont, exportedData.extra, exportedData.charProcOperatorList);\n this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", {\n id\n })).finally(() => {\n if (!font.fontExtraProperties && font.data) {\n font.clearData();\n }\n this.commonObjs.resolve(id, font);\n });\n break;\n case "CopyLocalImage":\n const {\n imageRef\n } = exportedData;\n assert(imageRef, "The imageRef must be defined.");\n for (const pageProxy of this.#pageCache.values()) {\n for (const [, data] of pageProxy.objs) {\n if (data?.ref !== imageRef) {\n continue;\n }\n if (!data.dataLen) {\n return null;\n }\n this.commonObjs.resolve(id, structuredClone(data));\n return data.dataLen;\n }\n }\n break;\n case "FontPath":\n this.commonObjs.resolve(id, new FontPathInfo(exportedData));\n break;\n case "Image":\n this.commonObjs.resolve(id, exportedData);\n break;\n case "Pattern":\n const pattern = new PatternInfo(exportedData);\n this.commonObjs.resolve(id, pattern.getIR());\n break;\n default:\n throw new Error(`Got unknown common object type ${type}`);\n }\n return null;\n });\n messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {\n if (this.destroyed) {\n return;\n }\n const pageProxy = this.#pageCache.get(pageIndex);\n if (pageProxy.objs.has(id)) {\n return;\n }\n if (pageProxy._intentStates.size === 0) {\n imageData?.bitmap?.close();\n return;\n }\n switch (type) {\n case "Image":\n case "Pattern":\n pageProxy.objs.resolve(id, imageData);\n break;\n default:\n throw new Error(`Got unknown object type ${type}`);\n }\n });\n messageHandler.on("DocProgress", data => {\n if (this.destroyed) {\n return;\n }\n this.#onProgress(data);\n });\n messageHandler.on("FetchBinaryData", async data => {\n if (this.destroyed) {\n throw new Error("Worker was destroyed.");\n }\n const factory = this[data.type];\n if (!factory) {\n throw new Error(`${data.type} not initialized, see the \\`useWorkerFetch\\` parameter.`);\n }\n return factory.fetch(data);\n });\n }\n getData() {\n return this.messageHandler.sendWithPromise("GetData", null);\n }\n saveDocument() {\n if (this.annotationStorage.size <= 0) {\n warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");\n }\n const {\n map,\n transfer\n } = this.annotationStorage.serializable;\n return this.messageHandler.sendWithPromise("SaveDocument", {\n isPureXfa: !!this._htmlForXfa,\n numPages: this._numPages,\n annotationStorage: map,\n filename: this.#fullReader?.filename ?? null\n }, transfer).finally(() => {\n this.annotationStorage.resetModified();\n });\n }\n extractPages(pageInfos) {\n return this.messageHandler.sendWithPromise("ExtractPages", {\n pageInfos\n });\n }\n getPage(pageNumber) {\n if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this.pagesMapper.pagesNumber) {\n return Promise.reject(new Error("Invalid page request."));\n }\n const pageIndex = pageNumber - 1;\n const newPageIndex = this.pagesMapper.getPageId(pageNumber) - 1;\n const cachedPromise = this.#pagePromises.get(pageIndex);\n if (cachedPromise) {\n return cachedPromise;\n }\n const promise = this.messageHandler.sendWithPromise("GetPage", {\n pageIndex: newPageIndex\n }).then(pageInfo => {\n if (this.destroyed) {\n throw new Error("Transport destroyed");\n }\n if (pageInfo.refStr) {\n this.#pageRefCache.set(pageInfo.refStr, newPageIndex);\n }\n const page = new PDFPageProxy(pageIndex, pageInfo, this, this.pagesMapper, this._params.pdfBug);\n this.#pageCache.set(pageIndex, page);\n return page;\n });\n this.#pagePromises.set(pageIndex, promise);\n return promise;\n }\n async getPageIndex(ref) {\n if (!isRefProxy(ref)) {\n throw new Error("Invalid pageIndex request.");\n }\n const index = await this.messageHandler.sendWithPromise("GetPageIndex", {\n num: ref.num,\n gen: ref.gen\n });\n const pageNumber = this.pagesMapper.getPageNumber(index + 1);\n if (pageNumber === 0) {\n throw new Error("GetPageIndex: page has been removed.");\n }\n return pageNumber - 1;\n }\n getAnnotations(pageIndex, intent) {\n return this.messageHandler.sendWithPromise("GetAnnotations", {\n pageIndex: this.pagesMapper.getPageId(pageIndex + 1) - 1,\n intent\n });\n }\n getFieldObjects() {\n return this.#cacheSimpleMethod("GetFieldObjects");\n }\n hasJSActions() {\n return this.#cacheSimpleMethod("HasJSActions");\n }\n getCalculationOrderIds() {\n return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);\n }\n getDestinations() {\n return this.messageHandler.sendWithPromise("GetDestinations", null);\n }\n getDestination(id) {\n if (typeof id !== "string") {\n return Promise.reject(new Error("Invalid destination request."));\n }\n return this.messageHandler.sendWithPromise("GetDestination", {\n id\n });\n }\n getPageLabels() {\n return this.messageHandler.sendWithPromise("GetPageLabels", null);\n }\n getPageLayout() {\n return this.messageHandler.sendWithPromise("GetPageLayout", null);\n }\n getPageMode() {\n return this.messageHandler.sendWithPromise("GetPageMode", null);\n }\n getViewerPreferences() {\n return this.messageHandler.sendWithPromise("GetViewerPreferences", null);\n }\n getOpenAction() {\n return this.messageHandler.sendWithPromise("GetOpenAction", null);\n }\n getAttachments() {\n return this.messageHandler.sendWithPromise("GetAttachments", null);\n }\n getAnnotationsByType(types, pageIndexesToSkip) {\n return this.messageHandler.sendWithPromise("GetAnnotationsByType", {\n types,\n pageIndexesToSkip\n });\n }\n getDocJSActions() {\n return this.#cacheSimpleMethod("GetDocJSActions");\n }\n getPageJSActions(pageIndex) {\n return this.messageHandler.sendWithPromise("GetPageJSActions", {\n pageIndex: this.pagesMapper.getPageId(pageIndex + 1) - 1\n });\n }\n getStructTree(pageIndex) {\n return this.messageHandler.sendWithPromise("GetStructTree", {\n pageIndex: this.pagesMapper.getPageId(pageIndex + 1) - 1\n });\n }\n getOutline() {\n return this.messageHandler.sendWithPromise("GetOutline", null);\n }\n getOptionalContentConfig(renderingIntent) {\n return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent));\n }\n getPermissions() {\n return this.messageHandler.sendWithPromise("GetPermissions", null);\n }\n getMetadata() {\n const name = "GetMetadata";\n return this.#methodPromises.getOrInsertComputed(name, () => this.messageHandler.sendWithPromise(name, null).then(results => ({\n info: results[0],\n metadata: results[1] ? new Metadata(results[1]) : null,\n contentDispositionFilename: this.#fullReader?.filename ?? null,\n contentLength: this.#fullReader?.contentLength ?? null,\n hasStructTree: results[2]\n })));\n }\n getMarkInfo() {\n return this.messageHandler.sendWithPromise("GetMarkInfo", null);\n }\n async startCleanup(keepLoadedFonts = false) {\n if (this.destroyed) {\n return;\n }\n await this.messageHandler.sendWithPromise("Cleanup", null);\n for (const page of this.#pageCache.values()) {\n const cleanupSuccessful = page.cleanup();\n if (!cleanupSuccessful) {\n throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);\n }\n }\n this.commonObjs.clear();\n if (!keepLoadedFonts) {\n this.fontLoader.clear();\n }\n this.#methodPromises.clear();\n this.filterFactory.destroy(true);\n TextLayer.cleanup();\n }\n cachedPageNumber(ref) {\n if (!isRefProxy(ref)) {\n return null;\n }\n const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`;\n const pageIndex = this.#pageRefCache.get(refStr);\n if (pageIndex >= 0) {\n const pageNumber = this.pagesMapper.getPageNumber(pageIndex + 1);\n if (pageNumber !== 0) {\n return pageNumber;\n }\n }\n return null;\n }\n}\nclass RenderTask {\n _internalRenderTask = null;\n onContinue = null;\n onError = null;\n constructor(internalRenderTask) {\n this._internalRenderTask = internalRenderTask;\n }\n get promise() {\n return this._internalRenderTask.capability.promise;\n }\n cancel(extraDelay = 0) {\n this._internalRenderTask.cancel(null, extraDelay);\n }\n get separateAnnots() {\n const {\n separateAnnots\n } = this._internalRenderTask.operatorList;\n if (!separateAnnots) {\n return false;\n }\n const {\n annotationCanvasMap\n } = this._internalRenderTask;\n return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;\n }\n}\nclass InternalRenderTask {\n #rAF = null;\n static #canvasInUse = new WeakSet();\n constructor({\n callback,\n params,\n objs,\n commonObjs,\n annotationCanvasMap,\n operatorList,\n pageIndex,\n canvasFactory,\n filterFactory,\n useRequestAnimationFrame = false,\n pdfBug = false,\n pageColors = null,\n enableHWA = false,\n operationsFilter = null\n }) {\n this.callback = callback;\n this.params = params;\n this.objs = objs;\n this.commonObjs = commonObjs;\n this.annotationCanvasMap = annotationCanvasMap;\n this.operatorListIdx = null;\n this.operatorList = operatorList;\n this._pageIndex = pageIndex;\n this.canvasFactory = canvasFactory;\n this.filterFactory = filterFactory;\n this._pdfBug = pdfBug;\n this.pageColors = pageColors;\n this.running = false;\n this.graphicsReadyCallback = null;\n this.graphicsReady = false;\n this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";\n this.cancelled = false;\n this.capability = Promise.withResolvers();\n this.task = new RenderTask(this);\n this._cancelBound = this.cancel.bind(this);\n this._continueBound = this._continue.bind(this);\n this._scheduleNextBound = this._scheduleNext.bind(this);\n this._nextBound = this._next.bind(this);\n this._canvas = params.canvas;\n this._canvasContext = params.canvas ? null : params.canvasContext;\n this._enableHWA = enableHWA;\n this._dependencyTracker = params.dependencyTracker;\n this._operationsFilter = operationsFilter;\n }\n get completed() {\n return this.capability.promise.catch(function () {});\n }\n initializeGraphics({\n transparency = false,\n optionalContentConfig\n }) {\n if (this.cancelled) {\n return;\n }\n if (this._canvas) {\n if (InternalRenderTask.#canvasInUse.has(this._canvas)) {\n throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");\n }\n InternalRenderTask.#canvasInUse.add(this._canvas);\n }\n if (this._pdfBug && globalThis.StepperManager?.enabled) {\n this.stepper = globalThis.StepperManager.create(this._pageIndex);\n this.stepper.init(this.operatorList);\n this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();\n }\n const {\n viewport,\n transform,\n background,\n dependencyTracker\n } = this.params;\n const canvasContext = this._canvasContext || this._canvas.getContext("2d", {\n alpha: false,\n willReadFrequently: !this._enableHWA\n });\n this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {\n optionalContentConfig\n }, this.annotationCanvasMap, this.pageColors, dependencyTracker);\n this.gfx.beginDrawing({\n transform,\n viewport,\n transparency,\n background\n });\n this.operatorListIdx = 0;\n this.graphicsReady = true;\n this.graphicsReadyCallback?.();\n }\n cancel(error = null, extraDelay = 0) {\n this.running = false;\n this.cancelled = true;\n this.gfx?.endDrawing();\n if (this.#rAF) {\n window.cancelAnimationFrame(this.#rAF);\n this.#rAF = null;\n }\n InternalRenderTask.#canvasInUse.delete(this._canvas);\n error ||= new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay);\n this.callback(error);\n this.task.onError?.(error);\n }\n operatorListChanged() {\n if (!this.graphicsReady) {\n this.graphicsReadyCallback ||= this._continueBound;\n return;\n }\n this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length);\n this.stepper?.updateOperatorList(this.operatorList);\n if (this.running) {\n return;\n }\n this._continue();\n }\n _continue() {\n this.running = true;\n if (this.cancelled) {\n return;\n }\n if (this.task.onContinue) {\n this.task.onContinue(this._scheduleNextBound);\n } else {\n this._scheduleNext();\n }\n }\n _scheduleNext() {\n if (this._useRequestAnimationFrame) {\n this.#rAF = window.requestAnimationFrame(() => {\n this.#rAF = null;\n this._nextBound().catch(this._cancelBound);\n });\n } else {\n Promise.resolve().then(this._nextBound).catch(this._cancelBound);\n }\n }\n async _next() {\n if (this.cancelled) {\n return;\n }\n this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper, this._operationsFilter);\n if (this.operatorListIdx === this.operatorList.argsArray.length) {\n this.running = false;\n if (this.operatorList.lastChunk) {\n this.gfx.endDrawing();\n InternalRenderTask.#canvasInUse.delete(this._canvas);\n this.callback();\n }\n }\n }\n}\nconst version = "5.5.207";\nconst build = "527964698";\n\n;// ./src/display/editor/color_picker.js\n\n\n\nclass ColorPicker {\n #button = null;\n #buttonSwatch = null;\n #defaultColor;\n #dropdown = null;\n #dropdownWasFromKeyboard = false;\n #isMainColorPicker = false;\n #editor = null;\n #eventBus;\n #openDropdownAC = null;\n #uiManager = null;\n static #l10nColor = null;\n static get _keyboardManager() {\n return shadow(this, "_keyboardManager", new KeyboardManager([[["Escape", "mac+Escape"], ColorPicker.prototype._hideDropdownFromKeyboard], [[" ", "mac+ "], ColorPicker.prototype._colorSelectFromKeyboard], [["ArrowDown", "ArrowRight", "mac+ArrowDown", "mac+ArrowRight"], ColorPicker.prototype._moveToNext], [["ArrowUp", "ArrowLeft", "mac+ArrowUp", "mac+ArrowLeft"], ColorPicker.prototype._moveToPrevious], [["Home", "mac+Home"], ColorPicker.prototype._moveToBeginning], [["End", "mac+End"], ColorPicker.prototype._moveToEnd]]));\n }\n constructor({\n editor = null,\n uiManager = null\n }) {\n if (editor) {\n this.#isMainColorPicker = false;\n this.#editor = editor;\n } else {\n this.#isMainColorPicker = true;\n }\n this.#uiManager = editor?._uiManager || uiManager;\n this.#eventBus = this.#uiManager._eventBus;\n this.#defaultColor = editor?.color?.toUpperCase() || this.#uiManager?.highlightColors.values().next().value || "#FFFF98";\n ColorPicker.#l10nColor ||= Object.freeze({\n blue: "pdfjs-editor-colorpicker-blue",\n green: "pdfjs-editor-colorpicker-green",\n pink: "pdfjs-editor-colorpicker-pink",\n red: "pdfjs-editor-colorpicker-red",\n yellow: "pdfjs-editor-colorpicker-yellow"\n });\n }\n renderButton() {\n const button = this.#button = document.createElement("button");\n button.className = "colorPicker";\n button.tabIndex = "0";\n button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button");\n button.ariaHasPopup = "true";\n if (this.#editor) {\n button.ariaControls = `${this.#editor.id}_colorpicker_dropdown`;\n }\n const signal = this.#uiManager._signal;\n button.addEventListener("click", this.#openDropdown.bind(this), {\n signal\n });\n button.addEventListener("keydown", this.#keyDown.bind(this), {\n signal\n });\n const swatch = this.#buttonSwatch = document.createElement("span");\n swatch.className = "swatch";\n swatch.ariaHidden = "true";\n swatch.style.backgroundColor = this.#defaultColor;\n button.append(swatch);\n return button;\n }\n renderMainDropdown() {\n const dropdown = this.#dropdown = this.#getDropdownRoot();\n dropdown.ariaOrientation = "horizontal";\n dropdown.ariaLabelledBy = "highlightColorPickerLabel";\n return dropdown;\n }\n #getDropdownRoot() {\n const div = document.createElement("div");\n const signal = this.#uiManager._signal;\n div.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n div.className = "dropdown";\n div.role = "listbox";\n div.ariaMultiSelectable = "false";\n div.ariaOrientation = "vertical";\n div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown");\n if (this.#editor) {\n div.id = `${this.#editor.id}_colorpicker_dropdown`;\n }\n for (const [name, color] of this.#uiManager.highlightColors) {\n const button = document.createElement("button");\n button.tabIndex = "0";\n button.role = "option";\n button.setAttribute("data-color", color);\n button.title = name;\n button.setAttribute("data-l10n-id", ColorPicker.#l10nColor[name]);\n const swatch = document.createElement("span");\n button.append(swatch);\n swatch.className = "swatch";\n swatch.style.backgroundColor = color;\n button.ariaSelected = color === this.#defaultColor;\n button.addEventListener("click", this.#colorSelect.bind(this, color), {\n signal\n });\n div.append(button);\n }\n div.addEventListener("keydown", this.#keyDown.bind(this), {\n signal\n });\n return div;\n }\n #colorSelect(color, event) {\n event.stopPropagation();\n this.#eventBus.dispatch("switchannotationeditorparams", {\n source: this,\n type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,\n value: color\n });\n this.updateColor(color);\n }\n _colorSelectFromKeyboard(event) {\n if (event.target === this.#button) {\n this.#openDropdown(event);\n return;\n }\n const color = event.target.getAttribute("data-color");\n if (!color) {\n return;\n }\n this.#colorSelect(color, event);\n }\n _moveToNext(event) {\n if (!this.#isDropdownVisible) {\n this.#openDropdown(event);\n return;\n }\n if (event.target === this.#button) {\n this.#dropdown.firstElementChild?.focus();\n return;\n }\n event.target.nextSibling?.focus();\n }\n _moveToPrevious(event) {\n if (event.target === this.#dropdown?.firstElementChild || event.target === this.#button) {\n if (this.#isDropdownVisible) {\n this._hideDropdownFromKeyboard();\n }\n return;\n }\n if (!this.#isDropdownVisible) {\n this.#openDropdown(event);\n }\n event.target.previousSibling?.focus();\n }\n _moveToBeginning(event) {\n if (!this.#isDropdownVisible) {\n this.#openDropdown(event);\n return;\n }\n this.#dropdown.firstElementChild?.focus();\n }\n _moveToEnd(event) {\n if (!this.#isDropdownVisible) {\n this.#openDropdown(event);\n return;\n }\n this.#dropdown.lastElementChild?.focus();\n }\n #keyDown(event) {\n ColorPicker._keyboardManager.exec(this, event);\n }\n #openDropdown(event) {\n if (this.#isDropdownVisible) {\n this.hideDropdown();\n return;\n }\n this.#dropdownWasFromKeyboard = event.detail === 0;\n if (!this.#openDropdownAC) {\n this.#openDropdownAC = new AbortController();\n window.addEventListener("pointerdown", this.#pointerDown.bind(this), {\n signal: this.#uiManager.combinedSignal(this.#openDropdownAC)\n });\n }\n this.#button.ariaExpanded = "true";\n if (this.#dropdown) {\n this.#dropdown.classList.remove("hidden");\n return;\n }\n const root = this.#dropdown = this.#getDropdownRoot();\n this.#button.append(root);\n }\n #pointerDown(event) {\n if (this.#dropdown?.contains(event.target)) {\n return;\n }\n this.hideDropdown();\n }\n hideDropdown() {\n this.#dropdown?.classList.add("hidden");\n this.#button.ariaExpanded = "false";\n this.#openDropdownAC?.abort();\n this.#openDropdownAC = null;\n }\n get #isDropdownVisible() {\n return this.#dropdown && !this.#dropdown.classList.contains("hidden");\n }\n _hideDropdownFromKeyboard() {\n if (this.#isMainColorPicker) {\n return;\n }\n if (!this.#isDropdownVisible) {\n this.#editor?.unselect();\n return;\n }\n this.hideDropdown();\n this.#button.focus({\n preventScroll: true,\n focusVisible: this.#dropdownWasFromKeyboard\n });\n }\n updateColor(color) {\n if (this.#buttonSwatch) {\n this.#buttonSwatch.style.backgroundColor = color;\n }\n if (!this.#dropdown) {\n return;\n }\n const i = this.#uiManager.highlightColors.values();\n for (const child of this.#dropdown.children) {\n child.ariaSelected = i.next().value === color.toUpperCase();\n }\n }\n destroy() {\n this.#button?.remove();\n this.#button = null;\n this.#buttonSwatch = null;\n this.#dropdown?.remove();\n this.#dropdown = null;\n }\n}\nclass BasicColorPicker {\n #input = null;\n #editor = null;\n #uiManager = null;\n static #l10nColor = null;\n constructor(editor) {\n this.#editor = editor;\n this.#uiManager = editor._uiManager;\n BasicColorPicker.#l10nColor ||= Object.freeze({\n freetext: "pdfjs-editor-color-picker-free-text-input",\n ink: "pdfjs-editor-color-picker-ink-input"\n });\n }\n renderButton() {\n if (this.#input) {\n return this.#input;\n }\n const {\n editorType,\n colorType,\n color\n } = this.#editor;\n const input = this.#input = document.createElement("input");\n input.type = "color";\n input.value = color || "#000000";\n input.className = "basicColorPicker";\n input.tabIndex = 0;\n input.setAttribute("data-l10n-id", BasicColorPicker.#l10nColor[editorType]);\n input.addEventListener("input", () => {\n this.#uiManager.updateParams(colorType, input.value);\n }, {\n signal: this.#uiManager._signal\n });\n return input;\n }\n update(value) {\n if (!this.#input) {\n return;\n }\n this.#input.value = value;\n }\n destroy() {\n this.#input?.remove();\n this.#input = null;\n }\n hideDropdown() {}\n}\n\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.iterator.flat-map.js\nvar es_iterator_flat_map = __webpack_require__(531);\n;// ./src/shared/scripting_utils.js\n\n\nfunction makeColorComp(n) {\n return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");\n}\nfunction scaleAndClamp(x) {\n return Math.max(0, Math.min(255, 255 * x));\n}\nclass ColorConverters {\n static CMYK_G([c, y, m, k]) {\n return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];\n }\n static G_CMYK([g]) {\n return ["CMYK", 0, 0, 0, 1 - g];\n }\n static G_RGB([g]) {\n return ["RGB", g, g, g];\n }\n static G_rgb([g]) {\n g = scaleAndClamp(g);\n return [g, g, g];\n }\n static G_HTML([g]) {\n const G = makeColorComp(g);\n return `#${G}${G}${G}`;\n }\n static RGB_G([r, g, b]) {\n return ["G", 0.3 * r + 0.59 * g + 0.11 * b];\n }\n static RGB_rgb(color) {\n return color.map(scaleAndClamp);\n }\n static RGB_HTML(color) {\n return `#${color.map(makeColorComp).join("")}`;\n }\n static T_HTML() {\n return "#00000000";\n }\n static T_rgb() {\n return [null];\n }\n static CMYK_RGB([c, y, m, k]) {\n return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];\n }\n static CMYK_rgb([c, y, m, k]) {\n return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))];\n }\n static CMYK_HTML(components) {\n const rgb = this.CMYK_RGB(components).slice(1);\n return this.RGB_HTML(rgb);\n }\n static RGB_CMYK([r, g, b]) {\n const c = 1 - r;\n const m = 1 - g;\n const y = 1 - b;\n const k = Math.min(c, m, y);\n return ["CMYK", c, m, y, k];\n }\n}\nconst DateFormats = (/* unused pure expression or super */ null && (["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"]));\nconst TimeFormats = (/* unused pure expression or super */ null && (["HH:MM", "h:MM tt", "HH:MM:ss", "h:MM:ss tt"]));\n\n;// ./src/display/svg_factory.js\n\n\nclass BaseSVGFactory {\n create(width, height, skipDimensions = false) {\n if (width <= 0 || height <= 0) {\n throw new Error("Invalid SVG dimensions");\n }\n const svg = this._createSVG("svg:svg");\n svg.setAttribute("version", "1.1");\n if (!skipDimensions) {\n svg.setAttribute("width", `${width}px`);\n svg.setAttribute("height", `${height}px`);\n }\n svg.setAttribute("preserveAspectRatio", "none");\n svg.setAttribute("viewBox", `0 0 ${width} ${height}`);\n return svg;\n }\n createElement(type) {\n if (typeof type !== "string") {\n throw new Error("Invalid SVG element type");\n }\n return this._createSVG(type);\n }\n _createSVG(type) {\n unreachable("Abstract method `_createSVG` called.");\n }\n}\nclass DOMSVGFactory extends BaseSVGFactory {\n _createSVG(type) {\n return document.createElementNS(SVG_NS, type);\n }\n}\n\n;// ./src/display/annotation_layer.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst annotation_layer_DEFAULT_FONT_SIZE = 9;\nconst GetElementsByNameSet = new WeakSet();\nconst TIMEZONE_OFFSET = new Date().getTimezoneOffset() * 60 * 1000;\nclass AnnotationElementFactory {\n static create(parameters) {\n const subtype = parameters.data.annotationType;\n switch (subtype) {\n case AnnotationType.LINK:\n return new LinkAnnotationElement(parameters);\n case AnnotationType.TEXT:\n return new TextAnnotationElement(parameters);\n case AnnotationType.WIDGET:\n const fieldType = parameters.data.fieldType;\n switch (fieldType) {\n case "Tx":\n return new TextWidgetAnnotationElement(parameters);\n case "Btn":\n if (parameters.data.radioButton) {\n return new RadioButtonWidgetAnnotationElement(parameters);\n } else if (parameters.data.checkBox) {\n return new CheckboxWidgetAnnotationElement(parameters);\n }\n return new PushButtonWidgetAnnotationElement(parameters);\n case "Ch":\n return new ChoiceWidgetAnnotationElement(parameters);\n case "Sig":\n return new SignatureWidgetAnnotationElement(parameters);\n }\n return new WidgetAnnotationElement(parameters);\n case AnnotationType.POPUP:\n return new PopupAnnotationElement(parameters);\n case AnnotationType.FREETEXT:\n return new FreeTextAnnotationElement(parameters);\n case AnnotationType.LINE:\n return new LineAnnotationElement(parameters);\n case AnnotationType.SQUARE:\n return new SquareAnnotationElement(parameters);\n case AnnotationType.CIRCLE:\n return new CircleAnnotationElement(parameters);\n case AnnotationType.POLYLINE:\n return new PolylineAnnotationElement(parameters);\n case AnnotationType.CARET:\n return new CaretAnnotationElement(parameters);\n case AnnotationType.INK:\n return new InkAnnotationElement(parameters);\n case AnnotationType.POLYGON:\n return new PolygonAnnotationElement(parameters);\n case AnnotationType.HIGHLIGHT:\n return new HighlightAnnotationElement(parameters);\n case AnnotationType.UNDERLINE:\n return new UnderlineAnnotationElement(parameters);\n case AnnotationType.SQUIGGLY:\n return new SquigglyAnnotationElement(parameters);\n case AnnotationType.STRIKEOUT:\n return new StrikeOutAnnotationElement(parameters);\n case AnnotationType.STAMP:\n return new StampAnnotationElement(parameters);\n case AnnotationType.FILEATTACHMENT:\n return new FileAttachmentAnnotationElement(parameters);\n default:\n return new AnnotationElement(parameters);\n }\n }\n}\nclass AnnotationElement {\n #updates = null;\n #hasBorder = false;\n #popupElement = null;\n constructor(parameters, {\n isRenderable = false,\n ignoreBorder = false,\n createQuadrilaterals = false\n } = {}) {\n this.isRenderable = isRenderable;\n this.data = parameters.data;\n this.layer = parameters.layer;\n this.linkService = parameters.linkService;\n this.downloadManager = parameters.downloadManager;\n this.imageResourcesPath = parameters.imageResourcesPath;\n this.renderForms = parameters.renderForms;\n this.svgFactory = parameters.svgFactory;\n this.annotationStorage = parameters.annotationStorage;\n this.enableComment = parameters.enableComment;\n this.enableScripting = parameters.enableScripting;\n this.hasJSActions = parameters.hasJSActions;\n this._fieldObjects = parameters.fieldObjects;\n this.parent = parameters.parent;\n this.hasOwnCommentButton = false;\n if (isRenderable) {\n this.contentElement = this.container = this._createContainer(ignoreBorder);\n }\n if (createQuadrilaterals) {\n this._createQuadrilaterals();\n }\n }\n static _hasPopupData({\n contentsObj,\n richText\n }) {\n return !!(contentsObj?.str || richText?.str);\n }\n get _isEditable() {\n return this.data.isEditable;\n }\n get hasPopupData() {\n return AnnotationElement._hasPopupData(this.data) || this.enableComment && !!this.commentText;\n }\n get commentData() {\n const {\n data\n } = this;\n const editor = this.annotationStorage?.getEditor(data.id);\n if (editor) {\n return editor.getData();\n }\n return data;\n }\n get hasCommentButton() {\n return this.enableComment && this.hasPopupElement;\n }\n get commentButtonPosition() {\n const editor = this.annotationStorage?.getEditor(this.data.id);\n if (editor) {\n return editor.commentButtonPositionInPage;\n }\n const {\n quadPoints,\n inkLists,\n rect\n } = this.data;\n let maxX = -Infinity;\n let maxY = -Infinity;\n if (quadPoints?.length >= 8) {\n for (let i = 0; i < quadPoints.length; i += 8) {\n if (quadPoints[i + 1] > maxY) {\n maxY = quadPoints[i + 1];\n maxX = quadPoints[i + 2];\n } else if (quadPoints[i + 1] === maxY) {\n maxX = Math.max(maxX, quadPoints[i + 2]);\n }\n }\n return [maxX, maxY];\n }\n if (inkLists?.length >= 1) {\n for (const inkList of inkLists) {\n for (let i = 0, ii = inkList.length; i < ii; i += 2) {\n if (inkList[i + 1] > maxY) {\n maxY = inkList[i + 1];\n maxX = inkList[i];\n } else if (inkList[i + 1] === maxY) {\n maxX = Math.max(maxX, inkList[i]);\n }\n }\n }\n if (maxX !== Infinity) {\n return [maxX, maxY];\n }\n }\n if (rect) {\n return [rect[2], rect[3]];\n }\n return null;\n }\n _normalizePoint(point) {\n const {\n page: {\n view\n },\n viewport: {\n rawDims: {\n pageWidth,\n pageHeight,\n pageX,\n pageY\n }\n }\n } = this.parent;\n point[1] = view[3] - point[1] + view[1];\n point[0] = 100 * (point[0] - pageX) / pageWidth;\n point[1] = 100 * (point[1] - pageY) / pageHeight;\n return point;\n }\n get commentText() {\n const {\n data\n } = this;\n return this.annotationStorage.getRawValue(`${AnnotationEditorPrefix}${data.id}`)?.popup?.contents || data.contentsObj?.str || "";\n }\n set commentText(text) {\n const {\n data\n } = this;\n const popup = {\n deleted: !text,\n contents: text || ""\n };\n if (!this.annotationStorage.updateEditor(data.id, {\n popup\n })) {\n this.annotationStorage.setValue(`${AnnotationEditorPrefix}${data.id}`, {\n id: data.id,\n annotationType: data.annotationType,\n page: this.parent.page,\n popup,\n popupRef: data.popupRef,\n modificationDate: new Date()\n });\n }\n if (!text) {\n this.removePopup();\n }\n }\n removePopup() {\n (this.#popupElement?.popup || this.popup)?.remove();\n this.#popupElement = this.popup = null;\n }\n updateEdited(params) {\n if (!this.container) {\n return;\n }\n if (params.rect) {\n this.#updates ||= {\n rect: this.data.rect.slice(0)\n };\n }\n const {\n rect,\n popup: newPopup\n } = params;\n if (rect) {\n this.#setRectEdited(rect);\n }\n let popup = this.#popupElement?.popup || this.popup;\n if (!popup && newPopup?.text) {\n this._createPopup(newPopup);\n popup = this.#popupElement.popup;\n }\n if (!popup) {\n return;\n }\n popup.updateEdited(params);\n if (newPopup?.deleted) {\n popup.remove();\n this.#popupElement = null;\n this.popup = null;\n }\n }\n resetEdited() {\n if (!this.#updates) {\n return;\n }\n this.#setRectEdited(this.#updates.rect);\n this.#popupElement?.popup.resetEdited();\n this.#updates = null;\n }\n #setRectEdited(rect) {\n const {\n container: {\n style\n },\n data: {\n rect: currentRect,\n rotation\n },\n parent: {\n viewport: {\n rawDims: {\n pageWidth,\n pageHeight,\n pageX,\n pageY\n }\n }\n }\n } = this;\n currentRect?.splice(0, 4, ...rect);\n style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;\n style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`;\n if (rotation === 0) {\n style.width = `${100 * (rect[2] - rect[0]) / pageWidth}%`;\n style.height = `${100 * (rect[3] - rect[1]) / pageHeight}%`;\n } else {\n this.setRotation(rotation);\n }\n }\n _createContainer(ignoreBorder) {\n const {\n data,\n parent: {\n page,\n viewport\n }\n } = this;\n const container = document.createElement("section");\n container.setAttribute("data-annotation-id", data.id);\n if (!(this instanceof WidgetAnnotationElement) && !(this instanceof LinkAnnotationElement)) {\n container.tabIndex = 0;\n }\n const {\n style\n } = container;\n style.zIndex = this.parent.zIndex;\n this.parent.zIndex += 2;\n if (data.alternativeText) {\n container.title = data.alternativeText;\n }\n if (data.noRotate) {\n container.classList.add("norotate");\n }\n if (!data.rect || this instanceof PopupAnnotationElement) {\n const {\n rotation\n } = data;\n if (!data.hasOwnCanvas && rotation !== 0) {\n this.setRotation(rotation, container);\n }\n return container;\n }\n const {\n width,\n height\n } = this;\n if (!ignoreBorder && data.borderStyle.width > 0) {\n style.borderWidth = `${data.borderStyle.width}px`;\n const horizontalRadius = data.borderStyle.horizontalCornerRadius;\n const verticalRadius = data.borderStyle.verticalCornerRadius;\n if (horizontalRadius > 0 || verticalRadius > 0) {\n const radius = `calc(${horizontalRadius}px * var(--total-scale-factor)) / calc(${verticalRadius}px * var(--total-scale-factor))`;\n style.borderRadius = radius;\n } else if (this instanceof RadioButtonWidgetAnnotationElement) {\n const radius = `calc(${width}px * var(--total-scale-factor)) / calc(${height}px * var(--total-scale-factor))`;\n style.borderRadius = radius;\n }\n switch (data.borderStyle.style) {\n case AnnotationBorderStyleType.SOLID:\n style.borderStyle = "solid";\n break;\n case AnnotationBorderStyleType.DASHED:\n style.borderStyle = "dashed";\n break;\n case AnnotationBorderStyleType.BEVELED:\n warn("Unimplemented border style: beveled");\n break;\n case AnnotationBorderStyleType.INSET:\n warn("Unimplemented border style: inset");\n break;\n case AnnotationBorderStyleType.UNDERLINE:\n style.borderBottomStyle = "solid";\n break;\n default:\n break;\n }\n const borderColor = data.borderColor || null;\n if (borderColor) {\n this.#hasBorder = true;\n style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);\n } else {\n style.borderWidth = 0;\n }\n }\n const rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);\n const {\n pageWidth,\n pageHeight,\n pageX,\n pageY\n } = viewport.rawDims;\n style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;\n style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;\n const {\n rotation\n } = data;\n if (data.hasOwnCanvas || rotation === 0) {\n style.width = `${100 * width / pageWidth}%`;\n style.height = `${100 * height / pageHeight}%`;\n } else {\n this.setRotation(rotation, container);\n }\n return container;\n }\n setRotation(angle, container = this.container) {\n if (!this.data.rect) {\n return;\n }\n const {\n pageWidth,\n pageHeight\n } = this.parent.viewport.rawDims;\n let {\n width,\n height\n } = this;\n if (angle % 180 !== 0) {\n [width, height] = [height, width];\n }\n container.style.width = `${100 * width / pageWidth}%`;\n container.style.height = `${100 * height / pageHeight}%`;\n container.setAttribute("data-main-rotation", (360 - angle) % 360);\n }\n get _commonActions() {\n const setColor = (jsName, styleName, event) => {\n const color = event.detail[jsName];\n const colorType = color[0];\n const colorArray = color.slice(1);\n event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray);\n this.annotationStorage.setValue(this.data.id, {\n [styleName]: ColorConverters[`${colorType}_rgb`](colorArray)\n });\n };\n return shadow(this, "_commonActions", {\n display: event => {\n const {\n display\n } = event.detail;\n const hidden = display % 2 === 1;\n this.container.style.visibility = hidden ? "hidden" : "visible";\n this.annotationStorage.setValue(this.data.id, {\n noView: hidden,\n noPrint: display === 1 || display === 2\n });\n },\n print: event => {\n this.annotationStorage.setValue(this.data.id, {\n noPrint: !event.detail.print\n });\n },\n hidden: event => {\n const {\n hidden\n } = event.detail;\n this.container.style.visibility = hidden ? "hidden" : "visible";\n this.annotationStorage.setValue(this.data.id, {\n noPrint: hidden,\n noView: hidden\n });\n },\n focus: event => {\n setTimeout(() => event.target.focus({\n preventScroll: false\n }), 0);\n },\n userName: event => {\n event.target.title = event.detail.userName;\n },\n readonly: event => {\n event.target.disabled = event.detail.readonly;\n },\n required: event => {\n this._setRequired(event.target, event.detail.required);\n },\n bgColor: event => {\n setColor("bgColor", "backgroundColor", event);\n },\n fillColor: event => {\n setColor("fillColor", "backgroundColor", event);\n },\n fgColor: event => {\n setColor("fgColor", "color", event);\n },\n textColor: event => {\n setColor("textColor", "color", event);\n },\n borderColor: event => {\n setColor("borderColor", "borderColor", event);\n },\n strokeColor: event => {\n setColor("strokeColor", "borderColor", event);\n },\n rotation: event => {\n const angle = event.detail.rotation;\n this.setRotation(angle);\n this.annotationStorage.setValue(this.data.id, {\n rotation: angle\n });\n }\n });\n }\n _dispatchEventFromSandbox(actions, jsEvent) {\n const commonActions = this._commonActions;\n for (const name of Object.keys(jsEvent.detail)) {\n const action = actions[name] || commonActions[name];\n action?.(jsEvent);\n }\n }\n _setDefaultPropertiesFromJS(element) {\n if (!this.enableScripting) {\n return;\n }\n const storedData = this.annotationStorage.getRawValue(this.data.id);\n if (!storedData) {\n return;\n }\n const commonActions = this._commonActions;\n for (const [actionName, detail] of Object.entries(storedData)) {\n const action = commonActions[actionName];\n if (action) {\n const eventProxy = {\n detail: {\n [actionName]: detail\n },\n target: element\n };\n action(eventProxy);\n delete storedData[actionName];\n }\n }\n }\n _createQuadrilaterals() {\n if (!this.container) {\n return;\n }\n const {\n quadPoints\n } = this.data;\n if (!quadPoints) {\n return;\n }\n const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map(x => Math.fround(x));\n if (quadPoints.length === 8) {\n const [trX, trY, blX, blY] = quadPoints.subarray(2, 6);\n if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) {\n return;\n }\n }\n const {\n style\n } = this.container;\n let svgBuffer;\n if (this.#hasBorder) {\n const {\n borderColor,\n borderWidth\n } = style;\n style.borderWidth = 0;\n svgBuffer = ["url(\'data:image/svg+xml;utf8,", `<svg xmlns="http://www.w3.org/2000/svg"`, ` preserveAspectRatio="none" viewBox="0 0 1 1">`, `<g fill="transparent" stroke="${borderColor}" stroke-width="${borderWidth}">`];\n this.container.classList.add("hasBorder");\n }\n const width = rectTrX - rectBlX;\n const height = rectTrY - rectBlY;\n const {\n svgFactory\n } = this;\n const svg = svgFactory.createElement("svg");\n svg.classList.add("quadrilateralsContainer");\n svg.setAttribute("width", 0);\n svg.setAttribute("height", 0);\n svg.role = "none";\n const defs = svgFactory.createElement("defs");\n svg.append(defs);\n const clipPath = svgFactory.createElement("clipPath");\n const id = `clippath_${this.data.id}`;\n clipPath.setAttribute("id", id);\n clipPath.setAttribute("clipPathUnits", "objectBoundingBox");\n defs.append(clipPath);\n for (let i = 2, ii = quadPoints.length; i < ii; i += 8) {\n const trX = quadPoints[i];\n const trY = quadPoints[i + 1];\n const blX = quadPoints[i + 2];\n const blY = quadPoints[i + 3];\n const rect = svgFactory.createElement("rect");\n const x = (blX - rectBlX) / width;\n const y = (rectTrY - trY) / height;\n const rectWidth = (trX - blX) / width;\n const rectHeight = (trY - blY) / height;\n rect.setAttribute("x", x);\n rect.setAttribute("y", y);\n rect.setAttribute("width", rectWidth);\n rect.setAttribute("height", rectHeight);\n clipPath.append(rect);\n svgBuffer?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}"/>`);\n }\n if (this.#hasBorder) {\n svgBuffer.push(`</g></svg>\')`);\n style.backgroundImage = svgBuffer.join("");\n }\n this.container.append(svg);\n this.container.style.clipPath = `url(#${id})`;\n }\n _createPopup(popupData = null) {\n const {\n data\n } = this;\n let contentsObj, modificationDate;\n if (popupData) {\n contentsObj = {\n str: popupData.text\n };\n modificationDate = popupData.date;\n } else {\n contentsObj = data.contentsObj;\n modificationDate = data.modificationDate;\n }\n this.#popupElement = new PopupAnnotationElement({\n data: {\n color: data.color,\n titleObj: data.titleObj,\n modificationDate,\n contentsObj,\n richText: data.richText,\n parentRect: data.rect,\n borderStyle: 0,\n id: `popup_${data.id}`,\n rotation: data.rotation,\n noRotate: true\n },\n linkService: this.linkService,\n parent: this.parent,\n elements: [this]\n });\n }\n get hasPopupElement() {\n return !!(this.#popupElement || this.popup || this.data.popupRef);\n }\n get extraPopupElement() {\n return this.#popupElement;\n }\n render() {\n unreachable("Abstract method `AnnotationElement.render` called");\n }\n _getElementsByName(name, skipId = null) {\n const fields = [];\n if (this._fieldObjects) {\n const fieldObj = this._fieldObjects[name];\n if (fieldObj) {\n for (const {\n page,\n id,\n exportValues\n } of fieldObj) {\n if (page === -1) {\n continue;\n }\n if (id === skipId) {\n continue;\n }\n const exportValue = typeof exportValues === "string" ? exportValues : null;\n const domElement = document.querySelector(`[data-element-id="${id}"]`);\n if (domElement && !GetElementsByNameSet.has(domElement)) {\n warn(`_getElementsByName - element not allowed: ${id}`);\n continue;\n }\n fields.push({\n id,\n exportValue,\n domElement\n });\n }\n }\n return fields;\n }\n for (const domElement of document.getElementsByName(name)) {\n const {\n exportValue\n } = domElement;\n const id = domElement.getAttribute("data-element-id");\n if (id === skipId) {\n continue;\n }\n if (!GetElementsByNameSet.has(domElement)) {\n continue;\n }\n fields.push({\n id,\n exportValue,\n domElement\n });\n }\n return fields;\n }\n show() {\n if (this.container) {\n this.container.hidden = false;\n }\n this.popup?.maybeShow();\n }\n hide() {\n if (this.container) {\n this.container.hidden = true;\n }\n this.popup?.forceHide();\n }\n getElementsToTriggerPopup() {\n return this.container;\n }\n addHighlightArea() {\n const triggers = this.getElementsToTriggerPopup();\n if (Array.isArray(triggers)) {\n for (const element of triggers) {\n element.classList.add("highlightArea");\n }\n } else {\n triggers.classList.add("highlightArea");\n }\n }\n _editOnDoubleClick() {\n if (!this._isEditable) {\n return;\n }\n const {\n annotationEditorType: mode,\n data: {\n id: editId\n }\n } = this;\n this.container.addEventListener("dblclick", () => {\n this.linkService.eventBus?.dispatch("switchannotationeditormode", {\n source: this,\n mode,\n editId,\n mustEnterInEditMode: true\n });\n });\n }\n get width() {\n return this.data.rect[2] - this.data.rect[0];\n }\n get height() {\n return this.data.rect[3] - this.data.rect[1];\n }\n}\nclass EditorAnnotationElement extends AnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true\n });\n this.editor = parameters.editor;\n }\n render() {\n this.container.className = "editorAnnotation";\n return this.container;\n }\n createOrUpdatePopup() {\n const {\n editor\n } = this;\n if (!editor.hasComment) {\n return;\n }\n this._createPopup(editor.comment);\n }\n get hasCommentButton() {\n return this.enableComment && this.editor.hasComment;\n }\n get commentButtonPosition() {\n return this.editor.commentButtonPositionInPage;\n }\n get commentText() {\n return this.editor.comment.text;\n }\n set commentText(text) {\n this.editor.comment = text;\n if (!text) {\n this.removePopup();\n }\n }\n get commentData() {\n return this.editor.getData();\n }\n remove() {\n this.parent.removeAnnotation(this.data.id);\n this.container.remove();\n this.container = null;\n this.removePopup();\n }\n}\nclass LinkAnnotationElement extends AnnotationElement {\n constructor(parameters, options = null) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: !!options?.ignoreBorder,\n createQuadrilaterals: true\n });\n this.isTooltipOnly = parameters.data.isTooltipOnly;\n }\n render() {\n const {\n data,\n linkService\n } = this;\n const link = document.createElement("a");\n link.setAttribute("data-element-id", data.id);\n let isBound = false;\n if (data.url) {\n linkService.addLinkAttributes(link, data.url, data.newWindow);\n isBound = true;\n } else if (data.action) {\n this._bindNamedAction(link, data.action, data.overlaidText);\n isBound = true;\n } else if (data.attachment) {\n this.#bindAttachment(link, data.attachment, data.overlaidText, data.attachmentDest);\n isBound = true;\n } else if (data.setOCGState) {\n this.#bindSetOCGState(link, data.setOCGState, data.overlaidText);\n isBound = true;\n } else if (data.dest) {\n this._bindLink(link, data.dest, data.overlaidText);\n isBound = true;\n } else {\n if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {\n this._bindJSAction(link, data);\n isBound = true;\n }\n if (data.resetForm) {\n this._bindResetFormAction(link, data.resetForm);\n isBound = true;\n } else if (this.isTooltipOnly && !isBound) {\n this._bindLink(link, "");\n isBound = true;\n }\n }\n this.container.classList.add("linkAnnotation");\n if (isBound) {\n this.contentElement = link;\n this.container.append(link);\n }\n return this.container;\n }\n #setInternalLink() {\n this.container.setAttribute("data-internal-link", "");\n }\n _bindLink(link, destination, overlaidText = "") {\n link.href = this.linkService.getDestinationHash(destination);\n link.onclick = () => {\n if (destination) {\n this.linkService.goToDestination(destination);\n }\n return false;\n };\n if (destination || destination === "") {\n this.#setInternalLink();\n }\n if (overlaidText) {\n link.title = overlaidText;\n }\n }\n _bindNamedAction(link, action, overlaidText = "") {\n link.href = this.linkService.getAnchorUrl("");\n link.onclick = () => {\n this.linkService.executeNamedAction(action);\n return false;\n };\n if (overlaidText) {\n link.title = overlaidText;\n }\n this.#setInternalLink();\n }\n #bindAttachment(link, attachment, overlaidText = "", dest = null) {\n link.href = this.linkService.getAnchorUrl("");\n if (attachment.description) {\n link.title = attachment.description;\n } else if (overlaidText) {\n link.title = overlaidText;\n }\n link.onclick = () => {\n this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest);\n return false;\n };\n this.#setInternalLink();\n }\n #bindSetOCGState(link, action, overlaidText = "") {\n link.href = this.linkService.getAnchorUrl("");\n link.onclick = () => {\n this.linkService.executeSetOCGState(action);\n return false;\n };\n if (overlaidText) {\n link.title = overlaidText;\n }\n this.#setInternalLink();\n }\n _bindJSAction(link, data) {\n link.href = this.linkService.getAnchorUrl("");\n const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);\n for (const name of Object.keys(data.actions)) {\n const jsName = map.get(name);\n if (!jsName) {\n continue;\n }\n link[jsName] = () => {\n this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {\n source: this,\n detail: {\n id: data.id,\n name\n }\n });\n return false;\n };\n }\n if (data.overlaidText) {\n link.title = data.overlaidText;\n }\n if (!link.onclick) {\n link.onclick = () => false;\n }\n this.#setInternalLink();\n }\n _bindResetFormAction(link, resetForm) {\n const otherClickAction = link.onclick;\n if (!otherClickAction) {\n link.href = this.linkService.getAnchorUrl("");\n }\n this.#setInternalLink();\n if (!this._fieldObjects) {\n warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");\n if (!otherClickAction) {\n link.onclick = () => false;\n }\n return;\n }\n link.onclick = () => {\n otherClickAction?.();\n const {\n fields: resetFormFields,\n refs: resetFormRefs,\n include\n } = resetForm;\n const allFields = [];\n if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {\n const fieldIds = new Set(resetFormRefs);\n for (const fieldName of resetFormFields) {\n const fields = this._fieldObjects[fieldName] || [];\n for (const {\n id\n } of fields) {\n fieldIds.add(id);\n }\n }\n for (const fields of Object.values(this._fieldObjects)) {\n for (const field of fields) {\n if (fieldIds.has(field.id) === include) {\n allFields.push(field);\n }\n }\n }\n } else {\n for (const fields of Object.values(this._fieldObjects)) {\n allFields.push(...fields);\n }\n }\n const storage = this.annotationStorage;\n const allIds = [];\n for (const field of allFields) {\n const {\n id\n } = field;\n allIds.push(id);\n switch (field.type) {\n case "text":\n {\n const value = field.defaultValue || "";\n storage.setValue(id, {\n value\n });\n break;\n }\n case "checkbox":\n case "radiobutton":\n {\n const value = field.defaultValue === field.exportValues;\n storage.setValue(id, {\n value\n });\n break;\n }\n case "combobox":\n case "listbox":\n {\n const value = field.defaultValue || "";\n storage.setValue(id, {\n value\n });\n break;\n }\n default:\n continue;\n }\n const domElement = document.querySelector(`[data-element-id="${id}"]`);\n if (!domElement) {\n continue;\n } else if (!GetElementsByNameSet.has(domElement)) {\n warn(`_bindResetFormAction - element not allowed: ${id}`);\n continue;\n }\n domElement.dispatchEvent(new Event("resetform"));\n }\n if (this.enableScripting) {\n this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {\n source: this,\n detail: {\n id: "app",\n ids: allIds,\n name: "ResetForm"\n }\n });\n }\n return false;\n };\n }\n}\nclass TextAnnotationElement extends AnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: true\n });\n }\n render() {\n this.container.classList.add("textAnnotation");\n const image = document.createElement("img");\n image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";\n image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type");\n image.setAttribute("data-l10n-args", JSON.stringify({\n type: this.data.name\n }));\n if (!this.data.popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n this.container.append(image);\n return this.container;\n }\n}\nclass WidgetAnnotationElement extends AnnotationElement {\n render() {\n return this.container;\n }\n showElementAndHideCanvas(element) {\n if (this.data.hasOwnCanvas) {\n if (element.previousSibling?.nodeName === "CANVAS") {\n element.previousSibling.hidden = true;\n }\n element.hidden = false;\n }\n }\n _getKeyModifier(event) {\n return FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey;\n }\n _setEventListener(element, elementData, baseName, eventName, valueGetter) {\n if (baseName.includes("mouse")) {\n element.addEventListener(baseName, event => {\n this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {\n source: this,\n detail: {\n id: this.data.id,\n name: eventName,\n value: valueGetter(event),\n shift: event.shiftKey,\n modifier: this._getKeyModifier(event)\n }\n });\n });\n } else {\n element.addEventListener(baseName, event => {\n if (baseName === "blur") {\n if (!elementData.focused || !event.relatedTarget) {\n return;\n }\n elementData.focused = false;\n } else if (baseName === "focus") {\n if (elementData.focused) {\n return;\n }\n elementData.focused = true;\n }\n if (!valueGetter) {\n return;\n }\n this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {\n source: this,\n detail: {\n id: this.data.id,\n name: eventName,\n value: valueGetter(event)\n }\n });\n });\n }\n }\n _setEventListeners(element, elementData, names, getter) {\n for (const [baseName, eventName] of names) {\n if (eventName === "Action" || this.data.actions?.[eventName]) {\n if (eventName === "Focus" || eventName === "Blur") {\n elementData ||= {\n focused: false\n };\n }\n this._setEventListener(element, elementData, baseName, eventName, getter);\n if (eventName === "Focus" && !this.data.actions?.Blur) {\n this._setEventListener(element, elementData, "blur", "Blur", null);\n } else if (eventName === "Blur" && !this.data.actions?.Focus) {\n this._setEventListener(element, elementData, "focus", "Focus", null);\n }\n }\n }\n }\n _setBackgroundColor(element) {\n const color = this.data.backgroundColor || null;\n element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]);\n }\n _setTextStyle(element) {\n const TEXT_ALIGNMENT = ["left", "center", "right"];\n const {\n fontColor\n } = this.data.defaultAppearanceData;\n const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE;\n const style = element.style;\n let computedFontSize;\n const BORDER_SIZE = 2;\n const roundToOneDecimal = x => Math.round(10 * x) / 10;\n if (this.data.multiLine) {\n const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);\n const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1;\n const lineHeight = height / numberOfLines;\n computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR));\n } else {\n const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);\n computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR));\n }\n style.fontSize = `calc(${computedFontSize}px * var(--total-scale-factor))`;\n style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);\n if (this.data.textAlignment !== null) {\n style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];\n }\n }\n _setRequired(element, isRequired) {\n if (isRequired) {\n element.setAttribute("required", true);\n } else {\n element.removeAttribute("required");\n }\n element.setAttribute("aria-required", isRequired);\n }\n}\nclass TextWidgetAnnotationElement extends WidgetAnnotationElement {\n constructor(parameters) {\n const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue;\n super(parameters, {\n isRenderable\n });\n }\n setPropertyOnSiblings(base, key, value, keyInStorage) {\n const storage = this.annotationStorage;\n for (const element of this._getElementsByName(base.name, base.id)) {\n if (element.domElement) {\n element.domElement[key] = value;\n }\n storage.setValue(element.id, {\n [keyInStorage]: value\n });\n }\n }\n render() {\n const storage = this.annotationStorage;\n const id = this.data.id;\n this.container.classList.add("textWidgetAnnotation");\n let element = null;\n if (this.renderForms) {\n const storedData = storage.getValue(id, {\n value: this.data.fieldValue\n });\n let textContent = storedData.value || "";\n const maxLen = storage.getValue(id, {\n charLimit: this.data.maxLen\n }).charLimit;\n if (maxLen && textContent.length > maxLen) {\n textContent = textContent.slice(0, maxLen);\n }\n let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\\n") || null;\n if (fieldFormattedValues && this.data.comb) {\n fieldFormattedValues = fieldFormattedValues.replaceAll(/\\s+/g, "");\n }\n const elementData = {\n userValue: textContent,\n formattedValue: fieldFormattedValues,\n lastCommittedValue: null,\n commitKey: 1,\n focused: false\n };\n if (this.data.multiLine) {\n element = document.createElement("textarea");\n element.textContent = fieldFormattedValues ?? textContent;\n if (this.data.doNotScroll) {\n element.style.overflowY = "hidden";\n }\n } else {\n element = document.createElement("input");\n element.type = this.data.password ? "password" : "text";\n element.setAttribute("value", fieldFormattedValues ?? textContent);\n if (this.data.doNotScroll) {\n element.style.overflowX = "hidden";\n }\n }\n if (this.data.hasOwnCanvas) {\n element.hidden = true;\n }\n GetElementsByNameSet.add(element);\n this.contentElement = element;\n element.setAttribute("data-element-id", id);\n element.disabled = this.data.readOnly;\n element.name = this.data.fieldName;\n element.tabIndex = 0;\n const {\n datetimeFormat,\n datetimeType,\n timeStep\n } = this.data;\n const hasDateOrTime = !!datetimeType && this.enableScripting;\n if (datetimeFormat) {\n element.title = datetimeFormat;\n }\n this._setRequired(element, this.data.required);\n if (maxLen) {\n element.maxLength = maxLen;\n }\n element.addEventListener("input", event => {\n storage.setValue(id, {\n value: event.target.value\n });\n this.setPropertyOnSiblings(element, "value", event.target.value, "value");\n elementData.formattedValue = null;\n });\n element.addEventListener("resetform", event => {\n const defaultValue = this.data.defaultFieldValue ?? "";\n element.value = elementData.userValue = defaultValue;\n elementData.formattedValue = null;\n });\n let blurListener = event => {\n const {\n formattedValue\n } = elementData;\n if (formattedValue !== null && formattedValue !== undefined) {\n event.target.value = formattedValue;\n }\n event.target.scrollLeft = 0;\n };\n if (this.enableScripting && this.hasJSActions) {\n element.addEventListener("focus", event => {\n if (elementData.focused) {\n return;\n }\n const {\n target\n } = event;\n if (hasDateOrTime) {\n target.type = datetimeType;\n if (timeStep) {\n target.step = timeStep;\n }\n }\n if (elementData.userValue) {\n const value = elementData.userValue;\n if (hasDateOrTime) {\n if (datetimeType === "time") {\n const date = new Date(value);\n const parts = [date.getHours(), date.getMinutes(), date.getSeconds()];\n target.value = parts.map(v => v.toString().padStart(2, "0")).join(":");\n } else {\n target.value = new Date(value - TIMEZONE_OFFSET).toISOString().split(datetimeType === "date" ? "T" : ".", 1)[0];\n }\n } else {\n target.value = value;\n }\n }\n elementData.lastCommittedValue = target.value;\n elementData.commitKey = 1;\n if (!this.data.actions?.Focus) {\n elementData.focused = true;\n }\n });\n element.addEventListener("updatefromsandbox", jsEvent => {\n this.showElementAndHideCanvas(jsEvent.target);\n const actions = {\n value(event) {\n elementData.userValue = event.detail.value ?? "";\n if (!hasDateOrTime) {\n storage.setValue(id, {\n value: elementData.userValue.toString()\n });\n }\n event.target.value = elementData.userValue;\n },\n formattedValue(event) {\n const {\n formattedValue\n } = event.detail;\n elementData.formattedValue = formattedValue;\n if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {\n event.target.value = formattedValue;\n }\n const data = {\n formattedValue\n };\n if (hasDateOrTime) {\n data.value = formattedValue;\n }\n storage.setValue(id, data);\n },\n selRange(event) {\n event.target.setSelectionRange(...event.detail.selRange);\n },\n charLimit: event => {\n const {\n charLimit\n } = event.detail;\n const {\n target\n } = event;\n if (charLimit === 0) {\n target.removeAttribute("maxLength");\n return;\n }\n target.setAttribute("maxLength", charLimit);\n let value = elementData.userValue;\n if (!value || value.length <= charLimit) {\n return;\n }\n value = value.slice(0, charLimit);\n target.value = elementData.userValue = value;\n storage.setValue(id, {\n value\n });\n this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {\n source: this,\n detail: {\n id,\n name: "Keystroke",\n value,\n willCommit: true,\n commitKey: 1,\n selStart: target.selectionStart,\n selEnd: target.selectionEnd\n }\n });\n }\n };\n this._dispatchEventFromSandbox(actions, jsEvent);\n });\n element.addEventListener("keydown", event => {\n elementData.commitKey = 1;\n let commitKey = -1;\n if (event.key === "Escape") {\n commitKey = 0;\n } else if (event.key === "Enter" && !this.data.multiLine) {\n commitKey = 2;\n } else if (event.key === "Tab") {\n elementData.commitKey = 3;\n }\n if (commitKey === -1) {\n return;\n }\n const {\n value\n } = event.target;\n if (elementData.lastCommittedValue === value) {\n return;\n }\n elementData.lastCommittedValue = value;\n elementData.userValue = value;\n this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {\n source: this,\n detail: {\n id,\n name: "Keystroke",\n value,\n willCommit: true,\n commitKey,\n selStart: event.target.selectionStart,\n selEnd: event.target.selectionEnd\n }\n });\n });\n const _blurListener = blurListener;\n blurListener = null;\n element.addEventListener("blur", event => {\n if (!elementData.focused || !event.relatedTarget) {\n return;\n }\n if (!this.data.actions?.Blur) {\n elementData.focused = false;\n }\n const {\n target\n } = event;\n let {\n value\n } = target;\n if (hasDateOrTime) {\n if (value && datetimeType === "time") {\n const parts = value.split(":").map(v => parseInt(v, 10));\n value = new Date(2000, 0, 1, parts[0], parts[1], parts[2] || 0).valueOf();\n target.step = "";\n } else {\n if (!value.includes("T")) {\n value = `${value}T00:00`;\n }\n value = new Date(value).valueOf();\n }\n target.type = "text";\n }\n elementData.userValue = value;\n if (elementData.lastCommittedValue !== value) {\n this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {\n source: this,\n detail: {\n id,\n name: "Keystroke",\n value,\n willCommit: true,\n commitKey: elementData.commitKey,\n selStart: event.target.selectionStart,\n selEnd: event.target.selectionEnd\n }\n });\n }\n _blurListener(event);\n });\n if (this.data.actions?.Keystroke) {\n element.addEventListener("beforeinput", event => {\n elementData.lastCommittedValue = null;\n const {\n data,\n target\n } = event;\n const {\n value,\n selectionStart,\n selectionEnd\n } = target;\n let selStart = selectionStart,\n selEnd = selectionEnd;\n switch (event.inputType) {\n case "deleteWordBackward":\n {\n const match = value.substring(0, selectionStart).match(/\\w*[^\\w]*$/);\n if (match) {\n selStart -= match[0].length;\n }\n break;\n }\n case "deleteWordForward":\n {\n const match = value.substring(selectionStart).match(/^[^\\w]*\\w*/);\n if (match) {\n selEnd += match[0].length;\n }\n break;\n }\n case "deleteContentBackward":\n if (selectionStart === selectionEnd) {\n selStart -= 1;\n }\n break;\n case "deleteContentForward":\n if (selectionStart === selectionEnd) {\n selEnd += 1;\n }\n break;\n }\n event.preventDefault();\n this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {\n source: this,\n detail: {\n id,\n name: "Keystroke",\n value,\n change: data || "",\n willCommit: false,\n selStart,\n selEnd\n }\n });\n });\n }\n this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);\n }\n if (blurListener) {\n element.addEventListener("blur", blurListener);\n }\n if (this.data.comb) {\n const fieldWidth = this.data.rect[2] - this.data.rect[0];\n const combWidth = fieldWidth / maxLen;\n element.classList.add("comb");\n element.style.letterSpacing = `calc(${combWidth}px * var(--total-scale-factor) - 1ch)`;\n }\n } else {\n element = document.createElement("div");\n element.textContent = this.data.fieldValue;\n element.style.verticalAlign = "middle";\n element.style.display = "table-cell";\n if (this.data.hasOwnCanvas) {\n element.hidden = true;\n }\n }\n this._setTextStyle(element);\n this._setBackgroundColor(element);\n this._setDefaultPropertiesFromJS(element);\n this.container.append(element);\n return this.container;\n }\n}\nclass SignatureWidgetAnnotationElement extends WidgetAnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: !!parameters.data.hasOwnCanvas\n });\n }\n}\nclass CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: parameters.renderForms\n });\n }\n render() {\n const storage = this.annotationStorage;\n const data = this.data;\n const id = data.id;\n let value = storage.getValue(id, {\n value: data.exportValue === data.fieldValue\n }).value;\n if (typeof value === "string") {\n value = value !== "Off";\n storage.setValue(id, {\n value\n });\n }\n this.container.classList.add("buttonWidgetAnnotation", "checkBox");\n const element = document.createElement("input");\n GetElementsByNameSet.add(element);\n element.setAttribute("data-element-id", id);\n element.disabled = data.readOnly;\n this._setRequired(element, this.data.required);\n element.type = "checkbox";\n element.name = data.fieldName;\n if (value) {\n element.setAttribute("checked", true);\n }\n element.setAttribute("exportValue", data.exportValue);\n element.tabIndex = 0;\n element.addEventListener("change", event => {\n const {\n name,\n checked\n } = event.target;\n for (const checkbox of this._getElementsByName(name, id)) {\n const curChecked = checked && checkbox.exportValue === data.exportValue;\n if (checkbox.domElement) {\n checkbox.domElement.checked = curChecked;\n }\n storage.setValue(checkbox.id, {\n value: curChecked\n });\n }\n storage.setValue(id, {\n value: checked\n });\n });\n element.addEventListener("resetform", event => {\n const defaultValue = data.defaultFieldValue || "Off";\n event.target.checked = defaultValue === data.exportValue;\n });\n if (this.enableScripting && this.hasJSActions) {\n element.addEventListener("updatefromsandbox", jsEvent => {\n const actions = {\n value(event) {\n event.target.checked = event.detail.value !== "Off";\n storage.setValue(id, {\n value: event.target.checked\n });\n }\n };\n this._dispatchEventFromSandbox(actions, jsEvent);\n });\n this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);\n }\n this._setBackgroundColor(element);\n this._setDefaultPropertiesFromJS(element);\n this.container.append(element);\n return this.container;\n }\n}\nclass RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: parameters.renderForms\n });\n }\n render() {\n this.container.classList.add("buttonWidgetAnnotation", "radioButton");\n const storage = this.annotationStorage;\n const data = this.data;\n const id = data.id;\n let value = storage.getValue(id, {\n value: data.fieldValue === data.buttonValue\n }).value;\n if (typeof value === "string") {\n value = value !== data.buttonValue;\n storage.setValue(id, {\n value\n });\n }\n if (value) {\n for (const radio of this._getElementsByName(data.fieldName, id)) {\n storage.setValue(radio.id, {\n value: false\n });\n }\n }\n const element = document.createElement("input");\n GetElementsByNameSet.add(element);\n element.setAttribute("data-element-id", id);\n element.disabled = data.readOnly;\n this._setRequired(element, this.data.required);\n element.type = "radio";\n element.name = data.fieldName;\n if (value) {\n element.setAttribute("checked", true);\n }\n element.tabIndex = 0;\n element.addEventListener("change", event => {\n const {\n name,\n checked\n } = event.target;\n for (const radio of this._getElementsByName(name, id)) {\n storage.setValue(radio.id, {\n value: false\n });\n }\n storage.setValue(id, {\n value: checked\n });\n });\n element.addEventListener("resetform", event => {\n const defaultValue = data.defaultFieldValue;\n event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;\n });\n if (this.enableScripting && this.hasJSActions) {\n const pdfButtonValue = data.buttonValue;\n element.addEventListener("updatefromsandbox", jsEvent => {\n const actions = {\n value: event => {\n const checked = pdfButtonValue === event.detail.value;\n for (const radio of this._getElementsByName(event.target.name)) {\n const curChecked = checked && radio.id === id;\n if (radio.domElement) {\n radio.domElement.checked = curChecked;\n }\n storage.setValue(radio.id, {\n value: curChecked\n });\n }\n }\n };\n this._dispatchEventFromSandbox(actions, jsEvent);\n });\n this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);\n }\n this._setBackgroundColor(element);\n this._setDefaultPropertiesFromJS(element);\n this.container.append(element);\n return this.container;\n }\n}\nclass PushButtonWidgetAnnotationElement extends LinkAnnotationElement {\n constructor(parameters) {\n super(parameters, {\n ignoreBorder: parameters.data.hasAppearance\n });\n }\n render() {\n const container = super.render();\n container.classList.add("buttonWidgetAnnotation", "pushButton");\n const linkElement = container.lastChild;\n if (this.enableScripting && this.hasJSActions && linkElement) {\n this._setDefaultPropertiesFromJS(linkElement);\n linkElement.addEventListener("updatefromsandbox", jsEvent => {\n this._dispatchEventFromSandbox({}, jsEvent);\n });\n }\n return container;\n }\n}\nclass ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: parameters.renderForms\n });\n }\n render() {\n this.container.classList.add("choiceWidgetAnnotation");\n const storage = this.annotationStorage;\n const id = this.data.id;\n const storedData = storage.getValue(id, {\n value: this.data.fieldValue\n });\n const selectElement = document.createElement("select");\n GetElementsByNameSet.add(selectElement);\n selectElement.setAttribute("data-element-id", id);\n selectElement.disabled = this.data.readOnly;\n this._setRequired(selectElement, this.data.required);\n selectElement.name = this.data.fieldName;\n selectElement.tabIndex = 0;\n let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;\n if (!this.data.combo) {\n selectElement.size = this.data.options.length;\n if (this.data.multiSelect) {\n selectElement.multiple = true;\n }\n }\n selectElement.addEventListener("resetform", event => {\n const defaultValue = this.data.defaultFieldValue;\n for (const option of selectElement.options) {\n option.selected = option.value === defaultValue;\n }\n });\n for (const option of this.data.options) {\n const optionElement = document.createElement("option");\n optionElement.textContent = option.displayValue;\n optionElement.value = option.exportValue;\n if (storedData.value.includes(option.exportValue)) {\n optionElement.setAttribute("selected", true);\n addAnEmptyEntry = false;\n }\n selectElement.append(optionElement);\n }\n let removeEmptyEntry = null;\n if (addAnEmptyEntry) {\n const noneOptionElement = document.createElement("option");\n noneOptionElement.value = " ";\n noneOptionElement.setAttribute("hidden", true);\n noneOptionElement.setAttribute("selected", true);\n selectElement.prepend(noneOptionElement);\n removeEmptyEntry = () => {\n noneOptionElement.remove();\n selectElement.removeEventListener("input", removeEmptyEntry);\n removeEmptyEntry = null;\n };\n selectElement.addEventListener("input", removeEmptyEntry);\n }\n const getValue = isExport => {\n const name = isExport ? "value" : "textContent";\n const {\n options,\n multiple\n } = selectElement;\n if (!multiple) {\n return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];\n }\n return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);\n };\n let selectedValues = getValue(false);\n const getItems = event => {\n const options = event.target.options;\n return Array.prototype.map.call(options, option => ({\n displayValue: option.textContent,\n exportValue: option.value\n }));\n };\n if (this.enableScripting && this.hasJSActions) {\n selectElement.addEventListener("updatefromsandbox", jsEvent => {\n const actions = {\n value(event) {\n removeEmptyEntry?.();\n const value = event.detail.value;\n const values = new Set(Array.isArray(value) ? value : [value]);\n for (const option of selectElement.options) {\n option.selected = values.has(option.value);\n }\n storage.setValue(id, {\n value: getValue(true)\n });\n selectedValues = getValue(false);\n },\n multipleSelection(event) {\n selectElement.multiple = true;\n },\n remove(event) {\n const options = selectElement.options;\n const index = event.detail.remove;\n options[index].selected = false;\n selectElement.remove(index);\n if (options.length > 0) {\n const i = Array.prototype.findIndex.call(options, option => option.selected);\n if (i === -1) {\n options[0].selected = true;\n }\n }\n storage.setValue(id, {\n value: getValue(true),\n items: getItems(event)\n });\n selectedValues = getValue(false);\n },\n clear(event) {\n while (selectElement.length !== 0) {\n selectElement.remove(0);\n }\n storage.setValue(id, {\n value: null,\n items: []\n });\n selectedValues = getValue(false);\n },\n insert(event) {\n const {\n index,\n displayValue,\n exportValue\n } = event.detail.insert;\n const selectChild = selectElement.children[index];\n const optionElement = document.createElement("option");\n optionElement.textContent = displayValue;\n optionElement.value = exportValue;\n if (selectChild) {\n selectChild.before(optionElement);\n } else {\n selectElement.append(optionElement);\n }\n storage.setValue(id, {\n value: getValue(true),\n items: getItems(event)\n });\n selectedValues = getValue(false);\n },\n items(event) {\n const {\n items\n } = event.detail;\n while (selectElement.length !== 0) {\n selectElement.remove(0);\n }\n for (const item of items) {\n const {\n displayValue,\n exportValue\n } = item;\n const optionElement = document.createElement("option");\n optionElement.textContent = displayValue;\n optionElement.value = exportValue;\n selectElement.append(optionElement);\n }\n if (selectElement.options.length > 0) {\n selectElement.options[0].selected = true;\n }\n storage.setValue(id, {\n value: getValue(true),\n items: getItems(event)\n });\n selectedValues = getValue(false);\n },\n indices(event) {\n const indices = new Set(event.detail.indices);\n for (const option of event.target.options) {\n option.selected = indices.has(option.index);\n }\n storage.setValue(id, {\n value: getValue(true)\n });\n selectedValues = getValue(false);\n },\n editable(event) {\n event.target.disabled = !event.detail.editable;\n }\n };\n this._dispatchEventFromSandbox(actions, jsEvent);\n });\n selectElement.addEventListener("input", event => {\n const exportValue = getValue(true);\n const change = getValue(false);\n storage.setValue(id, {\n value: exportValue\n });\n event.preventDefault();\n this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {\n source: this,\n detail: {\n id,\n name: "Keystroke",\n value: selectedValues,\n change,\n changeEx: exportValue,\n willCommit: false,\n commitKey: 1,\n keyDown: false\n }\n });\n });\n this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value);\n } else {\n selectElement.addEventListener("input", function (event) {\n storage.setValue(id, {\n value: getValue(true)\n });\n });\n }\n if (this.data.combo) {\n this._setTextStyle(selectElement);\n } else {}\n this._setBackgroundColor(selectElement);\n this._setDefaultPropertiesFromJS(selectElement);\n this.container.append(selectElement);\n return this.container;\n }\n}\nclass PopupAnnotationElement extends AnnotationElement {\n constructor(parameters) {\n const {\n data,\n elements,\n parent\n } = parameters;\n const hasCommentManager = !!parent._commentManager;\n super(parameters, {\n isRenderable: !hasCommentManager && AnnotationElement._hasPopupData(data)\n });\n this.elements = elements;\n if (hasCommentManager && AnnotationElement._hasPopupData(data)) {\n const popup = this.popup = this.#createPopup();\n for (const element of elements) {\n element.popup = popup;\n }\n } else {\n this.popup = null;\n }\n }\n #createPopup() {\n return new PopupElement({\n container: this.container,\n color: this.data.color,\n titleObj: this.data.titleObj,\n modificationDate: this.data.modificationDate || this.data.creationDate,\n contentsObj: this.data.contentsObj,\n richText: this.data.richText,\n rect: this.data.rect,\n parentRect: this.data.parentRect || null,\n parent: this.parent,\n elements: this.elements,\n open: this.data.open,\n commentManager: this.parent._commentManager\n });\n }\n render() {\n const {\n container\n } = this;\n container.classList.add("popupAnnotation");\n container.role = "comment";\n const popup = this.popup = this.#createPopup();\n const elementIds = [];\n for (const element of this.elements) {\n element.popup = popup;\n element.container.ariaHasPopup = "dialog";\n elementIds.push(element.data.id);\n element.addHighlightArea();\n }\n this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(","));\n return this.container;\n }\n}\nclass PopupElement {\n #commentManager = null;\n #boundKeyDown = this.#keyDown.bind(this);\n #boundHide = this.#hide.bind(this);\n #boundShow = this.#show.bind(this);\n #boundToggle = this.#toggle.bind(this);\n #color = null;\n #container = null;\n #contentsObj = null;\n #dateObj = null;\n #elements = null;\n #parent = null;\n #parentRect = null;\n #pinned = false;\n #popup = null;\n #popupAbortController = null;\n #position = null;\n #commentButton = null;\n #commentButtonPosition = null;\n #popupPosition = null;\n #rect = null;\n #richText = null;\n #titleObj = null;\n #updates = null;\n #wasVisible = false;\n #firstElement = null;\n #commentText = null;\n constructor({\n container,\n color,\n elements,\n titleObj,\n modificationDate,\n contentsObj,\n richText,\n parent,\n rect,\n parentRect,\n open,\n commentManager = null\n }) {\n this.#container = container;\n this.#titleObj = titleObj;\n this.#contentsObj = contentsObj;\n this.#richText = richText;\n this.#parent = parent;\n this.#color = color;\n this.#rect = rect;\n this.#parentRect = parentRect;\n this.#elements = elements;\n this.#commentManager = commentManager;\n this.#firstElement = elements[0];\n this.#dateObj = PDFDateString.toDateObject(modificationDate);\n this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup());\n if (!commentManager) {\n this.#addEventListeners();\n this.#container.hidden = true;\n if (open) {\n this.#toggle();\n }\n }\n }\n #addEventListeners() {\n if (this.#popupAbortController) {\n return;\n }\n this.#popupAbortController = new AbortController();\n const {\n signal\n } = this.#popupAbortController;\n for (const element of this.trigger) {\n element.addEventListener("click", this.#boundToggle, {\n signal\n });\n element.addEventListener("pointerenter", this.#boundShow, {\n signal\n });\n element.addEventListener("pointerleave", this.#boundHide, {\n signal\n });\n element.classList.add("popupTriggerArea");\n }\n for (const element of this.#elements) {\n element.container?.addEventListener("keydown", this.#boundKeyDown, {\n signal\n });\n }\n }\n #setCommentButtonPosition() {\n const element = this.#elements.find(e => e.hasCommentButton);\n if (!element) {\n return;\n }\n this.#commentButtonPosition = element._normalizePoint(element.commentButtonPosition);\n }\n renderCommentButton() {\n if (this.#commentButton) {\n if (!this.#commentButton.parentNode) {\n this.#firstElement.container.after(this.#commentButton);\n }\n return;\n }\n if (!this.#commentButtonPosition) {\n this.#setCommentButtonPosition();\n }\n if (!this.#commentButtonPosition) {\n return;\n }\n const {\n signal\n } = this.#popupAbortController = new AbortController();\n const hasOwnButton = this.#firstElement.hasOwnCommentButton;\n const togglePopup = () => {\n this.#commentManager.toggleCommentPopup(this, true, undefined, !hasOwnButton);\n };\n const showPopup = () => {\n this.#commentManager.toggleCommentPopup(this, false, true, !hasOwnButton);\n };\n const hidePopup = () => {\n this.#commentManager.toggleCommentPopup(this, false, false);\n };\n if (!hasOwnButton) {\n const button = this.#commentButton = document.createElement("button");\n button.className = "annotationCommentButton";\n const parentContainer = this.#firstElement.container;\n button.style.zIndex = parentContainer.style.zIndex + 1;\n button.tabIndex = 0;\n button.ariaHasPopup = "dialog";\n button.ariaControls = "commentPopup";\n button.setAttribute("data-l10n-id", "pdfjs-show-comment-button");\n this.#updateColor();\n this.#updateCommentButtonPosition();\n button.addEventListener("keydown", this.#boundKeyDown, {\n signal\n });\n button.addEventListener("click", togglePopup, {\n signal\n });\n button.addEventListener("pointerenter", showPopup, {\n signal\n });\n button.addEventListener("pointerleave", hidePopup, {\n signal\n });\n parentContainer.after(button);\n } else {\n this.#commentButton = this.#firstElement.container;\n for (const element of this.trigger) {\n element.ariaHasPopup = "dialog";\n element.ariaControls = "commentPopup";\n element.addEventListener("keydown", this.#boundKeyDown, {\n signal\n });\n element.addEventListener("click", togglePopup, {\n signal\n });\n element.addEventListener("pointerenter", showPopup, {\n signal\n });\n element.addEventListener("pointerleave", hidePopup, {\n signal\n });\n element.classList.add("popupTriggerArea");\n }\n }\n }\n #updateCommentButtonPosition() {\n if (this.#firstElement.extraPopupElement && !this.#firstElement.editor) {\n return;\n }\n if (!this.#commentButton) {\n this.renderCommentButton();\n }\n const [x, y] = this.#commentButtonPosition;\n const {\n style\n } = this.#commentButton;\n style.left = `calc(${x}%)`;\n style.top = `calc(${y}% - var(--comment-button-dim))`;\n }\n #updateColor() {\n if (this.#firstElement.extraPopupElement) {\n return;\n }\n if (!this.#commentButton) {\n this.renderCommentButton();\n }\n this.#commentButton.style.backgroundColor = this.commentButtonColor || "";\n }\n get commentButtonColor() {\n const {\n color,\n opacity\n } = this.#firstElement.commentData;\n if (!color) {\n return null;\n }\n return this.#parent._commentManager.makeCommentColor(color, opacity);\n }\n focusCommentButton() {\n setTimeout(() => {\n this.#commentButton?.focus();\n }, 0);\n }\n getData() {\n const {\n richText,\n color,\n opacity,\n creationDate,\n modificationDate\n } = this.#firstElement.commentData;\n return {\n contentsObj: {\n str: this.comment\n },\n richText,\n color,\n opacity,\n creationDate,\n modificationDate\n };\n }\n get elementBeforePopup() {\n return this.#commentButton;\n }\n get comment() {\n this.#commentText ||= this.#firstElement.commentText;\n return this.#commentText;\n }\n set comment(text) {\n if (text === this.comment) {\n return;\n }\n this.#firstElement.commentText = this.#commentText = text;\n }\n focus() {\n this.#firstElement.container?.focus();\n }\n get parentBoundingClientRect() {\n return this.#firstElement.layer.getBoundingClientRect();\n }\n setCommentButtonStates({\n selected,\n hasPopup\n }) {\n if (!this.#commentButton) {\n return;\n }\n this.#commentButton.classList.toggle("selected", selected);\n this.#commentButton.ariaExpanded = hasPopup;\n }\n setSelectedCommentButton(selected) {\n this.#commentButton.classList.toggle("selected", selected);\n }\n get commentPopupPosition() {\n if (this.#popupPosition) {\n return this.#popupPosition;\n }\n const {\n x,\n y,\n height\n } = this.#commentButton.getBoundingClientRect();\n const {\n x: parentX,\n y: parentY,\n width: parentWidth,\n height: parentHeight\n } = this.#firstElement.layer.getBoundingClientRect();\n return [(x - parentX) / parentWidth, (y + height - parentY) / parentHeight];\n }\n set commentPopupPosition(pos) {\n this.#popupPosition = pos;\n }\n hasDefaultPopupPosition() {\n return this.#popupPosition === null;\n }\n get commentButtonPosition() {\n return this.#commentButtonPosition;\n }\n get commentButtonWidth() {\n return this.#commentButton.getBoundingClientRect().width / this.parentBoundingClientRect.width;\n }\n editComment(options) {\n const [posX, posY] = this.#popupPosition || this.commentButtonPosition.map(x => x / 100);\n const parentDimensions = this.parentBoundingClientRect;\n const {\n x: parentX,\n y: parentY,\n width: parentWidth,\n height: parentHeight\n } = parentDimensions;\n this.#commentManager.showDialog(null, this, parentX + posX * parentWidth, parentY + posY * parentHeight, {\n ...options,\n parentDimensions\n });\n }\n render() {\n if (this.#popup) {\n return;\n }\n const popup = this.#popup = document.createElement("div");\n popup.className = "popup";\n if (this.#color) {\n const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color);\n popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`;\n }\n const header = document.createElement("span");\n header.className = "header";\n if (this.#titleObj?.str) {\n const title = document.createElement("span");\n title.className = "title";\n header.append(title);\n ({\n dir: title.dir,\n str: title.textContent\n } = this.#titleObj);\n }\n popup.append(header);\n if (this.#dateObj) {\n const modificationDate = document.createElement("time");\n modificationDate.className = "popupDate";\n modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string");\n modificationDate.setAttribute("data-l10n-args", JSON.stringify({\n dateObj: this.#dateObj.valueOf()\n }));\n modificationDate.dateTime = this.#dateObj.toISOString();\n header.append(modificationDate);\n }\n renderRichText({\n html: this.#html || this.#contentsObj.str,\n dir: this.#contentsObj?.dir,\n className: "popupContent"\n }, popup);\n this.#container.append(popup);\n }\n get #html() {\n const richText = this.#richText;\n const contentsObj = this.#contentsObj;\n if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) {\n return this.#richText.html || null;\n }\n return null;\n }\n get #fontSize() {\n return this.#html?.attributes?.style?.fontSize || 0;\n }\n get #fontColor() {\n return this.#html?.attributes?.style?.color || null;\n }\n #makePopupContent(text) {\n const popupLines = [];\n const popupContent = {\n str: text,\n html: {\n name: "div",\n attributes: {\n dir: "auto"\n },\n children: [{\n name: "p",\n children: popupLines\n }]\n }\n };\n const lineAttributes = {\n style: {\n color: this.#fontColor,\n fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--total-scale-factor))` : ""\n }\n };\n for (const line of text.split("\\n")) {\n popupLines.push({\n name: "span",\n value: line,\n attributes: lineAttributes\n });\n }\n return popupContent;\n }\n #keyDown(event) {\n if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {\n return;\n }\n if (event.key === "Enter" || event.key === "Escape" && this.#pinned) {\n this.#toggle();\n }\n }\n updateEdited({\n rect,\n popup,\n deleted\n }) {\n if (this.#commentManager) {\n if (deleted) {\n this.remove();\n this.#commentText = null;\n } else if (popup) {\n if (popup.deleted) {\n this.remove();\n } else {\n this.#updateColor();\n this.#commentText = popup.text;\n }\n }\n if (rect) {\n this.#commentButtonPosition = null;\n this.#setCommentButtonPosition();\n this.#updateCommentButtonPosition();\n }\n return;\n }\n if (deleted || popup?.deleted) {\n this.remove();\n return;\n }\n this.#addEventListeners();\n this.#updates ||= {\n contentsObj: this.#contentsObj,\n richText: this.#richText\n };\n if (rect) {\n this.#position = null;\n }\n if (popup && popup.text) {\n this.#richText = this.#makePopupContent(popup.text);\n this.#dateObj = PDFDateString.toDateObject(popup.date);\n this.#contentsObj = null;\n }\n this.#popup?.remove();\n this.#popup = null;\n }\n resetEdited() {\n if (!this.#updates) {\n return;\n }\n ({\n contentsObj: this.#contentsObj,\n richText: this.#richText\n } = this.#updates);\n this.#updates = null;\n this.#popup?.remove();\n this.#popup = null;\n this.#position = null;\n }\n remove() {\n this.#popupAbortController?.abort();\n this.#popupAbortController = null;\n this.#popup?.remove();\n this.#popup = null;\n this.#wasVisible = false;\n this.#pinned = false;\n this.#commentButton?.remove();\n this.#commentButton = null;\n if (this.trigger) {\n for (const element of this.trigger) {\n element.classList.remove("popupTriggerArea");\n }\n }\n }\n #setPosition() {\n if (this.#position !== null) {\n return;\n }\n const {\n page: {\n view\n },\n viewport: {\n rawDims: {\n pageWidth,\n pageHeight,\n pageX,\n pageY\n }\n }\n } = this.#parent;\n let useParentRect = !!this.#parentRect;\n let rect = useParentRect ? this.#parentRect : this.#rect;\n for (const element of this.#elements) {\n if (!rect || Util.intersect(element.data.rect, rect) !== null) {\n rect = element.data.rect;\n useParentRect = true;\n break;\n }\n }\n const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]);\n const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5;\n const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0;\n const popupLeft = normalizedRect[0] + parentWidth;\n const popupTop = normalizedRect[1];\n this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight];\n const {\n style\n } = this.#container;\n style.left = `${this.#position[0]}%`;\n style.top = `${this.#position[1]}%`;\n }\n #toggle() {\n if (this.#commentManager) {\n this.#commentManager.toggleCommentPopup(this, false);\n return;\n }\n this.#pinned = !this.#pinned;\n if (this.#pinned) {\n this.#show();\n this.#container.addEventListener("click", this.#boundToggle);\n this.#container.addEventListener("keydown", this.#boundKeyDown);\n } else {\n this.#hide();\n this.#container.removeEventListener("click", this.#boundToggle);\n this.#container.removeEventListener("keydown", this.#boundKeyDown);\n }\n }\n #show() {\n if (!this.#popup) {\n this.render();\n }\n if (!this.isVisible) {\n this.#setPosition();\n this.#container.hidden = false;\n this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000;\n } else if (this.#pinned) {\n this.#container.classList.add("focused");\n }\n }\n #hide() {\n this.#container.classList.remove("focused");\n if (this.#pinned || !this.isVisible) {\n return;\n }\n this.#container.hidden = true;\n this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000;\n }\n forceHide() {\n this.#wasVisible = this.isVisible;\n if (!this.#wasVisible) {\n return;\n }\n this.#container.hidden = true;\n }\n maybeShow() {\n if (this.#commentManager) {\n return;\n }\n this.#addEventListeners();\n if (!this.#wasVisible) {\n return;\n }\n if (!this.#popup) {\n this.#show();\n }\n this.#wasVisible = false;\n this.#container.hidden = false;\n }\n get isVisible() {\n if (this.#commentManager) {\n return false;\n }\n return this.#container.hidden === false;\n }\n}\nclass FreeTextAnnotationElement extends AnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true\n });\n this.textContent = parameters.data.textContent;\n this.textPosition = parameters.data.textPosition;\n this.annotationEditorType = AnnotationEditorType.FREETEXT;\n }\n render() {\n this.container.classList.add("freeTextAnnotation");\n if (this.textContent) {\n const content = this.contentElement = document.createElement("div");\n content.classList.add("annotationTextContent");\n content.setAttribute("role", "comment");\n for (const line of this.textContent) {\n const lineSpan = document.createElement("span");\n lineSpan.textContent = line;\n content.append(lineSpan);\n }\n this.container.append(content);\n }\n if (!this.data.popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n this._editOnDoubleClick();\n return this.container;\n }\n}\nclass LineAnnotationElement extends AnnotationElement {\n #line = null;\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true\n });\n }\n render() {\n this.container.classList.add("lineAnnotation");\n const {\n data,\n width,\n height\n } = this;\n const svg = this.svgFactory.create(width, height, true);\n const line = this.#line = this.svgFactory.createElement("svg:line");\n line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);\n line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);\n line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);\n line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);\n line.setAttribute("stroke-width", data.borderStyle.width || 1);\n line.setAttribute("stroke", "transparent");\n line.setAttribute("fill", "transparent");\n svg.append(line);\n this.container.append(svg);\n if (!data.popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n return this.container;\n }\n getElementsToTriggerPopup() {\n return this.#line;\n }\n addHighlightArea() {\n this.container.classList.add("highlightArea");\n }\n}\nclass SquareAnnotationElement extends AnnotationElement {\n #square = null;\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true\n });\n }\n render() {\n this.container.classList.add("squareAnnotation");\n const {\n data,\n width,\n height\n } = this;\n const svg = this.svgFactory.create(width, height, true);\n const borderWidth = data.borderStyle.width;\n const square = this.#square = this.svgFactory.createElement("svg:rect");\n square.setAttribute("x", borderWidth / 2);\n square.setAttribute("y", borderWidth / 2);\n square.setAttribute("width", width - borderWidth);\n square.setAttribute("height", height - borderWidth);\n square.setAttribute("stroke-width", borderWidth || 1);\n square.setAttribute("stroke", "transparent");\n square.setAttribute("fill", "transparent");\n svg.append(square);\n this.container.append(svg);\n if (!data.popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n return this.container;\n }\n getElementsToTriggerPopup() {\n return this.#square;\n }\n addHighlightArea() {\n this.container.classList.add("highlightArea");\n }\n}\nclass CircleAnnotationElement extends AnnotationElement {\n #circle = null;\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true\n });\n }\n render() {\n this.container.classList.add("circleAnnotation");\n const {\n data,\n width,\n height\n } = this;\n const svg = this.svgFactory.create(width, height, true);\n const borderWidth = data.borderStyle.width;\n const circle = this.#circle = this.svgFactory.createElement("svg:ellipse");\n circle.setAttribute("cx", width / 2);\n circle.setAttribute("cy", height / 2);\n circle.setAttribute("rx", width / 2 - borderWidth / 2);\n circle.setAttribute("ry", height / 2 - borderWidth / 2);\n circle.setAttribute("stroke-width", borderWidth || 1);\n circle.setAttribute("stroke", "transparent");\n circle.setAttribute("fill", "transparent");\n svg.append(circle);\n this.container.append(svg);\n if (!data.popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n return this.container;\n }\n getElementsToTriggerPopup() {\n return this.#circle;\n }\n addHighlightArea() {\n this.container.classList.add("highlightArea");\n }\n}\nclass PolylineAnnotationElement extends AnnotationElement {\n #polyline = null;\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true\n });\n this.containerClassName = "polylineAnnotation";\n this.svgElementName = "svg:polyline";\n }\n render() {\n this.container.classList.add(this.containerClassName);\n const {\n data: {\n rect,\n vertices,\n borderStyle,\n popupRef\n },\n width,\n height\n } = this;\n if (!vertices) {\n return this.container;\n }\n const svg = this.svgFactory.create(width, height, true);\n let points = [];\n for (let i = 0, ii = vertices.length; i < ii; i += 2) {\n const x = vertices[i] - rect[0];\n const y = rect[3] - vertices[i + 1];\n points.push(`${x},${y}`);\n }\n points = points.join(" ");\n const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName);\n polyline.setAttribute("points", points);\n polyline.setAttribute("stroke-width", borderStyle.width || 1);\n polyline.setAttribute("stroke", "transparent");\n polyline.setAttribute("fill", "transparent");\n svg.append(polyline);\n this.container.append(svg);\n if (!popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n return this.container;\n }\n getElementsToTriggerPopup() {\n return this.#polyline;\n }\n addHighlightArea() {\n this.container.classList.add("highlightArea");\n }\n}\nclass PolygonAnnotationElement extends PolylineAnnotationElement {\n constructor(parameters) {\n super(parameters);\n this.containerClassName = "polygonAnnotation";\n this.svgElementName = "svg:polygon";\n }\n}\nclass CaretAnnotationElement extends AnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true\n });\n }\n render() {\n this.container.classList.add("caretAnnotation");\n if (!this.data.popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n return this.container;\n }\n}\nclass InkAnnotationElement extends AnnotationElement {\n #polylinesGroupElement = null;\n #polylines = [];\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true\n });\n this.containerClassName = "inkAnnotation";\n this.svgElementName = "svg:polyline";\n this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK;\n }\n #getTransform(rotation, rect) {\n switch (rotation) {\n case 90:\n return {\n transform: `rotate(90) translate(${-rect[0]},${rect[1]}) scale(1,-1)`,\n width: rect[3] - rect[1],\n height: rect[2] - rect[0]\n };\n case 180:\n return {\n transform: `rotate(180) translate(${-rect[2]},${rect[1]}) scale(1,-1)`,\n width: rect[2] - rect[0],\n height: rect[3] - rect[1]\n };\n case 270:\n return {\n transform: `rotate(270) translate(${-rect[2]},${rect[3]}) scale(1,-1)`,\n width: rect[3] - rect[1],\n height: rect[2] - rect[0]\n };\n default:\n return {\n transform: `translate(${-rect[0]},${rect[3]}) scale(1,-1)`,\n width: rect[2] - rect[0],\n height: rect[3] - rect[1]\n };\n }\n }\n render() {\n this.container.classList.add(this.containerClassName);\n const {\n data: {\n rect,\n rotation,\n inkLists,\n borderStyle,\n popupRef\n }\n } = this;\n const {\n transform,\n width,\n height\n } = this.#getTransform(rotation, rect);\n const svg = this.svgFactory.create(width, height, true);\n const g = this.#polylinesGroupElement = this.svgFactory.createElement("svg:g");\n svg.append(g);\n g.setAttribute("stroke-width", borderStyle.width || 1);\n g.setAttribute("stroke-linecap", "round");\n g.setAttribute("stroke-linejoin", "round");\n g.setAttribute("stroke-miterlimit", 10);\n g.setAttribute("stroke", "transparent");\n g.setAttribute("fill", "transparent");\n g.setAttribute("transform", transform);\n for (let i = 0, ii = inkLists.length; i < ii; i++) {\n const polyline = this.svgFactory.createElement(this.svgElementName);\n this.#polylines.push(polyline);\n polyline.setAttribute("points", inkLists[i].join(","));\n g.append(polyline);\n }\n if (!popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n this.container.append(svg);\n this._editOnDoubleClick();\n return this.container;\n }\n updateEdited(params) {\n super.updateEdited(params);\n const {\n thickness,\n points,\n rect\n } = params;\n const g = this.#polylinesGroupElement;\n if (thickness >= 0) {\n g.setAttribute("stroke-width", thickness || 1);\n }\n if (points) {\n for (let i = 0, ii = this.#polylines.length; i < ii; i++) {\n this.#polylines[i].setAttribute("points", points[i].join(","));\n }\n }\n if (rect) {\n const {\n transform,\n width,\n height\n } = this.#getTransform(this.data.rotation, rect);\n const root = g.parentElement;\n root.setAttribute("viewBox", `0 0 ${width} ${height}`);\n g.setAttribute("transform", transform);\n }\n }\n getElementsToTriggerPopup() {\n return this.#polylines;\n }\n addHighlightArea() {\n this.container.classList.add("highlightArea");\n }\n}\nclass HighlightAnnotationElement extends AnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true,\n createQuadrilaterals: true\n });\n this.annotationEditorType = AnnotationEditorType.HIGHLIGHT;\n }\n render() {\n const {\n data: {\n overlaidText,\n popupRef\n }\n } = this;\n if (!popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n this.container.classList.add("highlightAnnotation");\n this._editOnDoubleClick();\n if (overlaidText) {\n const mark = document.createElement("mark");\n mark.classList.add("overlaidText");\n mark.textContent = overlaidText;\n this.container.append(mark);\n }\n return this.container;\n }\n}\nclass UnderlineAnnotationElement extends AnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true,\n createQuadrilaterals: true\n });\n }\n render() {\n const {\n data: {\n overlaidText,\n popupRef\n }\n } = this;\n if (!popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n this.container.classList.add("underlineAnnotation");\n if (overlaidText) {\n const underline = document.createElement("u");\n underline.classList.add("overlaidText");\n underline.textContent = overlaidText;\n this.container.append(underline);\n }\n return this.container;\n }\n}\nclass SquigglyAnnotationElement extends AnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true,\n createQuadrilaterals: true\n });\n }\n render() {\n const {\n data: {\n overlaidText,\n popupRef\n }\n } = this;\n if (!popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n this.container.classList.add("squigglyAnnotation");\n if (overlaidText) {\n const underline = document.createElement("u");\n underline.classList.add("overlaidText");\n underline.textContent = overlaidText;\n this.container.append(underline);\n }\n return this.container;\n }\n}\nclass StrikeOutAnnotationElement extends AnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true,\n createQuadrilaterals: true\n });\n }\n render() {\n const {\n data: {\n overlaidText,\n popupRef\n }\n } = this;\n if (!popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n this.container.classList.add("strikeoutAnnotation");\n if (overlaidText) {\n const strikeout = document.createElement("s");\n strikeout.classList.add("overlaidText");\n strikeout.textContent = overlaidText;\n this.container.append(strikeout);\n }\n return this.container;\n }\n}\nclass StampAnnotationElement extends AnnotationElement {\n constructor(parameters) {\n super(parameters, {\n isRenderable: true,\n ignoreBorder: true\n });\n this.annotationEditorType = AnnotationEditorType.STAMP;\n }\n render() {\n this.container.classList.add("stampAnnotation");\n this.container.setAttribute("role", "img");\n if (!this.data.popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n }\n this._editOnDoubleClick();\n return this.container;\n }\n}\nclass FileAttachmentAnnotationElement extends AnnotationElement {\n #trigger = null;\n constructor(parameters) {\n super(parameters, {\n isRenderable: true\n });\n const {\n file\n } = this.data;\n this.filename = file.filename;\n this.content = file.content;\n this.linkService.eventBus?.dispatch("fileattachmentannotation", {\n source: this,\n ...file\n });\n }\n render() {\n this.container.classList.add("fileAttachmentAnnotation");\n const {\n container,\n data\n } = this;\n let trigger;\n if (data.hasAppearance || data.fillAlpha === 0) {\n trigger = document.createElement("div");\n } else {\n trigger = document.createElement("img");\n trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`;\n if (data.fillAlpha && data.fillAlpha < 1) {\n trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`;\n }\n }\n trigger.addEventListener("dblclick", this.#download.bind(this));\n this.#trigger = trigger;\n const {\n isMac\n } = FeatureTest.platform;\n container.addEventListener("keydown", evt => {\n if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) {\n this.#download();\n }\n });\n if (!data.popupRef && this.hasPopupData) {\n this.hasOwnCommentButton = true;\n this._createPopup();\n } else {\n trigger.classList.add("popupTriggerArea");\n }\n container.append(trigger);\n return container;\n }\n getElementsToTriggerPopup() {\n return this.#trigger;\n }\n addHighlightArea() {\n this.container.classList.add("highlightArea");\n }\n #download() {\n this.downloadManager?.openOrDownloadData(this.content, this.filename);\n }\n}\nclass AnnotationLayer {\n #accessibilityManager = null;\n #annotationCanvasMap = null;\n #annotationStorage = null;\n #editableAnnotations = new Map();\n #structTreeLayer = null;\n #linkService = null;\n #elements = [];\n #hasAriaAttributesFromStructTree = false;\n constructor({\n div,\n accessibilityManager,\n annotationCanvasMap,\n annotationEditorUIManager,\n page,\n viewport,\n structTreeLayer,\n commentManager,\n linkService,\n annotationStorage\n }) {\n this.div = div;\n this.#accessibilityManager = accessibilityManager;\n this.#annotationCanvasMap = annotationCanvasMap;\n this.#structTreeLayer = structTreeLayer || null;\n this.#linkService = linkService || null;\n this.#annotationStorage = annotationStorage || new AnnotationStorage();\n this.page = page;\n this.viewport = viewport;\n this.zIndex = 0;\n this._annotationEditorUIManager = annotationEditorUIManager;\n this._commentManager = commentManager || null;\n }\n hasEditableAnnotations() {\n return this.#editableAnnotations.size > 0;\n }\n async render(params) {\n const {\n annotations\n } = params;\n const layer = this.div;\n setLayerDimensions(layer, this.viewport);\n const popupToElements = new Map();\n const popupAnnotations = [];\n const elementParams = {\n data: null,\n layer,\n linkService: this.#linkService,\n downloadManager: params.downloadManager,\n imageResourcesPath: params.imageResourcesPath || "",\n renderForms: params.renderForms !== false,\n svgFactory: new DOMSVGFactory(),\n annotationStorage: this.#annotationStorage,\n enableComment: params.enableComment === true,\n enableScripting: params.enableScripting === true,\n hasJSActions: params.hasJSActions,\n fieldObjects: params.fieldObjects,\n parent: this,\n elements: null\n };\n for (const data of annotations) {\n if (data.noHTML) {\n continue;\n }\n const isPopupAnnotation = data.annotationType === AnnotationType.POPUP;\n if (!isPopupAnnotation) {\n if (data.rect[2] === data.rect[0] || data.rect[3] === data.rect[1]) {\n continue;\n }\n } else {\n const elements = popupToElements.get(data.id);\n if (!elements) {\n continue;\n }\n if (!this._commentManager) {\n popupAnnotations.push(data);\n continue;\n }\n elementParams.elements = elements;\n }\n elementParams.data = data;\n const element = AnnotationElementFactory.create(elementParams);\n if (!element.isRenderable) {\n continue;\n }\n if (!isPopupAnnotation) {\n this.#elements.push(element);\n if (data.popupRef) {\n popupToElements.getOrInsertComputed(data.popupRef, makeArr).push(element);\n }\n }\n const rendered = element.render();\n if (data.hidden) {\n rendered.style.visibility = "hidden";\n }\n if (element._isEditable) {\n this.#editableAnnotations.set(element.data.id, element);\n this._annotationEditorUIManager?.renderAnnotationElement(element);\n }\n }\n await this.#addElementsToDOM();\n for (const data of popupAnnotations) {\n const elements = elementParams.elements = popupToElements.get(data.id);\n elementParams.data = data;\n const element = AnnotationElementFactory.create(elementParams);\n if (!element.isRenderable) {\n continue;\n }\n const rendered = element.render();\n element.contentElement.id = `${AnnotationPrefix}${data.id}`;\n if (data.hidden) {\n rendered.style.visibility = "hidden";\n }\n elements.at(-1).container.after(rendered);\n }\n this.#setAnnotationCanvasMap();\n }\n async #addElementsToDOM() {\n if (this.#elements.length === 0) {\n return;\n }\n this.div.replaceChildren();\n const promises = [];\n if (!this.#hasAriaAttributesFromStructTree) {\n this.#hasAriaAttributesFromStructTree = true;\n for (const {\n contentElement,\n data: {\n id\n }\n } of this.#elements) {\n const annotationId = contentElement.id = `${AnnotationPrefix}${id}`;\n promises.push(this.#structTreeLayer?.getAriaAttributes(annotationId).then(ariaAttributes => {\n if (ariaAttributes) {\n for (const [key, value] of ariaAttributes) {\n contentElement.setAttribute(key, value);\n }\n }\n }));\n }\n }\n this.#elements.sort(({\n data: {\n rect: [a0, a1, a2, a3]\n }\n }, {\n data: {\n rect: [b0, b1, b2, b3]\n }\n }) => {\n if (a0 === a2 && a1 === a3) {\n return +1;\n }\n if (b0 === b2 && b1 === b3) {\n return -1;\n }\n const top1 = a3;\n const bot1 = a1;\n const mid1 = (a1 + a3) / 2;\n const top2 = b3;\n const bot2 = b1;\n const mid2 = (b1 + b3) / 2;\n if (mid1 >= top2 && mid2 <= bot1) {\n return -1;\n }\n if (mid2 >= top1 && mid1 <= bot2) {\n return +1;\n }\n const centerX1 = (a0 + a2) / 2;\n const centerX2 = (b0 + b2) / 2;\n return centerX1 - centerX2;\n });\n const fragment = document.createDocumentFragment();\n for (const element of this.#elements) {\n fragment.append(element.container);\n if (this._commentManager) {\n (element.extraPopupElement?.popup || element.popup)?.renderCommentButton();\n } else if (element.extraPopupElement) {\n fragment.append(element.extraPopupElement.render());\n }\n }\n this.div.append(fragment);\n await Promise.all(promises);\n if (this.#accessibilityManager) {\n for (const element of this.#elements) {\n this.#accessibilityManager.addPointerInTextLayer(element.contentElement, false);\n }\n }\n }\n async addLinkAnnotations(annotations) {\n const elementParams = {\n data: null,\n layer: this.div,\n linkService: this.#linkService,\n svgFactory: new DOMSVGFactory(),\n parent: this\n };\n for (const data of annotations) {\n data.borderStyle ||= AnnotationLayer._defaultBorderStyle;\n elementParams.data = data;\n const element = AnnotationElementFactory.create(elementParams);\n if (!element.isRenderable) {\n continue;\n }\n element.render();\n element.contentElement.id = `${AnnotationPrefix}${data.id}`;\n this.#elements.push(element);\n }\n await this.#addElementsToDOM();\n }\n update({\n viewport\n }) {\n const layer = this.div;\n this.viewport = viewport;\n setLayerDimensions(layer, {\n rotation: viewport.rotation\n });\n this.#setAnnotationCanvasMap();\n layer.hidden = false;\n }\n #setAnnotationCanvasMap() {\n if (!this.#annotationCanvasMap) {\n return;\n }\n const layer = this.div;\n for (const [id, canvas] of this.#annotationCanvasMap) {\n const element = layer.querySelector(`[data-annotation-id="${id}"]`);\n if (!element) {\n continue;\n }\n canvas.className = "annotationContent";\n const {\n firstChild\n } = element;\n if (!firstChild) {\n element.append(canvas);\n } else if (firstChild.nodeName === "CANVAS") {\n firstChild.replaceWith(canvas);\n } else if (!firstChild.classList.contains("annotationContent")) {\n firstChild.before(canvas);\n } else {\n firstChild.after(canvas);\n }\n const editableAnnotation = this.#editableAnnotations.get(id);\n if (!editableAnnotation) {\n continue;\n }\n if (editableAnnotation._hasNoCanvas) {\n this._annotationEditorUIManager?.setMissingCanvas(id, element.id, canvas);\n editableAnnotation._hasNoCanvas = false;\n } else {\n editableAnnotation.canvas = canvas;\n }\n }\n this.#annotationCanvasMap.clear();\n }\n getEditableAnnotations() {\n return Array.from(this.#editableAnnotations.values());\n }\n getEditableAnnotation(id) {\n return this.#editableAnnotations.get(id);\n }\n addFakeAnnotation(editor) {\n const {\n div\n } = this;\n const {\n id,\n rotation\n } = editor;\n const element = new EditorAnnotationElement({\n data: {\n id,\n rect: editor.getPDFRect(),\n rotation\n },\n editor,\n layer: div,\n parent: this,\n enableComment: !!this._commentManager,\n linkService: this.#linkService,\n annotationStorage: this.#annotationStorage\n });\n element.render();\n element.contentElement.id = `${AnnotationPrefix}${id}`;\n element.createOrUpdatePopup();\n this.#elements.push(element);\n return element;\n }\n removeAnnotation(id) {\n const index = this.#elements.findIndex(el => el.data.id === id);\n if (index < 0) {\n return;\n }\n const [element] = this.#elements.splice(index, 1);\n this.#accessibilityManager?.removePointerInTextLayer(element.contentElement);\n }\n updateFakeAnnotations(editors) {\n if (editors.length === 0) {\n return;\n }\n for (const editor of editors) {\n editor.updateFakeAnnotationElement(this);\n }\n this.#addElementsToDOM();\n }\n togglePointerEvents(enabled = false) {\n this.div.classList.toggle("disabled", !enabled);\n }\n static get _defaultBorderStyle() {\n return shadow(this, "_defaultBorderStyle", Object.freeze({\n width: 1,\n rawWidth: 1,\n style: AnnotationBorderStyleType.SOLID,\n dashArray: [3],\n horizontalCornerRadius: 0,\n verticalCornerRadius: 0\n }));\n }\n}\n\n;// ./src/display/editor/freetext.js\n\n\n\n\n\n\n\n\n\nconst EOL_PATTERN = /\\r\\n?|\\n/g;\nclass FreeTextEditor extends AnnotationEditor {\n #content = "";\n #editorDivId = `${this.id}-editor`;\n #editModeAC = null;\n #fontSize;\n _colorPicker = null;\n static _freeTextDefaultContent = "";\n static _internalPadding = 0;\n static _defaultColor = null;\n static _defaultFontSize = 10;\n static get _keyboardManager() {\n const proto = FreeTextEditor.prototype;\n const arrowChecker = self => self.isEmpty();\n const small = AnnotationEditorUIManager.TRANSLATE_SMALL;\n const big = AnnotationEditorUIManager.TRANSLATE_BIG;\n return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, {\n bubbles: true\n }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, {\n args: [-small, 0],\n checker: arrowChecker\n }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, {\n args: [-big, 0],\n checker: arrowChecker\n }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, {\n args: [small, 0],\n checker: arrowChecker\n }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, {\n args: [big, 0],\n checker: arrowChecker\n }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, {\n args: [0, -small],\n checker: arrowChecker\n }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, {\n args: [0, -big],\n checker: arrowChecker\n }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, {\n args: [0, small],\n checker: arrowChecker\n }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, {\n args: [0, big],\n checker: arrowChecker\n }]]));\n }\n static _type = "freetext";\n static _editorType = AnnotationEditorType.FREETEXT;\n constructor(params) {\n super({\n ...params,\n name: "freeTextEditor"\n });\n this.color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor;\n this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;\n if (!this.annotationElementId) {\n this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert");\n }\n this.canAddComment = false;\n }\n static initialize(l10n, uiManager) {\n AnnotationEditor.initialize(l10n, uiManager);\n const style = getComputedStyle(document.documentElement);\n this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));\n }\n static updateDefaultParams(type, value) {\n switch (type) {\n case AnnotationEditorParamsType.FREETEXT_SIZE:\n FreeTextEditor._defaultFontSize = value;\n break;\n case AnnotationEditorParamsType.FREETEXT_COLOR:\n FreeTextEditor._defaultColor = value;\n break;\n }\n }\n updateParams(type, value) {\n switch (type) {\n case AnnotationEditorParamsType.FREETEXT_SIZE:\n this.#updateFontSize(value);\n break;\n case AnnotationEditorParamsType.FREETEXT_COLOR:\n this.#updateColor(value);\n break;\n }\n }\n static get defaultPropertiesToUpdate() {\n return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]];\n }\n get propertiesToUpdate() {\n return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.color]];\n }\n get toolbarButtons() {\n this._colorPicker ||= new BasicColorPicker(this);\n return [["colorPicker", this._colorPicker]];\n }\n get colorType() {\n return AnnotationEditorParamsType.FREETEXT_COLOR;\n }\n #updateFontSize(fontSize) {\n const setFontsize = size => {\n this.editorDiv.style.fontSize = `calc(${size}px * var(--total-scale-factor))`;\n this.translate(0, -(size - this.#fontSize) * this.parentScale);\n this.#fontSize = size;\n this.#setEditorDimensions();\n };\n const savedFontsize = this.#fontSize;\n this.addCommands({\n cmd: setFontsize.bind(this, fontSize),\n undo: setFontsize.bind(this, savedFontsize),\n post: this._uiManager.updateUI.bind(this._uiManager, this),\n mustExec: true,\n type: AnnotationEditorParamsType.FREETEXT_SIZE,\n overwriteIfSameType: true,\n keepUndo: true\n });\n }\n onUpdatedColor() {\n this.editorDiv.style.color = this.color;\n this._colorPicker?.update(this.color);\n super.onUpdatedColor();\n }\n #updateColor(color) {\n const setColor = col => {\n this.color = col;\n this.onUpdatedColor();\n };\n const savedColor = this.color;\n this.addCommands({\n cmd: setColor.bind(this, color),\n undo: setColor.bind(this, savedColor),\n post: this._uiManager.updateUI.bind(this._uiManager, this),\n mustExec: true,\n type: AnnotationEditorParamsType.FREETEXT_COLOR,\n overwriteIfSameType: true,\n keepUndo: true\n });\n }\n _translateEmpty(x, y) {\n this._uiManager.translateSelectedEditors(x, y, true);\n }\n getInitialTranslation() {\n const scale = this.parentScale;\n return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];\n }\n rebuild() {\n if (!this.parent) {\n return;\n }\n super.rebuild();\n if (this.div === null) {\n return;\n }\n if (!this.isAttachedToDOM) {\n this.parent.add(this);\n }\n }\n enableEditMode() {\n if (!super.enableEditMode()) {\n return false;\n }\n this.overlayDiv.classList.remove("enabled");\n this.editorDiv.contentEditable = true;\n this._isDraggable = false;\n this.div.removeAttribute("aria-activedescendant");\n this.#editModeAC = new AbortController();\n const signal = this._uiManager.combinedSignal(this.#editModeAC);\n this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), {\n signal\n });\n this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), {\n signal\n });\n this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), {\n signal\n });\n this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), {\n signal\n });\n this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), {\n signal\n });\n return true;\n }\n disableEditMode() {\n if (!super.disableEditMode()) {\n return false;\n }\n this.overlayDiv.classList.add("enabled");\n this.editorDiv.contentEditable = false;\n this.div.setAttribute("aria-activedescendant", this.#editorDivId);\n this._isDraggable = true;\n this.#editModeAC?.abort();\n this.#editModeAC = null;\n this.div.focus({\n preventScroll: true\n });\n this.isEditing = false;\n this.parent.div.classList.add("freetextEditing");\n return true;\n }\n focusin(event) {\n if (!this._focusEventsAllowed) {\n return;\n }\n super.focusin(event);\n if (event.target !== this.editorDiv) {\n this.editorDiv.focus();\n }\n }\n onceAdded(focus) {\n if (this.width) {\n return;\n }\n this.enableEditMode();\n if (focus) {\n this.editorDiv.focus();\n }\n if (this._initialOptions?.isCentered) {\n this.center();\n }\n this._initialOptions = null;\n }\n isEmpty() {\n return !this.editorDiv || this.editorDiv.innerText.trim() === "";\n }\n remove() {\n this.isEditing = false;\n if (this.parent) {\n this.parent.setEditingState(true);\n this.parent.div.classList.add("freetextEditing");\n }\n super.remove();\n }\n #extractText() {\n const buffer = [];\n this.editorDiv.normalize();\n let prevChild = null;\n for (const child of this.editorDiv.childNodes) {\n if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") {\n continue;\n }\n buffer.push(FreeTextEditor.#getNodeContent(child));\n prevChild = child;\n }\n return buffer.join("\\n");\n }\n #setEditorDimensions() {\n const [parentWidth, parentHeight] = this.parentDimensions;\n let rect;\n if (this.isAttachedToDOM) {\n rect = this.div.getBoundingClientRect();\n } else {\n const {\n currentLayer,\n div\n } = this;\n const savedDisplay = div.style.display;\n const savedVisibility = div.classList.contains("hidden");\n div.classList.remove("hidden");\n div.style.display = "hidden";\n currentLayer.div.append(this.div);\n rect = div.getBoundingClientRect();\n div.remove();\n div.style.display = savedDisplay;\n div.classList.toggle("hidden", savedVisibility);\n }\n if (this.rotation % 180 === this.parentRotation % 180) {\n this.width = rect.width / parentWidth;\n this.height = rect.height / parentHeight;\n } else {\n this.width = rect.height / parentWidth;\n this.height = rect.width / parentHeight;\n }\n this.fixAndSetPosition();\n }\n commit() {\n if (!this.isInEditMode()) {\n return;\n }\n super.commit();\n this.disableEditMode();\n const savedText = this.#content;\n const newText = this.#content = this.#extractText().trimEnd();\n if (savedText === newText) {\n return;\n }\n const setText = text => {\n this.#content = text;\n if (!text) {\n this.remove();\n return;\n }\n this.#setContent();\n this._uiManager.rebuild(this);\n this.#setEditorDimensions();\n };\n this.addCommands({\n cmd: () => {\n setText(newText);\n },\n undo: () => {\n setText(savedText);\n },\n mustExec: false\n });\n this.#setEditorDimensions();\n }\n shouldGetKeyboardEvents() {\n return this.isInEditMode();\n }\n enterInEditMode() {\n this.enableEditMode();\n this.editorDiv.focus();\n }\n keydown(event) {\n if (event.target === this.div && event.key === "Enter") {\n this.enterInEditMode();\n event.preventDefault();\n }\n }\n editorDivKeydown(event) {\n FreeTextEditor._keyboardManager.exec(this, event);\n }\n editorDivFocus(event) {\n this.isEditing = true;\n }\n editorDivBlur(event) {\n this.isEditing = false;\n }\n editorDivInput(event) {\n this.parent.div.classList.toggle("freetextEditing", this.isEmpty());\n }\n disableEditing() {\n this.editorDiv.setAttribute("role", "comment");\n this.editorDiv.removeAttribute("aria-multiline");\n }\n enableEditing() {\n this.editorDiv.setAttribute("role", "textbox");\n this.editorDiv.setAttribute("aria-multiline", true);\n }\n get canChangeContent() {\n return true;\n }\n render() {\n if (this.div) {\n return this.div;\n }\n let baseX, baseY;\n if (this._isCopy || this.annotationElementId) {\n baseX = this.x;\n baseY = this.y;\n }\n super.render();\n this.editorDiv = document.createElement("div");\n this.editorDiv.className = "internal";\n this.editorDiv.setAttribute("id", this.#editorDivId);\n this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text2");\n this.editorDiv.setAttribute("data-l10n-attrs", "default-content");\n this.enableEditing();\n this.editorDiv.contentEditable = true;\n const {\n style\n } = this.editorDiv;\n style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`;\n style.color = this.color;\n this.div.append(this.editorDiv);\n this.overlayDiv = document.createElement("div");\n this.overlayDiv.classList.add("overlay", "enabled");\n this.div.append(this.overlayDiv);\n if (this._isCopy || this.annotationElementId) {\n const [parentWidth, parentHeight] = this.parentDimensions;\n if (this.annotationElementId) {\n const {\n position\n } = this._initialData;\n let [tx, ty] = this.getInitialTranslation();\n [tx, ty] = this.pageTranslationToScreen(tx, ty);\n const [pageWidth, pageHeight] = this.pageDimensions;\n const [pageX, pageY] = this.pageTranslation;\n let posX, posY;\n switch (this.rotation) {\n case 0:\n posX = baseX + (position[0] - pageX) / pageWidth;\n posY = baseY + this.height - (position[1] - pageY) / pageHeight;\n break;\n case 90:\n posX = baseX + (position[0] - pageX) / pageWidth;\n posY = baseY - (position[1] - pageY) / pageHeight;\n [tx, ty] = [ty, -tx];\n break;\n case 180:\n posX = baseX - this.width + (position[0] - pageX) / pageWidth;\n posY = baseY - (position[1] - pageY) / pageHeight;\n [tx, ty] = [-tx, -ty];\n break;\n case 270:\n posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth;\n posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight;\n [tx, ty] = [-ty, tx];\n break;\n }\n this.setAt(posX * parentWidth, posY * parentHeight, tx, ty);\n } else {\n this._moveAfterPaste(baseX, baseY);\n }\n this.#setContent();\n this._isDraggable = true;\n this.editorDiv.contentEditable = false;\n } else {\n this._isDraggable = false;\n this.editorDiv.contentEditable = true;\n }\n return this.div;\n }\n static #getNodeContent(node) {\n return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, "");\n }\n editorDivPaste(event) {\n const clipboardData = event.clipboardData || window.clipboardData;\n const {\n types\n } = clipboardData;\n if (types.length === 1 && types[0] === "text/plain") {\n return;\n }\n event.preventDefault();\n const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\\n");\n if (!paste) {\n return;\n }\n const selection = window.getSelection();\n if (!selection.rangeCount) {\n return;\n }\n this.editorDiv.normalize();\n selection.deleteFromDocument();\n const range = selection.getRangeAt(0);\n if (!paste.includes("\\n")) {\n range.insertNode(document.createTextNode(paste));\n this.editorDiv.normalize();\n selection.collapseToStart();\n return;\n }\n const {\n startContainer,\n startOffset\n } = range;\n const bufferBefore = [];\n const bufferAfter = [];\n if (startContainer.nodeType === Node.TEXT_NODE) {\n const parent = startContainer.parentElement;\n bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, ""));\n if (parent !== this.editorDiv) {\n let buffer = bufferBefore;\n for (const child of this.editorDiv.childNodes) {\n if (child === parent) {\n buffer = bufferAfter;\n continue;\n }\n buffer.push(FreeTextEditor.#getNodeContent(child));\n }\n }\n bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, ""));\n } else if (startContainer === this.editorDiv) {\n let buffer = bufferBefore;\n let i = 0;\n for (const child of this.editorDiv.childNodes) {\n if (i++ === startOffset) {\n buffer = bufferAfter;\n }\n buffer.push(FreeTextEditor.#getNodeContent(child));\n }\n }\n this.#content = `${bufferBefore.join("\\n")}${paste}${bufferAfter.join("\\n")}`;\n this.#setContent();\n const newRange = new Range();\n let beforeLength = Math.sumPrecise(bufferBefore.map(line => line.length));\n for (const {\n firstChild\n } of this.editorDiv.childNodes) {\n if (firstChild.nodeType === Node.TEXT_NODE) {\n const length = firstChild.nodeValue.length;\n if (beforeLength <= length) {\n newRange.setStart(firstChild, beforeLength);\n newRange.setEnd(firstChild, beforeLength);\n break;\n }\n beforeLength -= length;\n }\n }\n selection.removeAllRanges();\n selection.addRange(newRange);\n }\n #setContent() {\n this.editorDiv.replaceChildren();\n if (!this.#content) {\n return;\n }\n for (const line of this.#content.split("\\n")) {\n const div = document.createElement("div");\n div.append(line ? document.createTextNode(line) : document.createElement("br"));\n this.editorDiv.append(div);\n }\n }\n #serializeContent() {\n return this.#content.replaceAll("\\xa0", " ");\n }\n static #deserializeContent(content) {\n return content.replaceAll(" ", "\\xa0");\n }\n get contentDiv() {\n return this.editorDiv;\n }\n getPDFRect() {\n const padding = FreeTextEditor._internalPadding * this.parentScale;\n return this.getRect(padding, padding);\n }\n static async deserialize(data, parent, uiManager) {\n let initialData = null;\n if (data instanceof FreeTextAnnotationElement) {\n const {\n data: {\n defaultAppearanceData: {\n fontSize,\n fontColor\n },\n rect,\n rotation,\n id,\n popupRef,\n richText,\n contentsObj,\n creationDate,\n modificationDate\n },\n textContent,\n textPosition,\n parent: {\n page: {\n pageNumber\n }\n }\n } = data;\n if (!textContent || textContent.length === 0) {\n return null;\n }\n initialData = data = {\n annotationType: AnnotationEditorType.FREETEXT,\n color: Array.from(fontColor),\n fontSize,\n value: textContent.join("\\n"),\n position: textPosition,\n pageIndex: pageNumber - 1,\n rect: rect.slice(0),\n rotation,\n annotationElementId: id,\n id,\n deleted: false,\n popupRef,\n comment: contentsObj?.str || null,\n richText,\n creationDate,\n modificationDate\n };\n }\n const editor = await super.deserialize(data, parent, uiManager);\n editor.#fontSize = data.fontSize;\n editor.color = Util.makeHexColor(...data.color);\n editor.#content = FreeTextEditor.#deserializeContent(data.value);\n editor._initialData = initialData;\n if (data.comment) {\n editor.setCommentData(data);\n }\n return editor;\n }\n serialize(isForCopying = false) {\n if (this.isEmpty()) {\n return null;\n }\n if (this.deleted) {\n return this.serializeDeleted();\n }\n const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.color);\n const serialized = Object.assign(super.serialize(isForCopying), {\n color,\n fontSize: this.#fontSize,\n value: this.#serializeContent()\n });\n this.addComment(serialized);\n if (isForCopying) {\n serialized.isCopy = true;\n return serialized;\n }\n if (this.annotationElementId && !this.#hasElementChanged(serialized)) {\n return null;\n }\n serialized.id = this.annotationElementId;\n return serialized;\n }\n #hasElementChanged(serialized) {\n const {\n value,\n fontSize,\n color,\n pageIndex\n } = this._initialData;\n return this.hasEditedComment || this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex;\n }\n renderAnnotationElement(annotation) {\n const content = super.renderAnnotationElement(annotation);\n if (!content) {\n return null;\n }\n const {\n style\n } = content;\n style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`;\n style.color = this.color;\n content.replaceChildren();\n for (const line of this.#content.split("\\n")) {\n const div = document.createElement("div");\n div.append(line ? document.createTextNode(line) : document.createElement("br"));\n content.append(div);\n }\n annotation.updateEdited({\n rect: this.getPDFRect(),\n popup: this._uiManager.hasCommentManager() || this.hasEditedComment ? this.comment : {\n text: this.#content\n }\n });\n return content;\n }\n resetAnnotationElement(annotation) {\n super.resetAnnotationElement(annotation);\n annotation.resetEdited();\n }\n}\n\n;// ./src/display/editor/drawers/outline.js\n\n\n\n\n\nclass Outline {\n static PRECISION = 1e-4;\n toSVGPath() {\n unreachable("Abstract method `toSVGPath` must be implemented.");\n }\n get box() {\n unreachable("Abstract getter `box` must be implemented.");\n }\n serialize(_bbox, _rotation) {\n unreachable("Abstract method `serialize` must be implemented.");\n }\n static _rescale(src, tx, ty, sx, sy, dest) {\n dest ||= new Float32Array(src.length);\n for (let i = 0, ii = src.length; i < ii; i += 2) {\n dest[i] = tx + src[i] * sx;\n dest[i + 1] = ty + src[i + 1] * sy;\n }\n return dest;\n }\n static _rescaleAndSwap(src, tx, ty, sx, sy, dest) {\n dest ||= new Float32Array(src.length);\n for (let i = 0, ii = src.length; i < ii; i += 2) {\n dest[i] = tx + src[i + 1] * sx;\n dest[i + 1] = ty + src[i] * sy;\n }\n return dest;\n }\n static _translate(src, tx, ty, dest) {\n dest ||= new Float32Array(src.length);\n for (let i = 0, ii = src.length; i < ii; i += 2) {\n dest[i] = tx + src[i];\n dest[i + 1] = ty + src[i + 1];\n }\n return dest;\n }\n static svgRound(x) {\n return Math.round(x * 10000);\n }\n static _normalizePoint(x, y, parentWidth, parentHeight, rotation) {\n switch (rotation) {\n case 90:\n return [1 - y / parentWidth, x / parentHeight];\n case 180:\n return [1 - x / parentWidth, 1 - y / parentHeight];\n case 270:\n return [y / parentWidth, 1 - x / parentHeight];\n default:\n return [x / parentWidth, y / parentHeight];\n }\n }\n static _normalizePagePoint(x, y, rotation) {\n switch (rotation) {\n case 90:\n return [1 - y, x];\n case 180:\n return [1 - x, 1 - y];\n case 270:\n return [y, 1 - x];\n default:\n return [x, y];\n }\n }\n static createBezierPoints(x1, y1, x2, y2, x3, y3) {\n return [(x1 + 5 * x2) / 6, (y1 + 5 * y2) / 6, (5 * x2 + x3) / 6, (5 * y2 + y3) / 6, (x2 + x3) / 2, (y2 + y3) / 2];\n }\n}\n\n;// ./src/display/editor/drawers/freedraw.js\n\n\n\n\n\n\n\nclass FreeDrawOutliner {\n #box;\n #bottom = [];\n #innerMargin;\n #isLTR;\n #top = [];\n #last = new Float32Array(18);\n #lastX;\n #lastY;\n #min;\n #min_dist;\n #scaleFactor;\n #thickness;\n #points = [];\n static #MIN_DIST = 8;\n static #MIN_DIFF = 2;\n static #MIN = FreeDrawOutliner.#MIN_DIST + FreeDrawOutliner.#MIN_DIFF;\n constructor({\n x,\n y\n }, box, scaleFactor, thickness, isLTR, innerMargin = 0) {\n this.#box = box;\n this.#thickness = thickness * scaleFactor;\n this.#isLTR = isLTR;\n this.#last.set([NaN, NaN, NaN, NaN, x, y], 6);\n this.#innerMargin = innerMargin;\n this.#min_dist = FreeDrawOutliner.#MIN_DIST * scaleFactor;\n this.#min = FreeDrawOutliner.#MIN * scaleFactor;\n this.#scaleFactor = scaleFactor;\n this.#points.push(x, y);\n }\n isEmpty() {\n return isNaN(this.#last[8]);\n }\n #getLastCoords() {\n const lastTop = this.#last.subarray(4, 6);\n const lastBottom = this.#last.subarray(16, 18);\n const [x, y, width, height] = this.#box;\n return [(this.#lastX + (lastTop[0] - lastBottom[0]) / 2 - x) / width, (this.#lastY + (lastTop[1] - lastBottom[1]) / 2 - y) / height, (this.#lastX + (lastBottom[0] - lastTop[0]) / 2 - x) / width, (this.#lastY + (lastBottom[1] - lastTop[1]) / 2 - y) / height];\n }\n add({\n x,\n y\n }) {\n this.#lastX = x;\n this.#lastY = y;\n const [layerX, layerY, layerWidth, layerHeight] = this.#box;\n let [x1, y1, x2, y2] = this.#last.subarray(8, 12);\n const diffX = x - x2;\n const diffY = y - y2;\n const d = Math.hypot(diffX, diffY);\n if (d < this.#min) {\n return false;\n }\n const diffD = d - this.#min_dist;\n const K = diffD / d;\n const shiftX = K * diffX;\n const shiftY = K * diffY;\n let x0 = x1;\n let y0 = y1;\n x1 = x2;\n y1 = y2;\n x2 += shiftX;\n y2 += shiftY;\n this.#points?.push(x, y);\n const nX = -shiftY / diffD;\n const nY = shiftX / diffD;\n const thX = nX * this.#thickness;\n const thY = nY * this.#thickness;\n this.#last.set(this.#last.subarray(2, 8), 0);\n this.#last.set([x2 + thX, y2 + thY], 4);\n this.#last.set(this.#last.subarray(14, 18), 12);\n this.#last.set([x2 - thX, y2 - thY], 16);\n if (isNaN(this.#last[6])) {\n if (this.#top.length === 0) {\n this.#last.set([x1 + thX, y1 + thY], 2);\n this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight);\n this.#last.set([x1 - thX, y1 - thY], 14);\n this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight);\n }\n this.#last.set([x0, y0, x1, y1, x2, y2], 6);\n return !this.isEmpty();\n }\n this.#last.set([x0, y0, x1, y1, x2, y2], 6);\n const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX));\n if (angle < Math.PI / 2) {\n [x1, y1, x2, y2] = this.#last.subarray(2, 6);\n this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);\n [x1, y1, x0, y0] = this.#last.subarray(14, 18);\n this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight);\n return true;\n }\n [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6);\n this.#top.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);\n [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18);\n this.#bottom.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight);\n return true;\n }\n toSVGPath() {\n if (this.isEmpty()) {\n return "";\n }\n const top = this.#top;\n const bottom = this.#bottom;\n if (isNaN(this.#last[6]) && !this.isEmpty()) {\n return this.#toSVGPathTwoPoints();\n }\n const buffer = [];\n buffer.push(`M${top[4]} ${top[5]}`);\n for (let i = 6; i < top.length; i += 6) {\n if (isNaN(top[i])) {\n buffer.push(`L${top[i + 4]} ${top[i + 5]}`);\n } else {\n buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`);\n }\n }\n this.#toSVGPathEnd(buffer);\n for (let i = bottom.length - 6; i >= 6; i -= 6) {\n if (isNaN(bottom[i])) {\n buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`);\n } else {\n buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`);\n }\n }\n this.#toSVGPathStart(buffer);\n return buffer.join(" ");\n }\n #toSVGPathTwoPoints() {\n const [x, y, width, height] = this.#box;\n const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();\n return `M${(this.#last[2] - x) / width} ${(this.#last[3] - y) / height} L${(this.#last[4] - x) / width} ${(this.#last[5] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(this.#last[16] - x) / width} ${(this.#last[17] - y) / height} L${(this.#last[14] - x) / width} ${(this.#last[15] - y) / height} Z`;\n }\n #toSVGPathStart(buffer) {\n const bottom = this.#bottom;\n buffer.push(`L${bottom[4]} ${bottom[5]} Z`);\n }\n #toSVGPathEnd(buffer) {\n const [x, y, width, height] = this.#box;\n const lastTop = this.#last.subarray(4, 6);\n const lastBottom = this.#last.subarray(16, 18);\n const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();\n buffer.push(`L${(lastTop[0] - x) / width} ${(lastTop[1] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(lastBottom[0] - x) / width} ${(lastBottom[1] - y) / height}`);\n }\n newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {\n return new FreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR);\n }\n getOutlines() {\n const top = this.#top;\n const bottom = this.#bottom;\n const last = this.#last;\n const [layerX, layerY, layerWidth, layerHeight] = this.#box;\n const points = new Float32Array((this.#points?.length ?? 0) + 2);\n for (let i = 0, ii = points.length - 2; i < ii; i += 2) {\n points[i] = (this.#points[i] - layerX) / layerWidth;\n points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight;\n }\n points[points.length - 2] = (this.#lastX - layerX) / layerWidth;\n points[points.length - 1] = (this.#lastY - layerY) / layerHeight;\n if (isNaN(last[6]) && !this.isEmpty()) {\n return this.#getOutlineTwoPoints(points);\n }\n const outline = new Float32Array(this.#top.length + 24 + this.#bottom.length);\n let N = top.length;\n for (let i = 0; i < N; i += 2) {\n if (isNaN(top[i])) {\n outline[i] = outline[i + 1] = NaN;\n continue;\n }\n outline[i] = top[i];\n outline[i + 1] = top[i + 1];\n }\n N = this.#getOutlineEnd(outline, N);\n for (let i = bottom.length - 6; i >= 6; i -= 6) {\n for (let j = 0; j < 6; j += 2) {\n if (isNaN(bottom[i + j])) {\n outline[N] = outline[N + 1] = NaN;\n N += 2;\n continue;\n }\n outline[N] = bottom[i + j];\n outline[N + 1] = bottom[i + j + 1];\n N += 2;\n }\n }\n this.#getOutlineStart(outline, N);\n return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);\n }\n #getOutlineTwoPoints(points) {\n const last = this.#last;\n const [layerX, layerY, layerWidth, layerHeight] = this.#box;\n const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();\n const outline = new Float32Array(36);\n outline.set([NaN, NaN, NaN, NaN, (last[2] - layerX) / layerWidth, (last[3] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[4] - layerX) / layerWidth, (last[5] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (last[16] - layerX) / layerWidth, (last[17] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[14] - layerX) / layerWidth, (last[15] - layerY) / layerHeight], 0);\n return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);\n }\n #getOutlineStart(outline, pos) {\n const bottom = this.#bottom;\n outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], pos);\n return pos += 6;\n }\n #getOutlineEnd(outline, pos) {\n const lastTop = this.#last.subarray(4, 6);\n const lastBottom = this.#last.subarray(16, 18);\n const [layerX, layerY, layerWidth, layerHeight] = this.#box;\n const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();\n outline.set([NaN, NaN, NaN, NaN, (lastTop[0] - layerX) / layerWidth, (lastTop[1] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (lastBottom[0] - layerX) / layerWidth, (lastBottom[1] - layerY) / layerHeight], pos);\n return pos += 24;\n }\n}\nclass FreeDrawOutline extends Outline {\n #box;\n #bbox = new Float32Array(4);\n #innerMargin;\n #isLTR;\n #points;\n #scaleFactor;\n #outline;\n constructor(outline, points, box, scaleFactor, innerMargin, isLTR) {\n super();\n this.#outline = outline;\n this.#points = points;\n this.#box = box;\n this.#scaleFactor = scaleFactor;\n this.#innerMargin = innerMargin;\n this.#isLTR = isLTR;\n this.firstPoint = [NaN, NaN];\n this.lastPoint = [NaN, NaN];\n this.#computeMinMax(isLTR);\n const [x, y, width, height] = this.#bbox;\n for (let i = 0, ii = outline.length; i < ii; i += 2) {\n outline[i] = (outline[i] - x) / width;\n outline[i + 1] = (outline[i + 1] - y) / height;\n }\n for (let i = 0, ii = points.length; i < ii; i += 2) {\n points[i] = (points[i] - x) / width;\n points[i + 1] = (points[i + 1] - y) / height;\n }\n }\n toSVGPath() {\n const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`];\n for (let i = 6, ii = this.#outline.length; i < ii; i += 6) {\n if (isNaN(this.#outline[i])) {\n buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`);\n continue;\n }\n buffer.push(`C${this.#outline[i]} ${this.#outline[i + 1]} ${this.#outline[i + 2]} ${this.#outline[i + 3]} ${this.#outline[i + 4]} ${this.#outline[i + 5]}`);\n }\n buffer.push("Z");\n return buffer.join(" ");\n }\n serialize([blX, blY, trX, trY], rotation) {\n const width = trX - blX;\n const height = trY - blY;\n let outline;\n let points;\n switch (rotation) {\n case 0:\n outline = Outline._rescale(this.#outline, blX, trY, width, -height);\n points = Outline._rescale(this.#points, blX, trY, width, -height);\n break;\n case 90:\n outline = Outline._rescaleAndSwap(this.#outline, blX, blY, width, height);\n points = Outline._rescaleAndSwap(this.#points, blX, blY, width, height);\n break;\n case 180:\n outline = Outline._rescale(this.#outline, trX, blY, -width, height);\n points = Outline._rescale(this.#points, trX, blY, -width, height);\n break;\n case 270:\n outline = Outline._rescaleAndSwap(this.#outline, trX, trY, -width, -height);\n points = Outline._rescaleAndSwap(this.#points, trX, trY, -width, -height);\n break;\n }\n return {\n outline: Array.from(outline),\n points: [Array.from(points)]\n };\n }\n #computeMinMax(isLTR) {\n const outline = this.#outline;\n let lastX = outline[4];\n let lastY = outline[5];\n const minMax = [lastX, lastY, lastX, lastY];\n let firstPointX = lastX;\n let firstPointY = lastY;\n let lastPointX = lastX;\n let lastPointY = lastY;\n const ltrCallback = isLTR ? Math.max : Math.min;\n const bezierBbox = new Float32Array(4);\n for (let i = 6, ii = outline.length; i < ii; i += 6) {\n const x = outline[i + 4],\n y = outline[i + 5];\n if (isNaN(outline[i])) {\n Util.pointBoundingBox(x, y, minMax);\n if (firstPointY > y) {\n firstPointX = x;\n firstPointY = y;\n } else if (firstPointY === y) {\n firstPointX = ltrCallback(firstPointX, x);\n }\n if (lastPointY < y) {\n lastPointX = x;\n lastPointY = y;\n } else if (lastPointY === y) {\n lastPointX = ltrCallback(lastPointX, x);\n }\n } else {\n bezierBbox[0] = bezierBbox[1] = Infinity;\n bezierBbox[2] = bezierBbox[3] = -Infinity;\n Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6), bezierBbox);\n Util.rectBoundingBox(bezierBbox[0], bezierBbox[1], bezierBbox[2], bezierBbox[3], minMax);\n if (firstPointY > bezierBbox[1]) {\n firstPointX = bezierBbox[0];\n firstPointY = bezierBbox[1];\n } else if (firstPointY === bezierBbox[1]) {\n firstPointX = ltrCallback(firstPointX, bezierBbox[0]);\n }\n if (lastPointY < bezierBbox[3]) {\n lastPointX = bezierBbox[2];\n lastPointY = bezierBbox[3];\n } else if (lastPointY === bezierBbox[3]) {\n lastPointX = ltrCallback(lastPointX, bezierBbox[2]);\n }\n }\n lastX = x;\n lastY = y;\n }\n const bbox = this.#bbox;\n bbox[0] = minMax[0] - this.#innerMargin;\n bbox[1] = minMax[1] - this.#innerMargin;\n bbox[2] = minMax[2] - minMax[0] + 2 * this.#innerMargin;\n bbox[3] = minMax[3] - minMax[1] + 2 * this.#innerMargin;\n this.firstPoint = [firstPointX, firstPointY];\n this.lastPoint = [lastPointX, lastPointY];\n }\n get box() {\n return this.#bbox;\n }\n newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {\n return new FreeDrawOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);\n }\n getNewOutline(thickness, innerMargin) {\n const [x, y, width, height] = this.#bbox;\n const [layerX, layerY, layerWidth, layerHeight] = this.#box;\n const sx = width * layerWidth;\n const sy = height * layerHeight;\n const tx = x * layerWidth + layerX;\n const ty = y * layerHeight + layerY;\n const outliner = this.newOutliner({\n x: this.#points[0] * sx + tx,\n y: this.#points[1] * sy + ty\n }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin);\n for (let i = 2; i < this.#points.length; i += 2) {\n outliner.add({\n x: this.#points[i] * sx + tx,\n y: this.#points[i + 1] * sy + ty\n });\n }\n return outliner.getOutlines();\n }\n}\n\n;// ./src/display/editor/drawers/highlight.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass HighlightOutliner {\n #box;\n #firstPoint;\n #lastPoint;\n #verticalEdges = [];\n #intervals = [];\n constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) {\n const minMax = [Infinity, Infinity, -Infinity, -Infinity];\n const NUMBER_OF_DIGITS = 4;\n const EPSILON = 10 ** -NUMBER_OF_DIGITS;\n for (const {\n x,\n y,\n width,\n height\n } of boxes) {\n const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON;\n const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON;\n const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON;\n const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON;\n const left = [x1, y1, y2, true];\n const right = [x2, y1, y2, false];\n this.#verticalEdges.push(left, right);\n Util.rectBoundingBox(x1, y1, x2, y2, minMax);\n }\n const bboxWidth = minMax[2] - minMax[0] + 2 * innerMargin;\n const bboxHeight = minMax[3] - minMax[1] + 2 * innerMargin;\n const shiftedMinX = minMax[0] - innerMargin;\n const shiftedMinY = minMax[1] - innerMargin;\n let firstPointX = isLTR ? -Infinity : Infinity;\n let firstPointY = Infinity;\n const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2);\n const lastPoint = [lastEdge[0], lastEdge[2]];\n for (const edge of this.#verticalEdges) {\n const [x, y1, y2, left] = edge;\n if (!left && isLTR) {\n if (y1 < firstPointY) {\n firstPointY = y1;\n firstPointX = x;\n } else if (y1 === firstPointY) {\n firstPointX = Math.max(firstPointX, x);\n }\n } else if (left && !isLTR) {\n if (y1 < firstPointY) {\n firstPointY = y1;\n firstPointX = x;\n } else if (y1 === firstPointY) {\n firstPointX = Math.min(firstPointX, x);\n }\n }\n edge[0] = (x - shiftedMinX) / bboxWidth;\n edge[1] = (y1 - shiftedMinY) / bboxHeight;\n edge[2] = (y2 - shiftedMinY) / bboxHeight;\n }\n this.#box = new Float32Array([shiftedMinX, shiftedMinY, bboxWidth, bboxHeight]);\n this.#firstPoint = [firstPointX, firstPointY];\n this.#lastPoint = lastPoint;\n }\n getOutlines() {\n this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);\n const outlineVerticalEdges = [];\n for (const edge of this.#verticalEdges) {\n if (edge[3]) {\n outlineVerticalEdges.push(...this.#breakEdge(edge));\n this.#insert(edge);\n } else {\n this.#remove(edge);\n outlineVerticalEdges.push(...this.#breakEdge(edge));\n }\n }\n return this.#getOutlines(outlineVerticalEdges);\n }\n #getOutlines(outlineVerticalEdges) {\n const edges = [];\n const allEdges = new Set();\n for (const edge of outlineVerticalEdges) {\n const [x, y1, y2] = edge;\n edges.push([x, y1, edge], [x, y2, edge]);\n }\n edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]);\n for (let i = 0, ii = edges.length; i < ii; i += 2) {\n const edge1 = edges[i][2];\n const edge2 = edges[i + 1][2];\n edge1.push(edge2);\n edge2.push(edge1);\n allEdges.add(edge1);\n allEdges.add(edge2);\n }\n const outlines = [];\n let outline;\n while (allEdges.size > 0) {\n const edge = allEdges.values().next().value;\n let [x, y1, y2, edge1, edge2] = edge;\n allEdges.delete(edge);\n let lastPointX = x;\n let lastPointY = y1;\n outline = [x, y2];\n outlines.push(outline);\n while (true) {\n let e;\n if (allEdges.has(edge1)) {\n e = edge1;\n } else if (allEdges.has(edge2)) {\n e = edge2;\n } else {\n break;\n }\n allEdges.delete(e);\n [x, y1, y2, edge1, edge2] = e;\n if (lastPointX !== x) {\n outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2);\n lastPointX = x;\n }\n lastPointY = lastPointY === y1 ? y2 : y1;\n }\n outline.push(lastPointX, lastPointY);\n }\n return new HighlightOutline(outlines, this.#box, this.#firstPoint, this.#lastPoint);\n }\n #binarySearch(y) {\n const array = this.#intervals;\n let start = 0;\n let end = array.length - 1;\n while (start <= end) {\n const middle = start + end >> 1;\n const y1 = array[middle][0];\n if (y1 === y) {\n return middle;\n }\n if (y1 < y) {\n start = middle + 1;\n } else {\n end = middle - 1;\n }\n }\n return end + 1;\n }\n #insert([, y1, y2]) {\n const index = this.#binarySearch(y1);\n this.#intervals.splice(index, 0, [y1, y2]);\n }\n #remove([, y1, y2]) {\n const index = this.#binarySearch(y1);\n for (let i = index; i < this.#intervals.length; i++) {\n const [start, end] = this.#intervals[i];\n if (start !== y1) {\n break;\n }\n if (start === y1 && end === y2) {\n this.#intervals.splice(i, 1);\n return;\n }\n }\n for (let i = index - 1; i >= 0; i--) {\n const [start, end] = this.#intervals[i];\n if (start !== y1) {\n break;\n }\n if (start === y1 && end === y2) {\n this.#intervals.splice(i, 1);\n return;\n }\n }\n }\n #breakEdge(edge) {\n const [x, y1, y2] = edge;\n const results = [[x, y1, y2]];\n const index = this.#binarySearch(y2);\n for (let i = 0; i < index; i++) {\n const [start, end] = this.#intervals[i];\n for (let j = 0, jj = results.length; j < jj; j++) {\n const [, y3, y4] = results[j];\n if (end <= y3 || y4 <= start) {\n continue;\n }\n if (y3 >= start) {\n if (y4 > end) {\n results[j][1] = end;\n } else {\n if (jj === 1) {\n return [];\n }\n results.splice(j, 1);\n j--;\n jj--;\n }\n continue;\n }\n results[j][2] = start;\n if (y4 > end) {\n results.push([x, end, y4]);\n }\n }\n }\n return results;\n }\n}\nclass HighlightOutline extends Outline {\n #box;\n #outlines;\n constructor(outlines, box, firstPoint, lastPoint) {\n super();\n this.#outlines = outlines;\n this.#box = box;\n this.firstPoint = firstPoint;\n this.lastPoint = lastPoint;\n }\n toSVGPath() {\n const buffer = [];\n for (const polygon of this.#outlines) {\n let [prevX, prevY] = polygon;\n buffer.push(`M${prevX} ${prevY}`);\n for (let i = 2; i < polygon.length; i += 2) {\n const x = polygon[i];\n const y = polygon[i + 1];\n if (x === prevX) {\n buffer.push(`V${y}`);\n prevY = y;\n } else if (y === prevY) {\n buffer.push(`H${x}`);\n prevX = x;\n }\n }\n buffer.push("Z");\n }\n return buffer.join(" ");\n }\n serialize([blX, blY, trX, trY], _rotation) {\n const outlines = [];\n const width = trX - blX;\n const height = trY - blY;\n for (const outline of this.#outlines) {\n const points = new Array(outline.length);\n for (let i = 0; i < outline.length; i += 2) {\n points[i] = blX + outline[i] * width;\n points[i + 1] = trY - outline[i + 1] * height;\n }\n outlines.push(points);\n }\n return outlines;\n }\n get box() {\n return this.#box;\n }\n get classNamesForOutlining() {\n return ["highlightOutline"];\n }\n}\nclass FreeHighlightOutliner extends FreeDrawOutliner {\n newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {\n return new FreeHighlightOutline(outline, points, box, scaleFactor, innerMargin, isLTR);\n }\n}\nclass FreeHighlightOutline extends FreeDrawOutline {\n newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {\n return new FreeHighlightOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);\n }\n}\n\n;// ./src/display/editor/highlight.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass HighlightEditor extends AnnotationEditor {\n #anchorNode = null;\n #anchorOffset = 0;\n #boxes;\n #clipPathId = null;\n #colorPicker = null;\n #focusOutlines = null;\n #focusNode = null;\n #focusOffset = 0;\n #highlightDiv = null;\n #highlightOutlines = null;\n #id = null;\n #isFreeHighlight = false;\n #firstPoint = null;\n #lastPoint = null;\n #outlineId = null;\n #text = "";\n #thickness;\n #methodOfCreation = "";\n static _defaultColor = null;\n static _defaultOpacity = 1;\n static _defaultThickness = 12;\n static _type = "highlight";\n static _editorType = AnnotationEditorType.HIGHLIGHT;\n static _freeHighlightId = -1;\n static _freeHighlight = null;\n static _freeHighlightClipId = "";\n static get _keyboardManager() {\n const proto = HighlightEditor.prototype;\n return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, {\n args: [0]\n }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, {\n args: [1]\n }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, {\n args: [2]\n }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, {\n args: [3]\n }]]));\n }\n constructor(params) {\n super({\n ...params,\n name: "highlightEditor"\n });\n this.color = params.color || HighlightEditor._defaultColor;\n this.#thickness = params.thickness || HighlightEditor._defaultThickness;\n this.opacity = params.opacity || HighlightEditor._defaultOpacity;\n this.#boxes = params.boxes || null;\n this.#methodOfCreation = params.methodOfCreation || "";\n this.#text = params.text || "";\n this._isDraggable = false;\n this.defaultL10nId = "pdfjs-editor-highlight-editor";\n if (params.highlightId > -1) {\n this.#isFreeHighlight = true;\n this.#createFreeOutlines(params);\n this.#addToDrawLayer();\n } else if (this.#boxes) {\n this.#anchorNode = params.anchorNode;\n this.#anchorOffset = params.anchorOffset;\n this.#focusNode = params.focusNode;\n this.#focusOffset = params.focusOffset;\n this.#createOutlines();\n this.#addToDrawLayer();\n this.rotate(this.rotation);\n }\n if (!this.annotationElementId) {\n this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert");\n }\n }\n get telemetryInitialData() {\n return {\n action: "added",\n type: this.#isFreeHighlight ? "free_highlight" : "highlight",\n color: this._uiManager.getNonHCMColorName(this.color),\n thickness: this.#thickness,\n methodOfCreation: this.#methodOfCreation\n };\n }\n get telemetryFinalData() {\n return {\n type: "highlight",\n color: this._uiManager.getNonHCMColorName(this.color)\n };\n }\n static computeTelemetryFinalData(data) {\n return {\n numberOfColors: data.get("color").size\n };\n }\n #createOutlines() {\n const outliner = new HighlightOutliner(this.#boxes, 0.001);\n this.#highlightOutlines = outliner.getOutlines();\n [this.x, this.y, this.width, this.height] = this.#highlightOutlines.box;\n const outlinerForOutline = new HighlightOutliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr");\n this.#focusOutlines = outlinerForOutline.getOutlines();\n const {\n firstPoint\n } = this.#highlightOutlines;\n this.#firstPoint = [(firstPoint[0] - this.x) / this.width, (firstPoint[1] - this.y) / this.height];\n const {\n lastPoint\n } = this.#focusOutlines;\n this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height];\n }\n #createFreeOutlines({\n highlightOutlines,\n highlightId,\n clipPathId\n }) {\n this.#highlightOutlines = highlightOutlines;\n const extraThickness = 1.5;\n this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025);\n if (highlightId >= 0) {\n this.#id = highlightId;\n this.#clipPathId = clipPathId;\n this.parent.drawLayer.finalizeDraw(highlightId, {\n bbox: highlightOutlines.box,\n path: {\n d: highlightOutlines.toSVGPath()\n }\n });\n this.#outlineId = this.parent.drawLayer.drawOutline({\n rootClass: {\n highlightOutline: true,\n free: true\n },\n bbox: this.#focusOutlines.box,\n path: {\n d: this.#focusOutlines.toSVGPath()\n }\n }, true);\n } else if (this.parent) {\n const angle = this.parent.viewport.rotation;\n this.parent.drawLayer.updateProperties(this.#id, {\n bbox: HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360),\n path: {\n d: highlightOutlines.toSVGPath()\n }\n });\n this.parent.drawLayer.updateProperties(this.#outlineId, {\n bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle),\n path: {\n d: this.#focusOutlines.toSVGPath()\n }\n });\n }\n const [x, y, width, height] = highlightOutlines.box;\n switch (this.rotation) {\n case 0:\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n break;\n case 90:\n {\n const [pageWidth, pageHeight] = this.parentDimensions;\n this.x = y;\n this.y = 1 - x;\n this.width = width * pageHeight / pageWidth;\n this.height = height * pageWidth / pageHeight;\n break;\n }\n case 180:\n this.x = 1 - x;\n this.y = 1 - y;\n this.width = width;\n this.height = height;\n break;\n case 270:\n {\n const [pageWidth, pageHeight] = this.parentDimensions;\n this.x = 1 - y;\n this.y = x;\n this.width = width * pageHeight / pageWidth;\n this.height = height * pageWidth / pageHeight;\n break;\n }\n }\n const {\n firstPoint\n } = highlightOutlines;\n this.#firstPoint = [(firstPoint[0] - x) / width, (firstPoint[1] - y) / height];\n const {\n lastPoint\n } = this.#focusOutlines;\n this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height];\n }\n static initialize(l10n, uiManager) {\n AnnotationEditor.initialize(l10n, uiManager);\n HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066";\n }\n static updateDefaultParams(type, value) {\n switch (type) {\n case AnnotationEditorParamsType.HIGHLIGHT_COLOR:\n HighlightEditor._defaultColor = value;\n break;\n case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:\n HighlightEditor._defaultThickness = value;\n break;\n }\n }\n translateInPage(x, y) {}\n get toolbarPosition() {\n return this.#lastPoint;\n }\n get commentButtonPosition() {\n return this.#firstPoint;\n }\n updateParams(type, value) {\n switch (type) {\n case AnnotationEditorParamsType.HIGHLIGHT_COLOR:\n this.#updateColor(value);\n break;\n case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:\n this.#updateThickness(value);\n break;\n }\n }\n static get defaultPropertiesToUpdate() {\n return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]];\n }\n get propertiesToUpdate() {\n return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]];\n }\n onUpdatedColor() {\n this.parent?.drawLayer.updateProperties(this.#id, {\n root: {\n fill: this.color,\n "fill-opacity": this.opacity\n }\n });\n this.#colorPicker?.updateColor(this.color);\n super.onUpdatedColor();\n }\n #updateColor(color) {\n const setColorAndOpacity = (col, opa) => {\n this.color = col;\n this.opacity = opa;\n this.onUpdatedColor();\n };\n const savedColor = this.color;\n const savedOpacity = this.opacity;\n this.addCommands({\n cmd: setColorAndOpacity.bind(this, color, HighlightEditor._defaultOpacity),\n undo: setColorAndOpacity.bind(this, savedColor, savedOpacity),\n post: this._uiManager.updateUI.bind(this._uiManager, this),\n mustExec: true,\n type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,\n overwriteIfSameType: true,\n keepUndo: true\n });\n this._reportTelemetry({\n action: "color_changed",\n color: this._uiManager.getNonHCMColorName(color)\n }, true);\n }\n #updateThickness(thickness) {\n const savedThickness = this.#thickness;\n const setThickness = th => {\n this.#thickness = th;\n this.#changeThickness(th);\n };\n this.addCommands({\n cmd: setThickness.bind(this, thickness),\n undo: setThickness.bind(this, savedThickness),\n post: this._uiManager.updateUI.bind(this._uiManager, this),\n mustExec: true,\n type: AnnotationEditorParamsType.INK_THICKNESS,\n overwriteIfSameType: true,\n keepUndo: true\n });\n this._reportTelemetry({\n action: "thickness_changed",\n thickness\n }, true);\n }\n get toolbarButtons() {\n if (this._uiManager.highlightColors) {\n const colorPicker = this.#colorPicker = new ColorPicker({\n editor: this\n });\n return [["colorPicker", colorPicker]];\n }\n return super.toolbarButtons;\n }\n disableEditing() {\n super.disableEditing();\n this.div.classList.toggle("disabled", true);\n }\n enableEditing() {\n super.enableEditing();\n this.div.classList.toggle("disabled", false);\n }\n fixAndSetPosition() {\n return super.fixAndSetPosition(this.#getRotation());\n }\n getBaseTranslation() {\n return [0, 0];\n }\n getRect(tx, ty) {\n return super.getRect(tx, ty, this.#getRotation());\n }\n onceAdded(focus) {\n if (!this.annotationElementId) {\n this.parent.addUndoableEditor(this);\n }\n if (focus) {\n this.div.focus();\n }\n }\n remove() {\n this.#cleanDrawLayer();\n this._reportTelemetry({\n action: "deleted"\n });\n super.remove();\n }\n rebuild() {\n if (!this.parent) {\n return;\n }\n super.rebuild();\n if (this.div === null) {\n return;\n }\n this.#addToDrawLayer();\n if (!this.isAttachedToDOM) {\n this.parent.add(this);\n }\n }\n setParent(parent) {\n let mustBeSelected = false;\n if (this.parent && !parent) {\n this.#cleanDrawLayer();\n } else if (parent) {\n this.#addToDrawLayer(parent);\n mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");\n }\n super.setParent(parent);\n this.show(this._isVisible);\n if (mustBeSelected) {\n this.select();\n }\n }\n #changeThickness(thickness) {\n if (!this.#isFreeHighlight) {\n return;\n }\n this.#createFreeOutlines({\n highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2)\n });\n this.fixAndSetPosition();\n this.setDims();\n }\n #cleanDrawLayer() {\n if (this.#id === null || !this.parent) {\n return;\n }\n this.parent.drawLayer.remove(this.#id);\n this.#id = null;\n this.parent.drawLayer.remove(this.#outlineId);\n this.#outlineId = null;\n }\n #addToDrawLayer(parent = this.parent) {\n if (this.#id !== null) {\n return;\n }\n ({\n id: this.#id,\n clipPathId: this.#clipPathId\n } = parent.drawLayer.draw({\n bbox: this.#highlightOutlines.box,\n root: {\n viewBox: "0 0 1 1",\n fill: this.color,\n "fill-opacity": this.opacity\n },\n rootClass: {\n highlight: true,\n free: this.#isFreeHighlight\n },\n path: {\n d: this.#highlightOutlines.toSVGPath()\n }\n }, false, true));\n this.#outlineId = parent.drawLayer.drawOutline({\n rootClass: {\n highlightOutline: true,\n free: this.#isFreeHighlight\n },\n bbox: this.#focusOutlines.box,\n path: {\n d: this.#focusOutlines.toSVGPath()\n }\n }, this.#isFreeHighlight);\n if (this.#highlightDiv) {\n this.#highlightDiv.style.clipPath = this.#clipPathId;\n }\n }\n static #rotateBbox([x, y, width, height], angle) {\n switch (angle) {\n case 90:\n return [1 - y - height, x, height, width];\n case 180:\n return [1 - x - width, 1 - y - height, width, height];\n case 270:\n return [y, 1 - x - width, height, width];\n }\n return [x, y, width, height];\n }\n rotate(angle) {\n const {\n drawLayer\n } = this.parent;\n let box;\n if (this.#isFreeHighlight) {\n angle = (angle - this.rotation + 360) % 360;\n box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle);\n } else {\n box = HighlightEditor.#rotateBbox([this.x, this.y, this.width, this.height], angle);\n }\n drawLayer.updateProperties(this.#id, {\n bbox: box,\n root: {\n "data-main-rotation": angle\n }\n });\n drawLayer.updateProperties(this.#outlineId, {\n bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle),\n root: {\n "data-main-rotation": angle\n }\n });\n }\n render() {\n if (this.div) {\n return this.div;\n }\n const div = super.render();\n if (this.#text) {\n div.setAttribute("aria-label", this.#text);\n div.setAttribute("role", "mark");\n }\n if (this.#isFreeHighlight) {\n div.classList.add("free");\n } else {\n this.div.addEventListener("keydown", this.#keydown.bind(this), {\n signal: this._uiManager._signal\n });\n }\n const highlightDiv = this.#highlightDiv = document.createElement("div");\n div.append(highlightDiv);\n highlightDiv.setAttribute("aria-hidden", "true");\n highlightDiv.className = "internal";\n highlightDiv.style.clipPath = this.#clipPathId;\n this.setDims();\n bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]);\n this.enableEditing();\n return div;\n }\n pointerover() {\n if (!this.isSelected) {\n this.parent?.drawLayer.updateProperties(this.#outlineId, {\n rootClass: {\n hovered: true\n }\n });\n }\n }\n pointerleave() {\n if (!this.isSelected) {\n this.parent?.drawLayer.updateProperties(this.#outlineId, {\n rootClass: {\n hovered: false\n }\n });\n }\n }\n #keydown(event) {\n HighlightEditor._keyboardManager.exec(this, event);\n }\n _moveCaret(direction) {\n this.parent.unselect(this);\n switch (direction) {\n case 0:\n case 2:\n this.#setCaret(true);\n break;\n case 1:\n case 3:\n this.#setCaret(false);\n break;\n }\n }\n #setCaret(start) {\n if (!this.#anchorNode) {\n return;\n }\n const selection = window.getSelection();\n if (start) {\n selection.setPosition(this.#anchorNode, this.#anchorOffset);\n } else {\n selection.setPosition(this.#focusNode, this.#focusOffset);\n }\n }\n select() {\n super.select();\n if (!this.#outlineId) {\n return;\n }\n this.parent?.drawLayer.updateProperties(this.#outlineId, {\n rootClass: {\n hovered: false,\n selected: true\n }\n });\n }\n unselect() {\n super.unselect();\n if (!this.#outlineId) {\n return;\n }\n this.parent?.drawLayer.updateProperties(this.#outlineId, {\n rootClass: {\n selected: false\n }\n });\n if (!this.#isFreeHighlight) {\n this.#setCaret(false);\n }\n }\n get _mustFixPosition() {\n return !this.#isFreeHighlight;\n }\n show(visible = this._isVisible) {\n super.show(visible);\n if (this.parent) {\n this.parent.drawLayer.updateProperties(this.#id, {\n rootClass: {\n hidden: !visible\n }\n });\n this.parent.drawLayer.updateProperties(this.#outlineId, {\n rootClass: {\n hidden: !visible\n }\n });\n }\n }\n #getRotation() {\n return this.#isFreeHighlight ? this.rotation : 0;\n }\n #serializeBoxes() {\n if (this.#isFreeHighlight) {\n return null;\n }\n const [pageWidth, pageHeight] = this.pageDimensions;\n const [pageX, pageY] = this.pageTranslation;\n const boxes = this.#boxes;\n const quadPoints = new Float32Array(boxes.length * 8);\n let i = 0;\n for (const {\n x,\n y,\n width,\n height\n } of boxes) {\n const sx = x * pageWidth + pageX;\n const sy = (1 - y) * pageHeight + pageY;\n quadPoints[i] = quadPoints[i + 4] = sx;\n quadPoints[i + 1] = quadPoints[i + 3] = sy;\n quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth;\n quadPoints[i + 5] = quadPoints[i + 7] = sy - height * pageHeight;\n i += 8;\n }\n return quadPoints;\n }\n #serializeOutlines(rect) {\n return this.#highlightOutlines.serialize(rect, this.#getRotation());\n }\n static startHighlighting(parent, isLTR, {\n target: textLayer,\n x,\n y\n }) {\n const {\n x: layerX,\n y: layerY,\n width: parentWidth,\n height: parentHeight\n } = textLayer.getBoundingClientRect();\n const ac = new AbortController();\n const signal = parent.combinedSignal(ac);\n const pointerUpCallback = e => {\n ac.abort();\n this.#endHighlight(parent, e);\n };\n window.addEventListener("blur", pointerUpCallback, {\n signal\n });\n window.addEventListener("pointerup", pointerUpCallback, {\n signal\n });\n window.addEventListener("pointerdown", stopEvent, {\n capture: true,\n passive: false,\n signal\n });\n window.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), {\n signal\n });\n this._freeHighlight = new FreeHighlightOutliner({\n x,\n y\n }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001);\n ({\n id: this._freeHighlightId,\n clipPathId: this._freeHighlightClipId\n } = parent.drawLayer.draw({\n bbox: [0, 0, 1, 1],\n root: {\n viewBox: "0 0 1 1",\n fill: this._defaultColor,\n "fill-opacity": this._defaultOpacity\n },\n rootClass: {\n highlight: true,\n free: true\n },\n path: {\n d: this._freeHighlight.toSVGPath()\n }\n }, true, true));\n }\n static #highlightMove(parent, event) {\n if (this._freeHighlight.add(event)) {\n parent.drawLayer.updateProperties(this._freeHighlightId, {\n path: {\n d: this._freeHighlight.toSVGPath()\n }\n });\n }\n }\n static #endHighlight(parent, event) {\n if (!this._freeHighlight.isEmpty()) {\n parent.createAndAddNewEditor(event, false, {\n highlightId: this._freeHighlightId,\n highlightOutlines: this._freeHighlight.getOutlines(),\n clipPathId: this._freeHighlightClipId,\n methodOfCreation: "main_toolbar"\n });\n } else {\n parent.drawLayer.remove(this._freeHighlightId);\n }\n this._freeHighlightId = -1;\n this._freeHighlight = null;\n this._freeHighlightClipId = "";\n }\n static async deserialize(data, parent, uiManager) {\n let initialData = null;\n if (data instanceof HighlightAnnotationElement) {\n const {\n data: {\n quadPoints,\n rect,\n rotation,\n id,\n color,\n opacity,\n popupRef,\n richText,\n contentsObj,\n creationDate,\n modificationDate\n },\n parent: {\n page: {\n pageNumber\n }\n }\n } = data;\n initialData = data = {\n annotationType: AnnotationEditorType.HIGHLIGHT,\n color: Array.from(color),\n opacity,\n quadPoints,\n boxes: null,\n pageIndex: pageNumber - 1,\n rect: rect.slice(0),\n rotation,\n annotationElementId: id,\n id,\n deleted: false,\n popupRef,\n richText,\n comment: contentsObj?.str || null,\n creationDate,\n modificationDate\n };\n } else if (data instanceof InkAnnotationElement) {\n const {\n data: {\n inkLists,\n rect,\n rotation,\n id,\n color,\n borderStyle: {\n rawWidth: thickness\n },\n popupRef,\n richText,\n contentsObj,\n creationDate,\n modificationDate\n },\n parent: {\n page: {\n pageNumber\n }\n }\n } = data;\n initialData = data = {\n annotationType: AnnotationEditorType.HIGHLIGHT,\n color: Array.from(color),\n thickness,\n inkLists,\n boxes: null,\n pageIndex: pageNumber - 1,\n rect: rect.slice(0),\n rotation,\n annotationElementId: id,\n id,\n deleted: false,\n popupRef,\n richText,\n comment: contentsObj?.str || null,\n creationDate,\n modificationDate\n };\n }\n const {\n color,\n quadPoints,\n inkLists,\n opacity\n } = data;\n const editor = await super.deserialize(data, parent, uiManager);\n editor.color = Util.makeHexColor(...color);\n editor.opacity = opacity || 1;\n if (inkLists) {\n editor.#thickness = data.thickness;\n }\n editor._initialData = initialData;\n if (data.comment) {\n editor.setCommentData(data);\n }\n const [pageWidth, pageHeight] = editor.pageDimensions;\n const [pageX, pageY] = editor.pageTranslation;\n if (quadPoints) {\n const boxes = editor.#boxes = [];\n for (let i = 0; i < quadPoints.length; i += 8) {\n boxes.push({\n x: (quadPoints[i] - pageX) / pageWidth,\n y: 1 - (quadPoints[i + 1] - pageY) / pageHeight,\n width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth,\n height: (quadPoints[i + 1] - quadPoints[i + 5]) / pageHeight\n });\n }\n editor.#createOutlines();\n editor.#addToDrawLayer();\n editor.rotate(editor.rotation);\n } else if (inkLists) {\n editor.#isFreeHighlight = true;\n const points = inkLists[0];\n const point = {\n x: points[0] - pageX,\n y: pageHeight - (points[1] - pageY)\n };\n const outliner = new FreeHighlightOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 0.001);\n for (let i = 0, ii = points.length; i < ii; i += 2) {\n point.x = points[i] - pageX;\n point.y = pageHeight - (points[i + 1] - pageY);\n outliner.add(point);\n }\n const {\n id,\n clipPathId\n } = parent.drawLayer.draw({\n bbox: [0, 0, 1, 1],\n root: {\n viewBox: "0 0 1 1",\n fill: editor.color,\n "fill-opacity": editor._defaultOpacity\n },\n rootClass: {\n highlight: true,\n free: true\n },\n path: {\n d: outliner.toSVGPath()\n }\n }, true, true);\n editor.#createFreeOutlines({\n highlightOutlines: outliner.getOutlines(),\n highlightId: id,\n clipPathId\n });\n editor.#addToDrawLayer();\n editor.rotate(editor.parentRotation);\n }\n return editor;\n }\n serialize(isForCopying = false) {\n if (this.isEmpty() || isForCopying) {\n return null;\n }\n if (this.deleted) {\n return this.serializeDeleted();\n }\n const color = AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color));\n const serialized = super.serialize(isForCopying);\n Object.assign(serialized, {\n color,\n opacity: this.opacity,\n thickness: this.#thickness,\n quadPoints: this.#serializeBoxes(),\n outlines: this.#serializeOutlines(serialized.rect)\n });\n this.addComment(serialized);\n if (this.annotationElementId && !this.#hasElementChanged(serialized)) {\n return null;\n }\n serialized.id = this.annotationElementId;\n return serialized;\n }\n #hasElementChanged(serialized) {\n const {\n color\n } = this._initialData;\n return this.hasEditedComment || serialized.color.some((c, i) => c !== color[i]);\n }\n renderAnnotationElement(annotation) {\n if (this.deleted) {\n annotation.hide();\n return null;\n }\n annotation.updateEdited({\n rect: this.getPDFRect(),\n popup: this.comment\n });\n return null;\n }\n static canCreateNewEmptyEditor() {\n return false;\n }\n}\n\n;// ./src/display/editor/draw.js\n\n\n\n\n\n\n\n\n\n\n\n\nclass DrawingOptions {\n #svgProperties = Object.create(null);\n updateProperty(name, value) {\n this[name] = value;\n this.updateSVGProperty(name, value);\n }\n updateProperties(properties) {\n if (!properties) {\n return;\n }\n for (const [name, value] of Object.entries(properties)) {\n if (!name.startsWith("_")) {\n this.updateProperty(name, value);\n }\n }\n }\n updateSVGProperty(name, value) {\n this.#svgProperties[name] = value;\n }\n toSVGProperties() {\n const root = this.#svgProperties;\n this.#svgProperties = Object.create(null);\n return {\n root\n };\n }\n reset() {\n this.#svgProperties = Object.create(null);\n }\n updateAll(options = this) {\n this.updateProperties(options);\n }\n clone() {\n unreachable("Not implemented");\n }\n}\nclass DrawingEditor extends AnnotationEditor {\n #drawOutlines = null;\n #mustBeCommitted;\n _colorPicker = null;\n _drawId = null;\n static _currentDrawId = -1;\n static _currentParent = null;\n static #currentDraw = null;\n static #currentDrawingAC = null;\n static #currentDrawingOptions = null;\n static _INNER_MARGIN = 3;\n constructor(params) {\n super(params);\n this.#mustBeCommitted = params.mustBeCommitted || false;\n this._addOutlines(params);\n }\n onUpdatedColor() {\n this._colorPicker?.update(this.color);\n super.onUpdatedColor();\n }\n _addOutlines(params) {\n if (params.drawOutlines) {\n this.#createDrawOutlines(params);\n this.#addToDrawLayer();\n }\n }\n #createDrawOutlines({\n drawOutlines,\n drawId,\n drawingOptions\n }) {\n this.#drawOutlines = drawOutlines;\n this._drawingOptions ||= drawingOptions;\n if (!this.annotationElementId) {\n this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`);\n }\n if (drawId >= 0) {\n this._drawId = drawId;\n this.parent.drawLayer.finalizeDraw(drawId, drawOutlines.defaultProperties);\n } else {\n this._drawId = this.#createDrawing(drawOutlines, this.parent);\n }\n this.#updateBbox(drawOutlines.box);\n }\n #createDrawing(drawOutlines, parent) {\n const {\n id\n } = parent.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(), drawOutlines.defaultSVGProperties), false, false);\n return id;\n }\n static _mergeSVGProperties(p1, p2) {\n const p1Keys = new Set(Object.keys(p1));\n for (const [key, value] of Object.entries(p2)) {\n if (p1Keys.has(key)) {\n Object.assign(p1[key], value);\n } else {\n p1[key] = value;\n }\n }\n return p1;\n }\n static getDefaultDrawingOptions(_options) {\n unreachable("Not implemented");\n }\n static get typesMap() {\n unreachable("Not implemented");\n }\n static get isDrawer() {\n return true;\n }\n static get supportMultipleDrawings() {\n return false;\n }\n static updateDefaultParams(type, value) {\n const propertyName = this.typesMap.get(type);\n if (propertyName) {\n this._defaultDrawingOptions.updateProperty(propertyName, value);\n }\n if (this._currentParent) {\n DrawingEditor.#currentDraw.updateProperty(propertyName, value);\n this._currentParent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties());\n }\n }\n updateParams(type, value) {\n const propertyName = this.constructor.typesMap.get(type);\n if (propertyName) {\n this._updateProperty(type, propertyName, value);\n }\n }\n static get defaultPropertiesToUpdate() {\n const properties = [];\n const options = this._defaultDrawingOptions;\n for (const [type, name] of this.typesMap) {\n properties.push([type, options[name]]);\n }\n return properties;\n }\n get propertiesToUpdate() {\n const properties = [];\n const {\n _drawingOptions\n } = this;\n for (const [type, name] of this.constructor.typesMap) {\n properties.push([type, _drawingOptions[name]]);\n }\n return properties;\n }\n _updateProperty(type, name, value) {\n const options = this._drawingOptions;\n const savedValue = options[name];\n const setter = val => {\n options.updateProperty(name, val);\n const bbox = this.#drawOutlines.updateProperty(name, val);\n if (bbox) {\n this.#updateBbox(bbox);\n }\n this.parent?.drawLayer.updateProperties(this._drawId, options.toSVGProperties());\n if (type === this.colorType) {\n this.onUpdatedColor();\n }\n };\n this.addCommands({\n cmd: setter.bind(this, value),\n undo: setter.bind(this, savedValue),\n post: this._uiManager.updateUI.bind(this._uiManager, this),\n mustExec: true,\n type,\n overwriteIfSameType: true,\n keepUndo: true\n });\n }\n _onResizing() {\n this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizingSVGProperties(this.#convertToDrawSpace()), {\n bbox: this.#rotateBox()\n }));\n }\n _onResized() {\n this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizedSVGProperties(this.#convertToDrawSpace()), {\n bbox: this.#rotateBox()\n }));\n }\n _onTranslating(_x, _y) {\n this.parent?.drawLayer.updateProperties(this._drawId, {\n bbox: this.#rotateBox()\n });\n }\n _onTranslated() {\n this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathTranslatedSVGProperties(this.#convertToDrawSpace(), this.parentDimensions), {\n bbox: this.#rotateBox()\n }));\n }\n _onStartDragging() {\n this.parent?.drawLayer.updateProperties(this._drawId, {\n rootClass: {\n moving: true\n }\n });\n }\n _onStopDragging() {\n this.parent?.drawLayer.updateProperties(this._drawId, {\n rootClass: {\n moving: false\n }\n });\n }\n commit() {\n super.commit();\n this.disableEditMode();\n this.disableEditing();\n }\n disableEditing() {\n super.disableEditing();\n this.div.classList.toggle("disabled", true);\n }\n enableEditing() {\n super.enableEditing();\n this.div.classList.toggle("disabled", false);\n }\n getBaseTranslation() {\n return [0, 0];\n }\n get isResizable() {\n return true;\n }\n onceAdded(focus) {\n if (!this.annotationElementId) {\n this.parent.addUndoableEditor(this);\n }\n this._isDraggable = true;\n if (this.#mustBeCommitted) {\n this.#mustBeCommitted = false;\n this.commit();\n this.parent.setSelected(this);\n if (focus && this.isOnScreen) {\n this.div.focus();\n }\n }\n }\n remove() {\n this.#cleanDrawLayer();\n super.remove();\n }\n rebuild() {\n if (!this.parent) {\n return;\n }\n super.rebuild();\n if (this.div === null) {\n return;\n }\n this.#addToDrawLayer();\n this.#updateBbox(this.#drawOutlines.box);\n if (!this.isAttachedToDOM) {\n this.parent.add(this);\n }\n }\n setParent(parent) {\n let mustBeSelected = false;\n if (this.parent && !parent) {\n this._uiManager.removeShouldRescale(this);\n this.#cleanDrawLayer();\n } else if (parent) {\n this._uiManager.addShouldRescale(this);\n this.#addToDrawLayer(parent);\n mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");\n }\n super.setParent(parent);\n if (mustBeSelected) {\n this.select();\n }\n }\n #cleanDrawLayer() {\n if (this._drawId === null || !this.parent) {\n return;\n }\n this.parent.drawLayer.remove(this._drawId);\n this._drawId = null;\n this._drawingOptions.reset();\n }\n #addToDrawLayer(parent = this.parent) {\n if (this._drawId !== null && this.parent === parent) {\n return;\n }\n if (this._drawId !== null) {\n this.parent.drawLayer.updateParent(this._drawId, parent.drawLayer);\n return;\n }\n this._drawingOptions.updateAll();\n this._drawId = this.#createDrawing(this.#drawOutlines, parent);\n }\n #convertToParentSpace([x, y, width, height]) {\n const {\n parentDimensions: [pW, pH],\n rotation\n } = this;\n switch (rotation) {\n case 90:\n return [y, 1 - x, width * (pH / pW), height * (pW / pH)];\n case 180:\n return [1 - x, 1 - y, width, height];\n case 270:\n return [1 - y, x, width * (pH / pW), height * (pW / pH)];\n default:\n return [x, y, width, height];\n }\n }\n #convertToDrawSpace() {\n const {\n x,\n y,\n width,\n height,\n parentDimensions: [pW, pH],\n rotation\n } = this;\n switch (rotation) {\n case 90:\n return [1 - y, x, width * (pW / pH), height * (pH / pW)];\n case 180:\n return [1 - x, 1 - y, width, height];\n case 270:\n return [y, 1 - x, width * (pW / pH), height * (pH / pW)];\n default:\n return [x, y, width, height];\n }\n }\n #updateBbox(bbox) {\n [this.x, this.y, this.width, this.height] = this.#convertToParentSpace(bbox);\n if (this.div) {\n this.fixAndSetPosition();\n this.setDims();\n }\n this._onResized();\n }\n #rotateBox() {\n const {\n x,\n y,\n width,\n height,\n rotation,\n parentRotation,\n parentDimensions: [pW, pH]\n } = this;\n switch ((rotation * 4 + parentRotation) / 90) {\n case 1:\n return [1 - y - height, x, height, width];\n case 2:\n return [1 - x - width, 1 - y - height, width, height];\n case 3:\n return [y, 1 - x - width, height, width];\n case 4:\n return [x, y - width * (pW / pH), height * (pH / pW), width * (pW / pH)];\n case 5:\n return [1 - y, x, width * (pW / pH), height * (pH / pW)];\n case 6:\n return [1 - x - height * (pH / pW), 1 - y, height * (pH / pW), width * (pW / pH)];\n case 7:\n return [y - width * (pW / pH), 1 - x - height * (pH / pW), width * (pW / pH), height * (pH / pW)];\n case 8:\n return [x - width, y - height, width, height];\n case 9:\n return [1 - y, x - width, height, width];\n case 10:\n return [1 - x, 1 - y, width, height];\n case 11:\n return [y - height, 1 - x, height, width];\n case 12:\n return [x - height * (pH / pW), y, height * (pH / pW), width * (pW / pH)];\n case 13:\n return [1 - y - width * (pW / pH), x - height * (pH / pW), width * (pW / pH), height * (pH / pW)];\n case 14:\n return [1 - x, 1 - y - width * (pW / pH), height * (pH / pW), width * (pW / pH)];\n case 15:\n return [y, 1 - x, width * (pW / pH), height * (pH / pW)];\n default:\n return [x, y, width, height];\n }\n }\n rotate() {\n if (!this.parent) {\n return;\n }\n this.parent.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties({\n bbox: this.#rotateBox()\n }, this.#drawOutlines.updateRotation((this.parentRotation - this.rotation + 360) % 360)));\n }\n onScaleChanging() {\n if (!this.parent) {\n return;\n }\n this.#updateBbox(this.#drawOutlines.updateParentDimensions(this.parentDimensions, this.parent.scale));\n }\n static onScaleChangingWhenDrawing() {}\n render() {\n if (this.div) {\n return this.div;\n }\n let baseX, baseY;\n if (this._isCopy) {\n baseX = this.x;\n baseY = this.y;\n }\n const div = super.render();\n div.classList.add("draw");\n const drawDiv = document.createElement("div");\n div.append(drawDiv);\n drawDiv.setAttribute("aria-hidden", "true");\n drawDiv.className = "internal";\n this.setDims();\n this._uiManager.addShouldRescale(this);\n this.disableEditing();\n if (this._isCopy) {\n this._moveAfterPaste(baseX, baseY);\n }\n return div;\n }\n static createDrawerInstance(_x, _y, _parentWidth, _parentHeight, _rotation) {\n unreachable("Not implemented");\n }\n static startDrawing(parent, uiManager, _isLTR, event) {\n const {\n target,\n offsetX: x,\n offsetY: y,\n pointerId,\n pointerType\n } = event;\n if (CurrentPointers.isInitializedAndDifferentPointerType(pointerType)) {\n return;\n }\n const {\n viewport: {\n rotation\n }\n } = parent;\n const {\n width: parentWidth,\n height: parentHeight\n } = target.getBoundingClientRect();\n const ac = DrawingEditor.#currentDrawingAC = new AbortController();\n const signal = parent.combinedSignal(ac);\n CurrentPointers.setPointer(pointerType, pointerId);\n window.addEventListener("pointerup", e => {\n if (CurrentPointers.isSamePointerIdOrRemove(e.pointerId)) {\n this._endDraw(e);\n }\n }, {\n signal\n });\n window.addEventListener("pointercancel", e => {\n if (CurrentPointers.isSamePointerIdOrRemove(e.pointerId)) {\n this._currentParent.endDrawingSession();\n }\n }, {\n signal\n });\n window.addEventListener("pointerdown", e => {\n if (!CurrentPointers.isSamePointerType(e.pointerType)) {\n return;\n }\n CurrentPointers.initializeAndAddPointerId(e.pointerId);\n if (DrawingEditor.#currentDraw.isCancellable()) {\n DrawingEditor.#currentDraw.removeLastElement();\n if (DrawingEditor.#currentDraw.isEmpty()) {\n this._currentParent.endDrawingSession(true);\n } else {\n this._endDraw(null);\n }\n }\n }, {\n capture: true,\n passive: false,\n signal\n });\n window.addEventListener("contextmenu", noContextMenu, {\n signal\n });\n target.addEventListener("pointermove", this._drawMove.bind(this), {\n signal\n });\n target.addEventListener("touchmove", e => {\n if (CurrentPointers.isSameTimeStamp(e.timeStamp)) {\n stopEvent(e);\n }\n }, {\n signal\n });\n parent.toggleDrawing();\n uiManager._editorUndoBar?.hide();\n if (DrawingEditor.#currentDraw) {\n parent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.startNew(x, y, parentWidth, parentHeight, rotation));\n return;\n }\n uiManager.updateUIForDefaultProperties(this);\n DrawingEditor.#currentDraw = this.createDrawerInstance(x, y, parentWidth, parentHeight, rotation);\n DrawingEditor.#currentDrawingOptions = this.getDefaultDrawingOptions();\n this._currentParent = parent;\n ({\n id: this._currentDrawId\n } = parent.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#currentDrawingOptions.toSVGProperties(), DrawingEditor.#currentDraw.defaultSVGProperties), true, false));\n }\n static _drawMove(event) {\n CurrentPointers.isSameTimeStamp(event.timeStamp);\n if (!DrawingEditor.#currentDraw) {\n return;\n }\n const {\n offsetX,\n offsetY,\n pointerId\n } = event;\n if (!CurrentPointers.isSamePointerId(pointerId)) {\n return;\n }\n if (CurrentPointers.isUsingMultiplePointers()) {\n this._endDraw(event);\n return;\n }\n this._currentParent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.add(offsetX, offsetY));\n CurrentPointers.setTimeStamp(event.timeStamp);\n stopEvent(event);\n }\n static _cleanup(all) {\n if (all) {\n this._currentDrawId = -1;\n this._currentParent = null;\n DrawingEditor.#currentDraw = null;\n DrawingEditor.#currentDrawingOptions = null;\n CurrentPointers.clearTimeStamp();\n }\n if (DrawingEditor.#currentDrawingAC) {\n DrawingEditor.#currentDrawingAC.abort();\n DrawingEditor.#currentDrawingAC = null;\n CurrentPointers.clearPointerIds();\n }\n }\n static _endDraw(event) {\n const parent = this._currentParent;\n if (!parent) {\n return;\n }\n parent.toggleDrawing(true);\n this._cleanup(false);\n if (event?.target === parent.div) {\n parent.drawLayer.updateProperties(this._currentDrawId, DrawingEditor.#currentDraw.end(event.offsetX, event.offsetY));\n }\n if (this.supportMultipleDrawings) {\n const draw = DrawingEditor.#currentDraw;\n const drawId = this._currentDrawId;\n const lastElement = draw.getLastElement();\n parent.addCommands({\n cmd: () => {\n parent.drawLayer.updateProperties(drawId, draw.setLastElement(lastElement));\n },\n undo: () => {\n parent.drawLayer.updateProperties(drawId, draw.removeLastElement());\n },\n mustExec: false,\n type: AnnotationEditorParamsType.DRAW_STEP\n });\n return;\n }\n this.endDrawing(false);\n }\n static endDrawing(isAborted) {\n const parent = this._currentParent;\n if (!parent) {\n return null;\n }\n parent.toggleDrawing(true);\n parent.cleanUndoStack(AnnotationEditorParamsType.DRAW_STEP);\n if (!DrawingEditor.#currentDraw.isEmpty()) {\n const {\n pageDimensions: [pageWidth, pageHeight],\n scale\n } = parent;\n const editor = parent.createAndAddNewEditor({\n offsetX: 0,\n offsetY: 0\n }, false, {\n drawId: this._currentDrawId,\n drawOutlines: DrawingEditor.#currentDraw.getOutlines(pageWidth * scale, pageHeight * scale, scale, this._INNER_MARGIN),\n drawingOptions: DrawingEditor.#currentDrawingOptions,\n mustBeCommitted: !isAborted\n });\n this._cleanup(true);\n return editor;\n }\n parent.drawLayer.remove(this._currentDrawId);\n this._cleanup(true);\n return null;\n }\n createDrawingOptions(_data) {}\n static deserializeDraw(_pageX, _pageY, _pageWidth, _pageHeight, _innerWidth, _data) {\n unreachable("Not implemented");\n }\n static async deserialize(data, parent, uiManager) {\n const {\n rawDims: {\n pageWidth,\n pageHeight,\n pageX,\n pageY\n }\n } = parent.viewport;\n const drawOutlines = this.deserializeDraw(pageX, pageY, pageWidth, pageHeight, this._INNER_MARGIN, data);\n const editor = await super.deserialize(data, parent, uiManager);\n editor.createDrawingOptions(data);\n editor.#createDrawOutlines({\n drawOutlines\n });\n editor.#addToDrawLayer();\n editor.onScaleChanging();\n editor.rotate();\n return editor;\n }\n serializeDraw(isForCopying) {\n const [pageX, pageY] = this.pageTranslation;\n const [pageWidth, pageHeight] = this.pageDimensions;\n return this.#drawOutlines.serialize([pageX, pageY, pageWidth, pageHeight], isForCopying);\n }\n renderAnnotationElement(annotation) {\n annotation.updateEdited({\n rect: this.getPDFRect()\n });\n return null;\n }\n static canCreateNewEmptyEditor() {\n return false;\n }\n}\n\n;// ./src/display/editor/drawers/inkdraw.js\n\n\n\n\n\n\n\n\n\nclass InkDrawOutliner {\n #last = new Float64Array(6);\n #line;\n #lines;\n #rotation;\n #thickness;\n #points;\n #lastSVGPath = "";\n #lastIndex = 0;\n #outlines = new InkDrawOutline();\n #parentWidth;\n #parentHeight;\n constructor(x, y, parentWidth, parentHeight, rotation, thickness) {\n this.#parentWidth = parentWidth;\n this.#parentHeight = parentHeight;\n this.#rotation = rotation;\n this.#thickness = thickness;\n [x, y] = this.#normalizePoint(x, y);\n const line = this.#line = [NaN, NaN, NaN, NaN, x, y];\n this.#points = [x, y];\n this.#lines = [{\n line,\n points: this.#points\n }];\n this.#last.set(line, 0);\n }\n updateProperty(name, value) {\n if (name === "stroke-width") {\n this.#thickness = value;\n }\n }\n #normalizePoint(x, y) {\n return Outline._normalizePoint(x, y, this.#parentWidth, this.#parentHeight, this.#rotation);\n }\n isEmpty() {\n return !this.#lines || this.#lines.length === 0;\n }\n isCancellable() {\n return this.#points.length <= 10;\n }\n add(x, y) {\n [x, y] = this.#normalizePoint(x, y);\n const [x1, y1, x2, y2] = this.#last.subarray(2, 6);\n const diffX = x - x2;\n const diffY = y - y2;\n const d = Math.hypot(this.#parentWidth * diffX, this.#parentHeight * diffY);\n if (d <= 2) {\n return null;\n }\n this.#points.push(x, y);\n if (isNaN(x1)) {\n this.#last.set([x2, y2, x, y], 2);\n this.#line.push(NaN, NaN, NaN, NaN, x, y);\n return {\n path: {\n d: this.toSVGPath()\n }\n };\n }\n if (isNaN(this.#last[0])) {\n this.#line.splice(6, 6);\n }\n this.#last.set([x1, y1, x2, y2, x, y], 0);\n this.#line.push(...Outline.createBezierPoints(x1, y1, x2, y2, x, y));\n return {\n path: {\n d: this.toSVGPath()\n }\n };\n }\n end(x, y) {\n const change = this.add(x, y);\n if (change) {\n return change;\n }\n if (this.#points.length === 2) {\n return {\n path: {\n d: this.toSVGPath()\n }\n };\n }\n return null;\n }\n startNew(x, y, parentWidth, parentHeight, rotation) {\n this.#parentWidth = parentWidth;\n this.#parentHeight = parentHeight;\n this.#rotation = rotation;\n [x, y] = this.#normalizePoint(x, y);\n const line = this.#line = [NaN, NaN, NaN, NaN, x, y];\n this.#points = [x, y];\n const last = this.#lines.at(-1);\n if (last) {\n last.line = new Float32Array(last.line);\n last.points = new Float32Array(last.points);\n }\n this.#lines.push({\n line,\n points: this.#points\n });\n this.#last.set(line, 0);\n this.#lastIndex = 0;\n this.toSVGPath();\n return null;\n }\n getLastElement() {\n return this.#lines.at(-1);\n }\n setLastElement(element) {\n if (!this.#lines) {\n return this.#outlines.setLastElement(element);\n }\n this.#lines.push(element);\n this.#line = element.line;\n this.#points = element.points;\n this.#lastIndex = 0;\n return {\n path: {\n d: this.toSVGPath()\n }\n };\n }\n removeLastElement() {\n if (!this.#lines) {\n return this.#outlines.removeLastElement();\n }\n this.#lines.pop();\n this.#lastSVGPath = "";\n for (let i = 0, ii = this.#lines.length; i < ii; i++) {\n const {\n line,\n points\n } = this.#lines[i];\n this.#line = line;\n this.#points = points;\n this.#lastIndex = 0;\n this.toSVGPath();\n }\n return {\n path: {\n d: this.#lastSVGPath\n }\n };\n }\n toSVGPath() {\n const firstX = Outline.svgRound(this.#line[4]);\n const firstY = Outline.svgRound(this.#line[5]);\n if (this.#points.length === 2) {\n this.#lastSVGPath = `${this.#lastSVGPath} M ${firstX} ${firstY} Z`;\n return this.#lastSVGPath;\n }\n if (this.#points.length <= 6) {\n const i = this.#lastSVGPath.lastIndexOf("M");\n this.#lastSVGPath = `${this.#lastSVGPath.slice(0, i)} M ${firstX} ${firstY}`;\n this.#lastIndex = 6;\n }\n if (this.#points.length === 4) {\n const secondX = Outline.svgRound(this.#line[10]);\n const secondY = Outline.svgRound(this.#line[11]);\n this.#lastSVGPath = `${this.#lastSVGPath} L ${secondX} ${secondY}`;\n this.#lastIndex = 12;\n return this.#lastSVGPath;\n }\n const buffer = [];\n if (this.#lastIndex === 0) {\n buffer.push(`M ${firstX} ${firstY}`);\n this.#lastIndex = 6;\n }\n for (let i = this.#lastIndex, ii = this.#line.length; i < ii; i += 6) {\n const [c1x, c1y, c2x, c2y, x, y] = this.#line.slice(i, i + 6).map(Outline.svgRound);\n buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`);\n }\n this.#lastSVGPath += buffer.join(" ");\n this.#lastIndex = this.#line.length;\n return this.#lastSVGPath;\n }\n getOutlines(parentWidth, parentHeight, scale, innerMargin) {\n const last = this.#lines.at(-1);\n last.line = new Float32Array(last.line);\n last.points = new Float32Array(last.points);\n this.#outlines.build(this.#lines, parentWidth, parentHeight, scale, this.#rotation, this.#thickness, innerMargin);\n this.#last = null;\n this.#line = null;\n this.#lines = null;\n this.#lastSVGPath = null;\n return this.#outlines;\n }\n get defaultSVGProperties() {\n return {\n root: {\n viewBox: "0 0 10000 10000"\n },\n rootClass: {\n draw: true\n },\n bbox: [0, 0, 1, 1]\n };\n }\n}\nclass InkDrawOutline extends Outline {\n #bbox;\n #currentRotation = 0;\n #innerMargin;\n #lines;\n #parentWidth;\n #parentHeight;\n #parentScale;\n #rotation;\n #thickness;\n build(lines, parentWidth, parentHeight, parentScale, rotation, thickness, innerMargin) {\n this.#parentWidth = parentWidth;\n this.#parentHeight = parentHeight;\n this.#parentScale = parentScale;\n this.#rotation = rotation;\n this.#thickness = thickness;\n this.#innerMargin = innerMargin ?? 0;\n this.#lines = lines;\n this.#computeBbox();\n }\n get thickness() {\n return this.#thickness;\n }\n setLastElement(element) {\n this.#lines.push(element);\n return {\n path: {\n d: this.toSVGPath()\n }\n };\n }\n removeLastElement() {\n this.#lines.pop();\n return {\n path: {\n d: this.toSVGPath()\n }\n };\n }\n toSVGPath() {\n const buffer = [];\n for (const {\n line\n } of this.#lines) {\n buffer.push(`M${Outline.svgRound(line[4])} ${Outline.svgRound(line[5])}`);\n if (line.length === 6) {\n buffer.push("Z");\n continue;\n }\n if (line.length === 12 && isNaN(line[6])) {\n buffer.push(`L${Outline.svgRound(line[10])} ${Outline.svgRound(line[11])}`);\n continue;\n }\n for (let i = 6, ii = line.length; i < ii; i += 6) {\n const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6).map(Outline.svgRound);\n buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`);\n }\n }\n return buffer.join("");\n }\n serialize([pageX, pageY, pageWidth, pageHeight], isForCopying) {\n const serializedLines = [];\n const serializedPoints = [];\n const [x, y, width, height] = this.#getBBoxWithNoMargin();\n let tx, ty, sx, sy, x1, y1, x2, y2, rescaleFn;\n switch (this.#rotation) {\n case 0:\n rescaleFn = Outline._rescale;\n tx = pageX;\n ty = pageY + pageHeight;\n sx = pageWidth;\n sy = -pageHeight;\n x1 = pageX + x * pageWidth;\n y1 = pageY + (1 - y - height) * pageHeight;\n x2 = pageX + (x + width) * pageWidth;\n y2 = pageY + (1 - y) * pageHeight;\n break;\n case 90:\n rescaleFn = Outline._rescaleAndSwap;\n tx = pageX;\n ty = pageY;\n sx = pageWidth;\n sy = pageHeight;\n x1 = pageX + y * pageWidth;\n y1 = pageY + x * pageHeight;\n x2 = pageX + (y + height) * pageWidth;\n y2 = pageY + (x + width) * pageHeight;\n break;\n case 180:\n rescaleFn = Outline._rescale;\n tx = pageX + pageWidth;\n ty = pageY;\n sx = -pageWidth;\n sy = pageHeight;\n x1 = pageX + (1 - x - width) * pageWidth;\n y1 = pageY + y * pageHeight;\n x2 = pageX + (1 - x) * pageWidth;\n y2 = pageY + (y + height) * pageHeight;\n break;\n case 270:\n rescaleFn = Outline._rescaleAndSwap;\n tx = pageX + pageWidth;\n ty = pageY + pageHeight;\n sx = -pageWidth;\n sy = -pageHeight;\n x1 = pageX + (1 - y - height) * pageWidth;\n y1 = pageY + (1 - x - width) * pageHeight;\n x2 = pageX + (1 - y) * pageWidth;\n y2 = pageY + (1 - x) * pageHeight;\n break;\n }\n for (const {\n line,\n points\n } of this.#lines) {\n serializedLines.push(rescaleFn(line, tx, ty, sx, sy, isForCopying ? new Array(line.length) : null));\n serializedPoints.push(rescaleFn(points, tx, ty, sx, sy, isForCopying ? new Array(points.length) : null));\n }\n return {\n lines: serializedLines,\n points: serializedPoints,\n rect: [x1, y1, x2, y2]\n };\n }\n static deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, {\n paths: {\n lines,\n points\n },\n rotation,\n thickness\n }) {\n const newLines = [];\n let tx, ty, sx, sy, rescaleFn;\n switch (rotation) {\n case 0:\n rescaleFn = Outline._rescale;\n tx = -pageX / pageWidth;\n ty = pageY / pageHeight + 1;\n sx = 1 / pageWidth;\n sy = -1 / pageHeight;\n break;\n case 90:\n rescaleFn = Outline._rescaleAndSwap;\n tx = -pageY / pageHeight;\n ty = -pageX / pageWidth;\n sx = 1 / pageHeight;\n sy = 1 / pageWidth;\n break;\n case 180:\n rescaleFn = Outline._rescale;\n tx = pageX / pageWidth + 1;\n ty = -pageY / pageHeight;\n sx = -1 / pageWidth;\n sy = 1 / pageHeight;\n break;\n case 270:\n rescaleFn = Outline._rescaleAndSwap;\n tx = pageY / pageHeight + 1;\n ty = pageX / pageWidth + 1;\n sx = -1 / pageHeight;\n sy = -1 / pageWidth;\n break;\n }\n if (!lines) {\n lines = [];\n for (const point of points) {\n const len = point.length;\n if (len === 2) {\n lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1]]));\n continue;\n }\n if (len === 4) {\n lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1], NaN, NaN, NaN, NaN, point[2], point[3]]));\n continue;\n }\n const line = new Float32Array(3 * (len - 2));\n lines.push(line);\n let [x1, y1, x2, y2] = point.subarray(0, 4);\n line.set([NaN, NaN, NaN, NaN, x1, y1], 0);\n for (let i = 4; i < len; i += 2) {\n const x = point[i];\n const y = point[i + 1];\n line.set(Outline.createBezierPoints(x1, y1, x2, y2, x, y), (i - 2) * 3);\n [x1, y1, x2, y2] = [x2, y2, x, y];\n }\n }\n }\n for (let i = 0, ii = lines.length; i < ii; i++) {\n newLines.push({\n line: rescaleFn(lines[i].map(x => x ?? NaN), tx, ty, sx, sy),\n points: rescaleFn(points[i].map(x => x ?? NaN), tx, ty, sx, sy)\n });\n }\n const outlines = new this.prototype.constructor();\n outlines.build(newLines, pageWidth, pageHeight, 1, rotation, thickness, innerMargin);\n return outlines;\n }\n #getMarginComponents(thickness = this.#thickness) {\n const margin = this.#innerMargin + thickness / 2 * this.#parentScale;\n return this.#rotation % 180 === 0 ? [margin / this.#parentWidth, margin / this.#parentHeight] : [margin / this.#parentHeight, margin / this.#parentWidth];\n }\n #getBBoxWithNoMargin() {\n const [x, y, width, height] = this.#bbox;\n const [marginX, marginY] = this.#getMarginComponents(0);\n return [x + marginX, y + marginY, width - 2 * marginX, height - 2 * marginY];\n }\n #computeBbox() {\n const bbox = this.#bbox = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);\n for (const {\n line\n } of this.#lines) {\n if (line.length <= 12) {\n for (let i = 4, ii = line.length; i < ii; i += 6) {\n Util.pointBoundingBox(line[i], line[i + 1], bbox);\n }\n continue;\n }\n let lastX = line[4],\n lastY = line[5];\n for (let i = 6, ii = line.length; i < ii; i += 6) {\n const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6);\n Util.bezierBoundingBox(lastX, lastY, c1x, c1y, c2x, c2y, x, y, bbox);\n lastX = x;\n lastY = y;\n }\n }\n const [marginX, marginY] = this.#getMarginComponents();\n bbox[0] = MathClamp(bbox[0] - marginX, 0, 1);\n bbox[1] = MathClamp(bbox[1] - marginY, 0, 1);\n bbox[2] = MathClamp(bbox[2] + marginX, 0, 1);\n bbox[3] = MathClamp(bbox[3] + marginY, 0, 1);\n bbox[2] -= bbox[0];\n bbox[3] -= bbox[1];\n }\n get box() {\n return this.#bbox;\n }\n updateProperty(name, value) {\n if (name === "stroke-width") {\n return this.#updateThickness(value);\n }\n return null;\n }\n #updateThickness(thickness) {\n const [oldMarginX, oldMarginY] = this.#getMarginComponents();\n this.#thickness = thickness;\n const [newMarginX, newMarginY] = this.#getMarginComponents();\n const [diffMarginX, diffMarginY] = [newMarginX - oldMarginX, newMarginY - oldMarginY];\n const bbox = this.#bbox;\n bbox[0] -= diffMarginX;\n bbox[1] -= diffMarginY;\n bbox[2] += 2 * diffMarginX;\n bbox[3] += 2 * diffMarginY;\n return bbox;\n }\n updateParentDimensions([width, height], scale) {\n const [oldMarginX, oldMarginY] = this.#getMarginComponents();\n this.#parentWidth = width;\n this.#parentHeight = height;\n this.#parentScale = scale;\n const [newMarginX, newMarginY] = this.#getMarginComponents();\n const diffMarginX = newMarginX - oldMarginX;\n const diffMarginY = newMarginY - oldMarginY;\n const bbox = this.#bbox;\n bbox[0] -= diffMarginX;\n bbox[1] -= diffMarginY;\n bbox[2] += 2 * diffMarginX;\n bbox[3] += 2 * diffMarginY;\n return bbox;\n }\n updateRotation(rotation) {\n this.#currentRotation = rotation;\n return {\n path: {\n transform: this.rotationTransform\n }\n };\n }\n get viewBox() {\n return this.#bbox.map(Outline.svgRound).join(" ");\n }\n get defaultProperties() {\n const [x, y] = this.#bbox;\n return {\n root: {\n viewBox: this.viewBox\n },\n path: {\n "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}`\n }\n };\n }\n get rotationTransform() {\n const [,, width, height] = this.#bbox;\n let a = 0,\n b = 0,\n c = 0,\n d = 0,\n e = 0,\n f = 0;\n switch (this.#currentRotation) {\n case 90:\n b = height / width;\n c = -width / height;\n e = width;\n break;\n case 180:\n a = -1;\n d = -1;\n e = width;\n f = height;\n break;\n case 270:\n b = -height / width;\n c = width / height;\n f = height;\n break;\n default:\n return "";\n }\n return `matrix(${a} ${b} ${c} ${d} ${Outline.svgRound(e)} ${Outline.svgRound(f)})`;\n }\n getPathResizingSVGProperties([newX, newY, newWidth, newHeight]) {\n const [marginX, marginY] = this.#getMarginComponents();\n const [x, y, width, height] = this.#bbox;\n if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) {\n const tx = newX + newWidth / 2 - (x + width / 2);\n const ty = newY + newHeight / 2 - (y + height / 2);\n return {\n path: {\n "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,\n transform: `${this.rotationTransform} translate(${tx} ${ty})`\n }\n };\n }\n const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX);\n const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY);\n const s2x = width / newWidth;\n const s2y = height / newHeight;\n return {\n path: {\n "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}`,\n transform: `${this.rotationTransform} scale(${s2x} ${s2y}) ` + `translate(${Outline.svgRound(marginX)} ${Outline.svgRound(marginY)}) scale(${s1x} ${s1y}) ` + `translate(${Outline.svgRound(-marginX)} ${Outline.svgRound(-marginY)})`\n }\n };\n }\n getPathResizedSVGProperties([newX, newY, newWidth, newHeight]) {\n const [marginX, marginY] = this.#getMarginComponents();\n const bbox = this.#bbox;\n const [x, y, width, height] = bbox;\n bbox[0] = newX;\n bbox[1] = newY;\n bbox[2] = newWidth;\n bbox[3] = newHeight;\n if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) {\n const tx = newX + newWidth / 2 - (x + width / 2);\n const ty = newY + newHeight / 2 - (y + height / 2);\n for (const {\n line,\n points\n } of this.#lines) {\n Outline._translate(line, tx, ty, line);\n Outline._translate(points, tx, ty, points);\n }\n return {\n root: {\n viewBox: this.viewBox\n },\n path: {\n "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,\n transform: this.rotationTransform || null,\n d: this.toSVGPath()\n }\n };\n }\n const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX);\n const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY);\n const tx = -s1x * (x + marginX) + newX + marginX;\n const ty = -s1y * (y + marginY) + newY + marginY;\n if (s1x !== 1 || s1y !== 1 || tx !== 0 || ty !== 0) {\n for (const {\n line,\n points\n } of this.#lines) {\n Outline._rescale(line, tx, ty, s1x, s1y, line);\n Outline._rescale(points, tx, ty, s1x, s1y, points);\n }\n }\n return {\n root: {\n viewBox: this.viewBox\n },\n path: {\n "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,\n transform: this.rotationTransform || null,\n d: this.toSVGPath()\n }\n };\n }\n getPathTranslatedSVGProperties([newX, newY], parentDimensions) {\n const [newParentWidth, newParentHeight] = parentDimensions;\n const bbox = this.#bbox;\n const tx = newX - bbox[0];\n const ty = newY - bbox[1];\n if (this.#parentWidth === newParentWidth && this.#parentHeight === newParentHeight) {\n for (const {\n line,\n points\n } of this.#lines) {\n Outline._translate(line, tx, ty, line);\n Outline._translate(points, tx, ty, points);\n }\n } else {\n const sx = this.#parentWidth / newParentWidth;\n const sy = this.#parentHeight / newParentHeight;\n this.#parentWidth = newParentWidth;\n this.#parentHeight = newParentHeight;\n for (const {\n line,\n points\n } of this.#lines) {\n Outline._rescale(line, tx, ty, sx, sy, line);\n Outline._rescale(points, tx, ty, sx, sy, points);\n }\n bbox[2] *= sx;\n bbox[3] *= sy;\n }\n bbox[0] = newX;\n bbox[1] = newY;\n return {\n root: {\n viewBox: this.viewBox\n },\n path: {\n d: this.toSVGPath(),\n "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`\n }\n };\n }\n get defaultSVGProperties() {\n const bbox = this.#bbox;\n return {\n root: {\n viewBox: this.viewBox\n },\n rootClass: {\n draw: true\n },\n path: {\n d: this.toSVGPath(),\n "transform-origin": `${Outline.svgRound(bbox[0])} ${Outline.svgRound(bbox[1])}`,\n transform: this.rotationTransform || null\n },\n bbox\n };\n }\n}\n\n;// ./src/display/editor/ink.js\n\n\n\n\n\n\n\n\n\n\nclass InkDrawingOptions extends DrawingOptions {\n constructor(viewerParameters) {\n super();\n this._viewParameters = viewerParameters;\n super.updateProperties({\n fill: "none",\n stroke: AnnotationEditor._defaultLineColor,\n "stroke-opacity": 1,\n "stroke-width": 1,\n "stroke-linecap": "round",\n "stroke-linejoin": "round",\n "stroke-miterlimit": 10\n });\n }\n updateSVGProperty(name, value) {\n if (name === "stroke-width") {\n value ??= this["stroke-width"];\n value *= this._viewParameters.realScale;\n }\n super.updateSVGProperty(name, value);\n }\n clone() {\n const clone = new InkDrawingOptions(this._viewParameters);\n clone.updateAll(this);\n return clone;\n }\n}\nclass InkEditor extends DrawingEditor {\n static _type = "ink";\n static _editorType = AnnotationEditorType.INK;\n static _defaultDrawingOptions = null;\n constructor(params) {\n super({\n ...params,\n name: "inkEditor"\n });\n this._willKeepAspectRatio = true;\n this.defaultL10nId = "pdfjs-editor-ink-editor";\n }\n static initialize(l10n, uiManager) {\n AnnotationEditor.initialize(l10n, uiManager);\n this._defaultDrawingOptions = new InkDrawingOptions(uiManager.viewParameters);\n }\n static getDefaultDrawingOptions(options) {\n const clone = this._defaultDrawingOptions.clone();\n clone.updateProperties(options);\n return clone;\n }\n static get supportMultipleDrawings() {\n return true;\n }\n static get typesMap() {\n return shadow(this, "typesMap", new Map([[AnnotationEditorParamsType.INK_THICKNESS, "stroke-width"], [AnnotationEditorParamsType.INK_COLOR, "stroke"], [AnnotationEditorParamsType.INK_OPACITY, "stroke-opacity"]]));\n }\n static createDrawerInstance(x, y, parentWidth, parentHeight, rotation) {\n return new InkDrawOutliner(x, y, parentWidth, parentHeight, rotation, this._defaultDrawingOptions["stroke-width"]);\n }\n static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) {\n return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);\n }\n static async deserialize(data, parent, uiManager) {\n let initialData = null;\n if (data instanceof InkAnnotationElement) {\n const {\n data: {\n inkLists,\n rect,\n rotation,\n id,\n color,\n opacity,\n borderStyle: {\n rawWidth: thickness\n },\n popupRef,\n richText,\n contentsObj,\n creationDate,\n modificationDate\n },\n parent: {\n page: {\n pageNumber\n }\n }\n } = data;\n initialData = data = {\n annotationType: AnnotationEditorType.INK,\n color: Array.from(color),\n thickness,\n opacity,\n paths: {\n points: inkLists\n },\n boxes: null,\n pageIndex: pageNumber - 1,\n rect: rect.slice(0),\n rotation,\n annotationElementId: id,\n id,\n deleted: false,\n popupRef,\n richText,\n comment: contentsObj?.str || null,\n creationDate,\n modificationDate\n };\n }\n const editor = await super.deserialize(data, parent, uiManager);\n editor._initialData = initialData;\n if (data.comment) {\n editor.setCommentData(data);\n }\n return editor;\n }\n get toolbarButtons() {\n this._colorPicker ||= new BasicColorPicker(this);\n return [["colorPicker", this._colorPicker]];\n }\n get colorType() {\n return AnnotationEditorParamsType.INK_COLOR;\n }\n get color() {\n return this._drawingOptions.stroke;\n }\n get opacity() {\n return this._drawingOptions["stroke-opacity"];\n }\n onScaleChanging() {\n if (!this.parent) {\n return;\n }\n super.onScaleChanging();\n const {\n _drawId,\n _drawingOptions,\n parent\n } = this;\n _drawingOptions.updateSVGProperty("stroke-width");\n parent.drawLayer.updateProperties(_drawId, _drawingOptions.toSVGProperties());\n }\n static onScaleChangingWhenDrawing() {\n const parent = this._currentParent;\n if (!parent) {\n return;\n }\n super.onScaleChangingWhenDrawing();\n this._defaultDrawingOptions.updateSVGProperty("stroke-width");\n parent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties());\n }\n createDrawingOptions({\n color,\n thickness,\n opacity\n }) {\n this._drawingOptions = InkEditor.getDefaultDrawingOptions({\n stroke: Util.makeHexColor(...color),\n "stroke-width": thickness,\n "stroke-opacity": opacity\n });\n }\n serialize(isForCopying = false) {\n if (this.isEmpty()) {\n return null;\n }\n if (this.deleted) {\n return this.serializeDeleted();\n }\n const {\n lines,\n points\n } = this.serializeDraw(isForCopying);\n const {\n _drawingOptions: {\n stroke,\n "stroke-opacity": opacity,\n "stroke-width": thickness\n }\n } = this;\n const serialized = Object.assign(super.serialize(isForCopying), {\n color: AnnotationEditor._colorManager.convert(stroke),\n opacity,\n thickness,\n paths: {\n lines,\n points\n }\n });\n this.addComment(serialized);\n if (isForCopying) {\n serialized.isCopy = true;\n return serialized;\n }\n if (this.annotationElementId && !this.#hasElementChanged(serialized)) {\n return null;\n }\n serialized.id = this.annotationElementId;\n return serialized;\n }\n #hasElementChanged(serialized) {\n const {\n color,\n thickness,\n opacity,\n pageIndex\n } = this._initialData;\n return this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized || serialized.color.some((c, i) => c !== color[i]) || serialized.thickness !== thickness || serialized.opacity !== opacity || serialized.pageIndex !== pageIndex;\n }\n renderAnnotationElement(annotation) {\n if (this.deleted) {\n annotation.hide();\n return null;\n }\n const {\n points,\n rect\n } = this.serializeDraw(false);\n annotation.updateEdited({\n rect,\n thickness: this._drawingOptions["stroke-width"],\n points,\n popup: this.comment\n });\n return null;\n }\n}\n\n;// ./src/display/editor/drawers/contour.js\n\nclass ContourDrawOutline extends InkDrawOutline {\n toSVGPath() {\n let path = super.toSVGPath();\n if (!path.endsWith("Z")) {\n path += "Z";\n }\n return path;\n }\n}\n\n// EXTERNAL MODULE: ./node_modules/core-js/modules/es.uint8-array.from-base64.js\nvar es_uint8_array_from_base64 = __webpack_require__(5213);\n;// ./src/display/editor/drawers/signaturedraw.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst BASE_HEADER_LENGTH = 8;\nconst POINTS_PROPERTIES_NUMBER = 3;\nclass SignatureExtractor {\n static #PARAMETERS = {\n maxDim: 512,\n sigmaSFactor: 0.02,\n sigmaR: 25,\n kernelSize: 16\n };\n static #neighborIndexToId(i0, j0, i, j) {\n i -= i0;\n j -= j0;\n if (i === 0) {\n return j > 0 ? 0 : 4;\n }\n if (i === 1) {\n return j + 6;\n }\n return 2 - j;\n }\n static #neighborIdToIndex = new Int32Array([0, 1, -1, 1, -1, 0, -1, -1, 0, -1, 1, -1, 1, 0, 1, 1]);\n static #clockwiseNonZero(buf, width, i0, j0, i, j, offset) {\n const id = this.#neighborIndexToId(i0, j0, i, j);\n for (let k = 0; k < 8; k++) {\n const kk = (-k + id - offset + 16) % 8;\n const shiftI = this.#neighborIdToIndex[2 * kk];\n const shiftJ = this.#neighborIdToIndex[2 * kk + 1];\n if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) {\n return kk;\n }\n }\n return -1;\n }\n static #counterClockwiseNonZero(buf, width, i0, j0, i, j, offset) {\n const id = this.#neighborIndexToId(i0, j0, i, j);\n for (let k = 0; k < 8; k++) {\n const kk = (k + id + offset + 16) % 8;\n const shiftI = this.#neighborIdToIndex[2 * kk];\n const shiftJ = this.#neighborIdToIndex[2 * kk + 1];\n if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) {\n return kk;\n }\n }\n return -1;\n }\n static #findContours(buf, width, height, threshold) {\n const N = buf.length;\n const types = new Int32Array(N);\n for (let i = 0; i < N; i++) {\n types[i] = buf[i] <= threshold ? 1 : 0;\n }\n for (let i = 1; i < height - 1; i++) {\n types[i * width] = types[i * width + width - 1] = 0;\n }\n for (let i = 0; i < width; i++) {\n types[i] = types[width * height - 1 - i] = 0;\n }\n let nbd = 1;\n let lnbd;\n const contours = [];\n for (let i = 1; i < height - 1; i++) {\n lnbd = 1;\n for (let j = 1; j < width - 1; j++) {\n const ij = i * width + j;\n const pix = types[ij];\n if (pix === 0) {\n continue;\n }\n let i2 = i;\n let j2 = j;\n if (pix === 1 && types[ij - 1] === 0) {\n nbd += 1;\n j2 -= 1;\n } else if (pix >= 1 && types[ij + 1] === 0) {\n nbd += 1;\n j2 += 1;\n if (pix > 1) {\n lnbd = pix;\n }\n } else {\n if (pix !== 1) {\n lnbd = Math.abs(pix);\n }\n continue;\n }\n const points = [j, i];\n const isHole = j2 === j + 1;\n const contour = {\n isHole,\n points,\n id: nbd,\n parent: 0\n };\n contours.push(contour);\n let contour0;\n for (const c of contours) {\n if (c.id === lnbd) {\n contour0 = c;\n break;\n }\n }\n if (!contour0) {\n contour.parent = isHole ? lnbd : 0;\n } else if (contour0.isHole) {\n contour.parent = isHole ? contour0.parent : lnbd;\n } else {\n contour.parent = isHole ? lnbd : contour0.parent;\n }\n const k = this.#clockwiseNonZero(types, width, i, j, i2, j2, 0);\n if (k === -1) {\n types[ij] = -nbd;\n if (types[ij] !== 1) {\n lnbd = Math.abs(types[ij]);\n }\n continue;\n }\n let shiftI = this.#neighborIdToIndex[2 * k];\n let shiftJ = this.#neighborIdToIndex[2 * k + 1];\n const i1 = i + shiftI;\n const j1 = j + shiftJ;\n i2 = i1;\n j2 = j1;\n let i3 = i;\n let j3 = j;\n while (true) {\n const kk = this.#counterClockwiseNonZero(types, width, i3, j3, i2, j2, 1);\n shiftI = this.#neighborIdToIndex[2 * kk];\n shiftJ = this.#neighborIdToIndex[2 * kk + 1];\n const i4 = i3 + shiftI;\n const j4 = j3 + shiftJ;\n points.push(j4, i4);\n const ij3 = i3 * width + j3;\n if (types[ij3 + 1] === 0) {\n types[ij3] = -nbd;\n } else if (types[ij3] === 1) {\n types[ij3] = nbd;\n }\n if (i4 === i && j4 === j && i3 === i1 && j3 === j1) {\n if (types[ij] !== 1) {\n lnbd = Math.abs(types[ij]);\n }\n break;\n } else {\n i2 = i3;\n j2 = j3;\n i3 = i4;\n j3 = j4;\n }\n }\n }\n }\n return contours;\n }\n static #douglasPeuckerHelper(points, start, end, output) {\n if (end - start <= 4) {\n for (let i = start; i < end - 2; i += 2) {\n output.push(points[i], points[i + 1]);\n }\n return;\n }\n const ax = points[start];\n const ay = points[start + 1];\n const abx = points[end - 4] - ax;\n const aby = points[end - 3] - ay;\n const dist = Math.hypot(abx, aby);\n const nabx = abx / dist;\n const naby = aby / dist;\n const aa = nabx * ay - naby * ax;\n const m = aby / abx;\n const invS = 1 / dist;\n const phi = Math.atan(m);\n const cosPhi = Math.cos(phi);\n const sinPhi = Math.sin(phi);\n const tmax = invS * (Math.abs(cosPhi) + Math.abs(sinPhi));\n const poly = invS * (1 - tmax + tmax ** 2);\n const partialPhi = Math.max(Math.atan(Math.abs(sinPhi + cosPhi) * poly), Math.atan(Math.abs(sinPhi - cosPhi) * poly));\n let dmax = 0;\n let index = start;\n for (let i = start + 2; i < end - 2; i += 2) {\n const d = Math.abs(aa - nabx * points[i + 1] + naby * points[i]);\n if (d > dmax) {\n index = i;\n dmax = d;\n }\n }\n if (dmax > (dist * partialPhi) ** 2) {\n this.#douglasPeuckerHelper(points, start, index + 2, output);\n this.#douglasPeuckerHelper(points, index, end, output);\n } else {\n output.push(ax, ay);\n }\n }\n static #douglasPeucker(points) {\n const output = [];\n const len = points.length;\n this.#douglasPeuckerHelper(points, 0, len, output);\n output.push(points[len - 2], points[len - 1]);\n return output.length <= 4 ? null : output;\n }\n static #bilateralFilter(buf, width, height, sigmaS, sigmaR, kernelSize) {\n const kernel = new Float32Array(kernelSize ** 2);\n const sigmaS2 = -2 * sigmaS ** 2;\n const halfSize = kernelSize >> 1;\n for (let i = 0; i < kernelSize; i++) {\n const x = (i - halfSize) ** 2;\n for (let j = 0; j < kernelSize; j++) {\n kernel[i * kernelSize + j] = Math.exp((x + (j - halfSize) ** 2) / sigmaS2);\n }\n }\n const rangeValues = new Float32Array(256);\n const sigmaR2 = -2 * sigmaR ** 2;\n for (let i = 0; i < 256; i++) {\n rangeValues[i] = Math.exp(i ** 2 / sigmaR2);\n }\n const N = buf.length;\n const out = new Uint8Array(N);\n const histogram = new Uint32Array(256);\n for (let i = 0; i < height; i++) {\n for (let j = 0; j < width; j++) {\n const ij = i * width + j;\n const center = buf[ij];\n let sum = 0;\n let norm = 0;\n for (let k = 0; k < kernelSize; k++) {\n const y = i + k - halfSize;\n if (y < 0 || y >= height) {\n continue;\n }\n for (let l = 0; l < kernelSize; l++) {\n const x = j + l - halfSize;\n if (x < 0 || x >= width) {\n continue;\n }\n const neighbour = buf[y * width + x];\n const w = kernel[k * kernelSize + l] * rangeValues[Math.abs(neighbour - center)];\n sum += neighbour * w;\n norm += w;\n }\n }\n const pix = out[ij] = Math.round(sum / norm);\n histogram[pix]++;\n }\n }\n return [out, histogram];\n }\n static #getHistogram(buf) {\n const histogram = new Uint32Array(256);\n for (const g of buf) {\n histogram[g]++;\n }\n return histogram;\n }\n static #toUint8(buf) {\n const N = buf.length;\n const out = new Uint8ClampedArray(N >> 2);\n let max = -Infinity;\n let min = Infinity;\n for (let i = 0, ii = out.length; i < ii; i++) {\n const pix = out[i] = buf[i << 2];\n max = Math.max(max, pix);\n min = Math.min(min, pix);\n }\n const ratio = 255 / (max - min);\n for (let i = 0, ii = out.length; i < ii; i++) {\n out[i] = (out[i] - min) * ratio;\n }\n return out;\n }\n static #guessThreshold(histogram) {\n let i;\n let M = -Infinity;\n let L = -Infinity;\n const min = histogram.findIndex(v => v !== 0);\n let pos = min;\n let spos = min;\n for (i = min; i < 256; i++) {\n const v = histogram[i];\n if (v > M) {\n if (i - pos > L) {\n L = i - pos;\n spos = i - 1;\n }\n M = v;\n pos = i;\n }\n }\n for (i = spos - 1; i >= 0; i--) {\n if (histogram[i] > histogram[i + 1]) {\n break;\n }\n }\n return i;\n }\n static #getGrayPixels(bitmap) {\n const originalBitmap = bitmap;\n const {\n width,\n height\n } = bitmap;\n const {\n maxDim\n } = this.#PARAMETERS;\n let newWidth = width;\n let newHeight = height;\n if (width > maxDim || height > maxDim) {\n let prevWidth = width;\n let prevHeight = height;\n let steps = Math.log2(Math.max(width, height) / maxDim);\n const isteps = Math.floor(steps);\n steps = steps === isteps ? isteps - 1 : isteps;\n for (let i = 0; i < steps; i++) {\n newWidth = Math.ceil(prevWidth / 2);\n newHeight = Math.ceil(prevHeight / 2);\n const offscreen = new OffscreenCanvas(newWidth, newHeight);\n const ctx = offscreen.getContext("2d");\n ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);\n prevWidth = newWidth;\n prevHeight = newHeight;\n if (bitmap !== originalBitmap) {\n bitmap.close();\n }\n bitmap = offscreen.transferToImageBitmap();\n }\n const ratio = Math.min(maxDim / newWidth, maxDim / newHeight);\n newWidth = Math.round(newWidth * ratio);\n newHeight = Math.round(newHeight * ratio);\n }\n const offscreen = new OffscreenCanvas(newWidth, newHeight);\n const ctx = offscreen.getContext("2d", {\n willReadFrequently: true\n });\n ctx.fillStyle = "white";\n ctx.fillRect(0, 0, newWidth, newHeight);\n ctx.filter = "grayscale(1)";\n ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, newWidth, newHeight);\n const grayImage = ctx.getImageData(0, 0, newWidth, newHeight).data;\n const uint8Buf = this.#toUint8(grayImage);\n return [uint8Buf, newWidth, newHeight];\n }\n static extractContoursFromText(text, {\n fontFamily,\n fontStyle,\n fontWeight\n }, pageWidth, pageHeight, rotation, innerMargin) {\n let canvas = new OffscreenCanvas(1, 1);\n let ctx = canvas.getContext("2d", {\n alpha: false\n });\n const fontSize = 200;\n const font = ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;\n const {\n actualBoundingBoxLeft,\n actualBoundingBoxRight,\n actualBoundingBoxAscent,\n actualBoundingBoxDescent,\n fontBoundingBoxAscent,\n fontBoundingBoxDescent,\n width\n } = ctx.measureText(text);\n const SCALE = 1.5;\n const canvasWidth = Math.ceil(Math.max(Math.abs(actualBoundingBoxLeft) + Math.abs(actualBoundingBoxRight) || 0, width) * SCALE);\n const canvasHeight = Math.ceil(Math.max(Math.abs(actualBoundingBoxAscent) + Math.abs(actualBoundingBoxDescent) || fontSize, Math.abs(fontBoundingBoxAscent) + Math.abs(fontBoundingBoxDescent) || fontSize) * SCALE);\n canvas = new OffscreenCanvas(canvasWidth, canvasHeight);\n ctx = canvas.getContext("2d", {\n alpha: true,\n willReadFrequently: true\n });\n ctx.font = font;\n ctx.filter = "grayscale(1)";\n ctx.fillStyle = "white";\n ctx.fillRect(0, 0, canvasWidth, canvasHeight);\n ctx.fillStyle = "black";\n ctx.fillText(text, canvasWidth * (SCALE - 1) / 2, canvasHeight * (3 - SCALE) / 2);\n const uint8Buf = this.#toUint8(ctx.getImageData(0, 0, canvasWidth, canvasHeight).data);\n const histogram = this.#getHistogram(uint8Buf);\n const threshold = this.#guessThreshold(histogram);\n const contourList = this.#findContours(uint8Buf, canvasWidth, canvasHeight, threshold);\n return this.processDrawnLines({\n lines: {\n curves: contourList,\n width: canvasWidth,\n height: canvasHeight\n },\n pageWidth,\n pageHeight,\n rotation,\n innerMargin,\n mustSmooth: true,\n areContours: true\n });\n }\n static process(bitmap, pageWidth, pageHeight, rotation, innerMargin) {\n const [uint8Buf, width, height] = this.#getGrayPixels(bitmap);\n const [buffer, histogram] = this.#bilateralFilter(uint8Buf, width, height, Math.hypot(width, height) * this.#PARAMETERS.sigmaSFactor, this.#PARAMETERS.sigmaR, this.#PARAMETERS.kernelSize);\n const threshold = this.#guessThreshold(histogram);\n const contourList = this.#findContours(buffer, width, height, threshold);\n return this.processDrawnLines({\n lines: {\n curves: contourList,\n width,\n height\n },\n pageWidth,\n pageHeight,\n rotation,\n innerMargin,\n mustSmooth: true,\n areContours: true\n });\n }\n static processDrawnLines({\n lines,\n pageWidth,\n pageHeight,\n rotation,\n innerMargin,\n mustSmooth,\n areContours\n }) {\n if (rotation % 180 !== 0) {\n [pageWidth, pageHeight] = [pageHeight, pageWidth];\n }\n const {\n curves,\n width,\n height\n } = lines;\n const thickness = lines.thickness ?? 0;\n const linesAndPoints = [];\n const ratio = Math.min(pageWidth / width, pageHeight / height);\n const xScale = ratio / pageWidth;\n const yScale = ratio / pageHeight;\n const newCurves = [];\n for (const {\n points\n } of curves) {\n const reducedPoints = mustSmooth ? this.#douglasPeucker(points) : points;\n if (!reducedPoints) {\n continue;\n }\n newCurves.push(reducedPoints);\n const len = reducedPoints.length;\n const newPoints = new Float32Array(len);\n const line = new Float32Array(3 * (len === 2 ? 2 : len - 2));\n linesAndPoints.push({\n line,\n points: newPoints\n });\n if (len === 2) {\n newPoints[0] = reducedPoints[0] * xScale;\n newPoints[1] = reducedPoints[1] * yScale;\n line.set([NaN, NaN, NaN, NaN, newPoints[0], newPoints[1]], 0);\n continue;\n }\n let [x1, y1, x2, y2] = reducedPoints;\n x1 *= xScale;\n y1 *= yScale;\n x2 *= xScale;\n y2 *= yScale;\n newPoints.set([x1, y1, x2, y2], 0);\n line.set([NaN, NaN, NaN, NaN, x1, y1], 0);\n for (let i = 4; i < len; i += 2) {\n const x = newPoints[i] = reducedPoints[i] * xScale;\n const y = newPoints[i + 1] = reducedPoints[i + 1] * yScale;\n line.set(Outline.createBezierPoints(x1, y1, x2, y2, x, y), (i - 2) * 3);\n [x1, y1, x2, y2] = [x2, y2, x, y];\n }\n }\n if (linesAndPoints.length === 0) {\n return null;\n }\n const outline = areContours ? new ContourDrawOutline() : new InkDrawOutline();\n outline.build(linesAndPoints, pageWidth, pageHeight, 1, rotation, areContours ? 0 : thickness, innerMargin);\n return {\n outline,\n newCurves,\n areContours,\n thickness,\n width,\n height\n };\n }\n static async compressSignature({\n outlines,\n areContours,\n thickness,\n width,\n height\n }) {\n let minDiff = Infinity;\n let maxDiff = -Infinity;\n let outlinesLength = 0;\n for (const points of outlines) {\n outlinesLength += points.length;\n for (let i = 2, ii = points.length; i < ii; i++) {\n const dx = points[i] - points[i - 2];\n minDiff = Math.min(minDiff, dx);\n maxDiff = Math.max(maxDiff, dx);\n }\n }\n let bufferType;\n if (minDiff >= -128 && maxDiff <= 127) {\n bufferType = Int8Array;\n } else if (minDiff >= -32768 && maxDiff <= 32767) {\n bufferType = Int16Array;\n } else {\n bufferType = Int32Array;\n }\n const len = outlines.length;\n const headerLength = BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * len;\n const header = new Uint32Array(headerLength);\n let offset = 0;\n header[offset++] = headerLength * Uint32Array.BYTES_PER_ELEMENT + (outlinesLength - 2 * len) * bufferType.BYTES_PER_ELEMENT;\n header[offset++] = 0;\n header[offset++] = width;\n header[offset++] = height;\n header[offset++] = areContours ? 0 : 1;\n header[offset++] = Math.max(0, Math.floor(thickness ?? 0));\n header[offset++] = len;\n header[offset++] = bufferType.BYTES_PER_ELEMENT;\n for (const points of outlines) {\n header[offset++] = points.length - 2;\n header[offset++] = points[0];\n header[offset++] = points[1];\n }\n const cs = new CompressionStream("deflate-raw");\n const writer = cs.writable.getWriter();\n await writer.ready;\n writer.write(header);\n const BufferCtor = bufferType.prototype.constructor;\n for (const points of outlines) {\n const diffs = new BufferCtor(points.length - 2);\n for (let i = 2, ii = points.length; i < ii; i++) {\n diffs[i - 2] = points[i] - points[i - 2];\n }\n writer.write(diffs);\n }\n writer.close();\n const buf = await new Response(cs.readable).arrayBuffer();\n const bytes = new Uint8Array(buf);\n return bytes.toBase64();\n }\n static async decompressSignature(signatureData) {\n try {\n const bytes = Uint8Array.fromBase64(signatureData);\n const {\n readable,\n writable\n } = new DecompressionStream("deflate-raw");\n const writer = writable.getWriter();\n await writer.ready;\n writer.write(bytes).then(async () => {\n await writer.ready;\n await writer.close();\n }).catch(() => {});\n let data = null;\n let offset = 0;\n for await (const chunk of readable) {\n data ||= new Uint8Array(new Uint32Array(chunk.buffer, 0, 4)[0]);\n data.set(chunk, offset);\n offset += chunk.length;\n }\n const header = new Uint32Array(data.buffer, 0, data.length >> 2);\n const version = header[1];\n if (version !== 0) {\n throw new Error(`Invalid version: ${version}`);\n }\n const width = header[2];\n const height = header[3];\n const areContours = header[4] === 0;\n const thickness = header[5];\n const numberOfDrawings = header[6];\n const bufferType = header[7];\n const outlines = [];\n const diffsOffset = (BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * numberOfDrawings) * Uint32Array.BYTES_PER_ELEMENT;\n let diffs;\n switch (bufferType) {\n case Int8Array.BYTES_PER_ELEMENT:\n diffs = new Int8Array(data.buffer, diffsOffset);\n break;\n case Int16Array.BYTES_PER_ELEMENT:\n diffs = new Int16Array(data.buffer, diffsOffset);\n break;\n case Int32Array.BYTES_PER_ELEMENT:\n diffs = new Int32Array(data.buffer, diffsOffset);\n break;\n }\n offset = 0;\n for (let i = 0; i < numberOfDrawings; i++) {\n const len = header[POINTS_PROPERTIES_NUMBER * i + BASE_HEADER_LENGTH];\n const points = new Float32Array(len + 2);\n outlines.push(points);\n for (let j = 0; j < POINTS_PROPERTIES_NUMBER - 1; j++) {\n points[j] = header[POINTS_PROPERTIES_NUMBER * i + BASE_HEADER_LENGTH + j + 1];\n }\n for (let j = 0; j < len; j++) {\n points[j + 2] = points[j] + diffs[offset++];\n }\n }\n return {\n areContours,\n thickness,\n outlines,\n width,\n height\n };\n } catch (e) {\n warn(`decompressSignature: ${e}`);\n return null;\n }\n }\n}\n\n;// ./src/display/editor/signature.js\n\n\n\n\n\n\n\n\n\n\n\n\nclass SignatureOptions extends DrawingOptions {\n constructor() {\n super();\n super.updateProperties({\n fill: AnnotationEditor._defaultLineColor,\n "stroke-width": 0\n });\n }\n clone() {\n const clone = new SignatureOptions();\n clone.updateAll(this);\n return clone;\n }\n}\nclass DrawnSignatureOptions extends InkDrawingOptions {\n constructor(viewerParameters) {\n super(viewerParameters);\n super.updateProperties({\n stroke: AnnotationEditor._defaultLineColor,\n "stroke-width": 1\n });\n }\n clone() {\n const clone = new DrawnSignatureOptions(this._viewParameters);\n clone.updateAll(this);\n return clone;\n }\n}\nclass SignatureEditor extends DrawingEditor {\n #isExtracted = false;\n #description = null;\n #signatureData = null;\n #signatureUUID = null;\n static _type = "signature";\n static _editorType = AnnotationEditorType.SIGNATURE;\n static _defaultDrawingOptions = null;\n constructor(params) {\n super({\n ...params,\n mustBeCommitted: true,\n name: "signatureEditor"\n });\n this._willKeepAspectRatio = true;\n this.#signatureData = params.signatureData || null;\n this.#description = null;\n this.defaultL10nId = "pdfjs-editor-signature-editor1";\n }\n static initialize(l10n, uiManager) {\n AnnotationEditor.initialize(l10n, uiManager);\n this._defaultDrawingOptions = new SignatureOptions();\n this._defaultDrawnSignatureOptions = new DrawnSignatureOptions(uiManager.viewParameters);\n }\n static getDefaultDrawingOptions(options) {\n const clone = this._defaultDrawingOptions.clone();\n clone.updateProperties(options);\n return clone;\n }\n static get supportMultipleDrawings() {\n return false;\n }\n static get typesMap() {\n return shadow(this, "typesMap", new Map());\n }\n static get isDrawer() {\n return false;\n }\n get telemetryFinalData() {\n return {\n type: "signature",\n hasDescription: !!this.#description\n };\n }\n static computeTelemetryFinalData(data) {\n const hasDescriptionStats = data.get("hasDescription");\n return {\n hasAltText: hasDescriptionStats.get(true) ?? 0,\n hasNoAltText: hasDescriptionStats.get(false) ?? 0\n };\n }\n get isResizable() {\n return true;\n }\n onScaleChanging() {\n if (this._drawId === null) {\n return;\n }\n super.onScaleChanging();\n }\n render() {\n if (this.div) {\n return this.div;\n }\n let baseX, baseY;\n const {\n _isCopy\n } = this;\n if (_isCopy) {\n this._isCopy = false;\n baseX = this.x;\n baseY = this.y;\n }\n super.render();\n if (this._drawId === null) {\n if (this.#signatureData) {\n const {\n lines,\n mustSmooth,\n areContours,\n description,\n uuid,\n heightInPage\n } = this.#signatureData;\n const {\n rawDims: {\n pageWidth,\n pageHeight\n },\n rotation\n } = this.parent.viewport;\n const outline = SignatureExtractor.processDrawnLines({\n lines,\n pageWidth,\n pageHeight,\n rotation,\n innerMargin: SignatureEditor._INNER_MARGIN,\n mustSmooth,\n areContours\n });\n this.addSignature(outline, heightInPage, description, uuid);\n } else {\n this.div.setAttribute("data-l10n-args", JSON.stringify({\n description: ""\n }));\n this.div.hidden = true;\n this._uiManager.getSignature(this);\n }\n } else {\n this.div.setAttribute("data-l10n-args", JSON.stringify({\n description: this.#description || ""\n }));\n }\n if (_isCopy) {\n this._isCopy = true;\n this._moveAfterPaste(baseX, baseY);\n }\n return this.div;\n }\n setUuid(uuid) {\n this.#signatureUUID = uuid;\n this.addEditToolbar();\n }\n getUuid() {\n return this.#signatureUUID;\n }\n get description() {\n return this.#description;\n }\n set description(description) {\n this.#description = description;\n if (!this.div) {\n return;\n }\n this.div.setAttribute("data-l10n-args", JSON.stringify({\n description\n }));\n super.addEditToolbar().then(toolbar => {\n toolbar?.updateEditSignatureButton(description);\n });\n }\n getSignaturePreview() {\n const {\n newCurves,\n areContours,\n thickness,\n width,\n height\n } = this.#signatureData;\n const maxDim = Math.max(width, height);\n const outlineData = SignatureExtractor.processDrawnLines({\n lines: {\n curves: newCurves.map(points => ({\n points\n })),\n thickness,\n width,\n height\n },\n pageWidth: maxDim,\n pageHeight: maxDim,\n rotation: 0,\n innerMargin: 0,\n mustSmooth: false,\n areContours\n });\n return {\n areContours,\n outline: outlineData.outline\n };\n }\n get toolbarButtons() {\n if (this._uiManager.signatureManager) {\n return [["editSignature", this._uiManager.signatureManager]];\n }\n return super.toolbarButtons;\n }\n addSignature(data, heightInPage, description, uuid) {\n const {\n x: savedX,\n y: savedY\n } = this;\n const {\n outline\n } = this.#signatureData = data;\n this.#isExtracted = outline instanceof ContourDrawOutline;\n this.description = description;\n let drawingOptions;\n if (this.#isExtracted) {\n drawingOptions = SignatureEditor.getDefaultDrawingOptions();\n } else {\n drawingOptions = SignatureEditor._defaultDrawnSignatureOptions.clone();\n drawingOptions.updateProperties({\n "stroke-width": outline.thickness\n });\n }\n this._addOutlines({\n drawOutlines: outline,\n drawingOptions\n });\n const [, pageHeight] = this.pageDimensions;\n let newHeight = heightInPage / pageHeight;\n newHeight = newHeight >= 1 ? 0.5 : newHeight;\n this.width *= newHeight / this.height;\n if (this.width >= 1) {\n newHeight *= 0.9 / this.width;\n this.width = 0.9;\n }\n this.height = newHeight;\n this.setDims();\n this.x = savedX;\n this.y = savedY;\n this.center();\n this._onResized();\n this.onScaleChanging();\n this.rotate();\n this._uiManager.addToAnnotationStorage(this);\n this.setUuid(uuid);\n this._reportTelemetry({\n action: "pdfjs.signature.inserted",\n data: {\n hasBeenSaved: !!uuid,\n hasDescription: !!description\n }\n });\n this.div.hidden = false;\n }\n getFromImage(bitmap) {\n const {\n rawDims: {\n pageWidth,\n pageHeight\n },\n rotation\n } = this.parent.viewport;\n return SignatureExtractor.process(bitmap, pageWidth, pageHeight, rotation, SignatureEditor._INNER_MARGIN);\n }\n getFromText(text, fontInfo) {\n const {\n rawDims: {\n pageWidth,\n pageHeight\n },\n rotation\n } = this.parent.viewport;\n return SignatureExtractor.extractContoursFromText(text, fontInfo, pageWidth, pageHeight, rotation, SignatureEditor._INNER_MARGIN);\n }\n getDrawnSignature(curves) {\n const {\n rawDims: {\n pageWidth,\n pageHeight\n },\n rotation\n } = this.parent.viewport;\n return SignatureExtractor.processDrawnLines({\n lines: curves,\n pageWidth,\n pageHeight,\n rotation,\n innerMargin: SignatureEditor._INNER_MARGIN,\n mustSmooth: false,\n areContours: false\n });\n }\n createDrawingOptions({\n areContours,\n thickness\n }) {\n if (areContours) {\n this._drawingOptions = SignatureEditor.getDefaultDrawingOptions();\n } else {\n this._drawingOptions = SignatureEditor._defaultDrawnSignatureOptions.clone();\n this._drawingOptions.updateProperties({\n "stroke-width": thickness\n });\n }\n }\n serialize(isForCopying = false) {\n if (this.isEmpty()) {\n return null;\n }\n const {\n lines,\n points\n } = this.serializeDraw(isForCopying);\n const {\n _drawingOptions: {\n "stroke-width": thickness\n }\n } = this;\n const serialized = Object.assign(super.serialize(isForCopying), {\n isSignature: true,\n areContours: this.#isExtracted,\n color: [0, 0, 0],\n thickness: this.#isExtracted ? 0 : thickness\n });\n this.addComment(serialized);\n if (isForCopying) {\n serialized.paths = {\n lines,\n points\n };\n serialized.uuid = this.#signatureUUID;\n serialized.isCopy = true;\n } else {\n serialized.lines = lines;\n }\n if (this.#description) {\n serialized.accessibilityData = {\n type: "Figure",\n alt: this.#description\n };\n }\n return serialized;\n }\n static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) {\n if (data.areContours) {\n return ContourDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);\n }\n return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);\n }\n static async deserialize(data, parent, uiManager) {\n const editor = await super.deserialize(data, parent, uiManager);\n editor.#isExtracted = data.areContours;\n editor.description = data.accessibilityData?.alt || "";\n editor.#signatureUUID = data.uuid;\n return editor;\n }\n}\n\n;// ./src/display/editor/stamp.js\n\n\n\n\n\n\n\n\n\nclass StampEditor extends AnnotationEditor {\n #bitmap = null;\n #bitmapId = null;\n #bitmapPromise = null;\n #bitmapUrl = null;\n #bitmapFile = null;\n #bitmapFileName = "";\n #canvas = null;\n #missingCanvas = false;\n #resizeTimeoutId = null;\n #isSvg = false;\n #hasBeenAddedInUndoStack = false;\n static _type = "stamp";\n static _editorType = AnnotationEditorType.STAMP;\n constructor(params) {\n super({\n ...params,\n name: "stampEditor"\n });\n this.#bitmapUrl = params.bitmapUrl;\n this.#bitmapFile = params.bitmapFile;\n this.defaultL10nId = "pdfjs-editor-stamp-editor";\n }\n static initialize(l10n, uiManager) {\n AnnotationEditor.initialize(l10n, uiManager);\n }\n static isHandlingMimeForPasting(mime) {\n return SupportedImageMimeTypes.includes(mime);\n }\n static paste(item, parent) {\n parent.pasteEditor({\n mode: AnnotationEditorType.STAMP\n }, {\n bitmapFile: item.getAsFile()\n });\n }\n altTextFinish() {\n if (this._uiManager.useNewAltTextFlow) {\n this.div.hidden = false;\n }\n super.altTextFinish();\n }\n get telemetryFinalData() {\n return {\n type: "stamp",\n hasAltText: !!this.altTextData?.altText\n };\n }\n static computeTelemetryFinalData(data) {\n const hasAltTextStats = data.get("hasAltText");\n return {\n hasAltText: hasAltTextStats.get(true) ?? 0,\n hasNoAltText: hasAltTextStats.get(false) ?? 0\n };\n }\n #getBitmapFetched(data, fromId = false) {\n if (!data) {\n this.remove();\n return;\n }\n this.#bitmap = data.bitmap;\n if (!fromId) {\n this.#bitmapId = data.id;\n this.#isSvg = data.isSvg;\n }\n if (data.file) {\n this.#bitmapFileName = data.file.name;\n }\n this.#createCanvas();\n }\n #getBitmapDone() {\n this.#bitmapPromise = null;\n this._uiManager.enableWaiting(false);\n if (!this.#canvas) {\n return;\n }\n if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {\n this.addEditToolbar().then(() => {\n this._editToolbar.hide();\n this._uiManager.editAltText(this, true);\n });\n return;\n }\n if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {\n this._reportTelemetry({\n action: "pdfjs.image.image_added",\n data: {\n alt_text_modal: false,\n alt_text_type: "empty"\n }\n });\n try {\n this.mlGuessAltText();\n } catch {}\n }\n this.div.focus();\n }\n async mlGuessAltText(imageData = null, updateAltTextData = true) {\n if (this.hasAltTextData()) {\n return null;\n }\n const {\n mlManager\n } = this._uiManager;\n if (!mlManager) {\n throw new Error("No ML.");\n }\n if (!(await mlManager.isEnabledFor("altText"))) {\n throw new Error("ML isn\'t enabled for alt text.");\n }\n const {\n data,\n width,\n height\n } = imageData || this.copyCanvas(null, null, true).imageData;\n const response = await mlManager.guess({\n name: "altText",\n request: {\n data,\n width,\n height,\n channels: data.length / (width * height)\n }\n });\n if (!response) {\n throw new Error("No response from the AI service.");\n }\n if (response.error) {\n throw new Error("Error from the AI service.");\n }\n if (response.cancel) {\n return null;\n }\n if (!response.output) {\n throw new Error("No valid response from the AI service.");\n }\n const altText = response.output;\n await this.setGuessedAltText(altText);\n if (updateAltTextData && !this.hasAltTextData()) {\n this.altTextData = {\n alt: altText,\n decorative: false\n };\n }\n return altText;\n }\n #getBitmap() {\n if (this.#bitmapId) {\n this._uiManager.enableWaiting(true);\n this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone());\n return;\n }\n if (this.#bitmapUrl) {\n const url = this.#bitmapUrl;\n this.#bitmapUrl = null;\n this._uiManager.enableWaiting(true);\n this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());\n return;\n }\n if (this.#bitmapFile) {\n const file = this.#bitmapFile;\n this.#bitmapFile = null;\n this._uiManager.enableWaiting(true);\n this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());\n return;\n }\n const input = document.createElement("input");\n input.type = "file";\n input.accept = SupportedImageMimeTypes.join(",");\n const signal = this._uiManager._signal;\n this.#bitmapPromise = new Promise(resolve => {\n input.addEventListener("change", async () => {\n if (!input.files || input.files.length === 0) {\n this.remove();\n } else {\n this._uiManager.enableWaiting(true);\n const data = await this._uiManager.imageManager.getFromFile(input.files[0]);\n this._reportTelemetry({\n action: "pdfjs.image.image_selected",\n data: {\n alt_text_modal: this._uiManager.useNewAltTextFlow\n }\n });\n this.#getBitmapFetched(data);\n }\n resolve();\n }, {\n signal\n });\n input.addEventListener("cancel", () => {\n this.remove();\n resolve();\n }, {\n signal\n });\n }).finally(() => this.#getBitmapDone());\n input.click();\n }\n remove() {\n if (this.#bitmapId) {\n this.#bitmap = null;\n this._uiManager.imageManager.deleteId(this.#bitmapId);\n this.#canvas?.remove();\n this.#canvas = null;\n if (this.#resizeTimeoutId) {\n clearTimeout(this.#resizeTimeoutId);\n this.#resizeTimeoutId = null;\n }\n }\n super.remove();\n }\n rebuild() {\n if (!this.parent) {\n if (this.#bitmapId) {\n this.#getBitmap();\n }\n return;\n }\n super.rebuild();\n if (this.div === null) {\n return;\n }\n if (this.#bitmapId && this.#canvas === null) {\n this.#getBitmap();\n }\n if (!this.isAttachedToDOM) {\n this.parent.add(this);\n }\n }\n onceAdded(focus) {\n this._isDraggable = true;\n if (focus) {\n this.div.focus();\n }\n }\n isEmpty() {\n return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId || this.#missingCanvas);\n }\n get toolbarButtons() {\n return [["altText", this.createAltText()]];\n }\n get isResizable() {\n return true;\n }\n render() {\n if (this.div) {\n return this.div;\n }\n let baseX, baseY;\n if (this._isCopy) {\n baseX = this.x;\n baseY = this.y;\n }\n super.render();\n this.div.hidden = true;\n this.createAltText();\n if (!this.#missingCanvas) {\n if (this.#bitmap) {\n this.#createCanvas();\n } else {\n this.#getBitmap();\n }\n }\n if (this._isCopy) {\n this._moveAfterPaste(baseX, baseY);\n }\n this._uiManager.addShouldRescale(this);\n return this.div;\n }\n setCanvas(annotationElementId, canvas) {\n const {\n id: bitmapId,\n bitmap\n } = this._uiManager.imageManager.getFromCanvas(annotationElementId, canvas);\n canvas.remove();\n if (bitmapId && this._uiManager.imageManager.isValidId(bitmapId)) {\n this.#bitmapId = bitmapId;\n if (bitmap) {\n this.#bitmap = bitmap;\n }\n this.#missingCanvas = false;\n this.#createCanvas();\n }\n }\n _onResized() {\n this.onScaleChanging();\n }\n onScaleChanging() {\n if (!this.parent) {\n return;\n }\n if (this.#resizeTimeoutId !== null) {\n clearTimeout(this.#resizeTimeoutId);\n }\n const TIME_TO_WAIT = 200;\n this.#resizeTimeoutId = setTimeout(() => {\n this.#resizeTimeoutId = null;\n this.#drawBitmap();\n }, TIME_TO_WAIT);\n }\n #createCanvas() {\n const {\n div\n } = this;\n let {\n width,\n height\n } = this.#bitmap;\n const [pageWidth, pageHeight] = this.pageDimensions;\n const MAX_RATIO = 0.75;\n if (this.width) {\n width = this.width * pageWidth;\n height = this.height * pageHeight;\n } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) {\n const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height);\n width *= factor;\n height *= factor;\n }\n this._uiManager.enableWaiting(false);\n const canvas = this.#canvas = document.createElement("canvas");\n canvas.setAttribute("role", "img");\n this.addContainer(canvas);\n this.width = width / pageWidth;\n this.height = height / pageHeight;\n this.setDims();\n if (this._initialOptions?.isCentered) {\n this.center();\n } else {\n this.fixAndSetPosition();\n }\n this._initialOptions = null;\n if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) {\n div.hidden = false;\n }\n this.#drawBitmap();\n if (!this.#hasBeenAddedInUndoStack) {\n this.parent.addUndoableEditor(this);\n this.#hasBeenAddedInUndoStack = true;\n }\n this._reportTelemetry({\n action: "inserted_image"\n });\n if (this.#bitmapFileName) {\n this.div.setAttribute("aria-description", this.#bitmapFileName);\n }\n if (!this.annotationElementId) {\n this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert");\n }\n }\n copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) {\n if (!maxDataDimension) {\n maxDataDimension = 224;\n }\n const {\n width: bitmapWidth,\n height: bitmapHeight\n } = this.#bitmap;\n const outputScale = new OutputScale();\n let bitmap = this.#bitmap;\n let width = bitmapWidth,\n height = bitmapHeight;\n let canvas = null;\n if (maxPreviewDimension) {\n if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) {\n const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight);\n width = Math.floor(bitmapWidth * ratio);\n height = Math.floor(bitmapHeight * ratio);\n }\n canvas = document.createElement("canvas");\n const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx);\n const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy);\n if (!this.#isSvg) {\n bitmap = this.#scaleBitmap(scaledWidth, scaledHeight);\n }\n const ctx = canvas.getContext("2d");\n ctx.filter = this._uiManager.hcmFilter;\n let white = "white",\n black = "#cfcfd8";\n if (this._uiManager.hcmFilter !== "none") {\n black = "black";\n } else if (ColorScheme.isDarkMode) {\n white = "#8f8f9d";\n black = "#42414d";\n }\n const boxDim = 15;\n const boxDimWidth = boxDim * outputScale.sx;\n const boxDimHeight = boxDim * outputScale.sy;\n const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2);\n const patternCtx = pattern.getContext("2d");\n patternCtx.fillStyle = white;\n patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2);\n patternCtx.fillStyle = black;\n patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight);\n patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight);\n ctx.fillStyle = ctx.createPattern(pattern, "repeat");\n ctx.fillRect(0, 0, scaledWidth, scaledHeight);\n ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);\n }\n let imageData = null;\n if (createImageData) {\n let dataWidth, dataHeight;\n if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) {\n dataWidth = bitmap.width;\n dataHeight = bitmap.height;\n } else {\n bitmap = this.#bitmap;\n if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) {\n const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight);\n dataWidth = Math.floor(bitmapWidth * ratio);\n dataHeight = Math.floor(bitmapHeight * ratio);\n if (!this.#isSvg) {\n bitmap = this.#scaleBitmap(dataWidth, dataHeight);\n }\n }\n }\n const offscreen = new OffscreenCanvas(dataWidth, dataHeight);\n const offscreenCtx = offscreen.getContext("2d", {\n willReadFrequently: true\n });\n offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight);\n imageData = {\n width: dataWidth,\n height: dataHeight,\n data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data\n };\n }\n return {\n canvas,\n width,\n height,\n imageData\n };\n }\n #scaleBitmap(width, height) {\n const {\n width: bitmapWidth,\n height: bitmapHeight\n } = this.#bitmap;\n let newWidth = bitmapWidth;\n let newHeight = bitmapHeight;\n let bitmap = this.#bitmap;\n while (newWidth > 2 * width || newHeight > 2 * height) {\n const prevWidth = newWidth;\n const prevHeight = newHeight;\n if (newWidth > 2 * width) {\n newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2);\n }\n if (newHeight > 2 * height) {\n newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2);\n }\n const offscreen = new OffscreenCanvas(newWidth, newHeight);\n const ctx = offscreen.getContext("2d");\n ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);\n bitmap = offscreen.transferToImageBitmap();\n }\n return bitmap;\n }\n #drawBitmap() {\n const [parentWidth, parentHeight] = this.parentDimensions;\n const {\n width,\n height\n } = this;\n const outputScale = new OutputScale();\n const scaledWidth = Math.ceil(width * parentWidth * outputScale.sx);\n const scaledHeight = Math.ceil(height * parentHeight * outputScale.sy);\n const canvas = this.#canvas;\n if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) {\n return;\n }\n canvas.width = scaledWidth;\n canvas.height = scaledHeight;\n const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight);\n const ctx = canvas.getContext("2d");\n ctx.filter = this._uiManager.hcmFilter;\n ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);\n }\n #serializeBitmap(toUrl) {\n if (toUrl) {\n if (this.#isSvg) {\n const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId);\n if (url) {\n return url;\n }\n }\n const canvas = document.createElement("canvas");\n ({\n width: canvas.width,\n height: canvas.height\n } = this.#bitmap);\n const ctx = canvas.getContext("2d");\n ctx.drawImage(this.#bitmap, 0, 0);\n return canvas.toDataURL();\n }\n if (this.#isSvg) {\n const [pageWidth, pageHeight] = this.pageDimensions;\n const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS);\n const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS);\n const offscreen = new OffscreenCanvas(width, height);\n const ctx = offscreen.getContext("2d");\n ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height);\n return offscreen.transferToImageBitmap();\n }\n return structuredClone(this.#bitmap);\n }\n static async deserialize(data, parent, uiManager) {\n let initialData = null;\n let missingCanvas = false;\n if (data instanceof StampAnnotationElement) {\n const {\n data: {\n rect,\n rotation,\n id,\n structParent,\n popupRef,\n richText,\n contentsObj,\n creationDate,\n modificationDate\n },\n container,\n parent: {\n page: {\n pageNumber\n }\n },\n canvas\n } = data;\n let bitmapId, bitmap;\n if (canvas) {\n delete data.canvas;\n ({\n id: bitmapId,\n bitmap\n } = uiManager.imageManager.getFromCanvas(container.id, canvas));\n canvas.remove();\n } else {\n missingCanvas = true;\n data._hasNoCanvas = true;\n }\n const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || "";\n initialData = data = {\n annotationType: AnnotationEditorType.STAMP,\n bitmapId,\n bitmap,\n pageIndex: pageNumber - 1,\n rect: rect.slice(0),\n rotation,\n annotationElementId: id,\n id,\n deleted: false,\n accessibilityData: {\n decorative: false,\n altText\n },\n isSvg: false,\n structParent,\n popupRef,\n richText,\n comment: contentsObj?.str || null,\n creationDate,\n modificationDate\n };\n }\n const editor = await super.deserialize(data, parent, uiManager);\n const {\n rect,\n bitmap,\n bitmapUrl,\n bitmapId,\n isSvg,\n accessibilityData\n } = data;\n if (missingCanvas) {\n uiManager.addMissingCanvas(data.id, editor);\n editor.#missingCanvas = true;\n } else if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) {\n editor.#bitmapId = bitmapId;\n if (bitmap) {\n editor.#bitmap = bitmap;\n }\n } else {\n editor.#bitmapUrl = bitmapUrl;\n }\n editor.#isSvg = isSvg;\n const [parentWidth, parentHeight] = editor.pageDimensions;\n editor.width = (rect[2] - rect[0]) / parentWidth;\n editor.height = (rect[3] - rect[1]) / parentHeight;\n if (accessibilityData) {\n editor.altTextData = accessibilityData;\n }\n editor._initialData = initialData;\n if (data.comment) {\n editor.setCommentData(data);\n }\n editor.#hasBeenAddedInUndoStack = !!initialData;\n return editor;\n }\n serialize(isForCopying = false, context = null) {\n if (this.isEmpty()) {\n return null;\n }\n if (this.deleted) {\n return this.serializeDeleted();\n }\n const serialized = Object.assign(super.serialize(isForCopying), {\n bitmapId: this.#bitmapId,\n isSvg: this.#isSvg\n });\n this.addComment(serialized);\n if (isForCopying) {\n serialized.bitmapUrl = this.#serializeBitmap(true);\n serialized.accessibilityData = this.serializeAltText(true);\n serialized.isCopy = true;\n return serialized;\n }\n const {\n decorative,\n altText\n } = this.serializeAltText(false);\n if (!decorative && altText) {\n serialized.accessibilityData = {\n type: "Figure",\n alt: altText\n };\n }\n if (this.annotationElementId) {\n const changes = this.#hasElementChanged(serialized);\n if (changes.isSame) {\n return null;\n }\n if (changes.isSameAltText) {\n delete serialized.accessibilityData;\n } else {\n serialized.accessibilityData.structParent = this._initialData.structParent ?? -1;\n }\n serialized.id = this.annotationElementId;\n delete serialized.bitmapId;\n return serialized;\n }\n if (context === null) {\n return serialized;\n }\n context.stamps ||= new Map();\n const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null;\n if (!context.stamps.has(this.#bitmapId)) {\n context.stamps.set(this.#bitmapId, {\n area,\n serialized\n });\n serialized.bitmap = this.#serializeBitmap(false);\n } else if (this.#isSvg) {\n const prevData = context.stamps.get(this.#bitmapId);\n if (area > prevData.area) {\n prevData.area = area;\n prevData.serialized.bitmap.close();\n prevData.serialized.bitmap = this.#serializeBitmap(false);\n }\n }\n return serialized;\n }\n #hasElementChanged(serialized) {\n const {\n pageIndex,\n accessibilityData: {\n altText\n }\n } = this._initialData;\n const isSamePageIndex = serialized.pageIndex === pageIndex;\n const isSameAltText = (serialized.accessibilityData?.alt || "") === altText;\n return {\n isSame: !this.hasEditedComment && !this._hasBeenMoved && !this._hasBeenResized && isSamePageIndex && isSameAltText,\n isSameAltText\n };\n }\n renderAnnotationElement(annotation) {\n if (this.deleted) {\n annotation.hide();\n return null;\n }\n annotation.updateEdited({\n rect: this.getPDFRect(),\n popup: this.comment\n });\n return null;\n }\n}\n\n;// ./src/display/editor/annotation_editor_layer.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass AnnotationEditorLayer {\n #accessibilityManager;\n #allowClick = false;\n #annotationLayer = null;\n #clickAC = null;\n #editorFocusTimeoutId = null;\n #editors = new Map();\n #hadPointerDown = false;\n #isDisabling = false;\n #isEnabling = false;\n #drawingAC = null;\n #focusedElement = null;\n #textLayer = null;\n #textSelectionAC = null;\n #textLayerDblClickAC = null;\n #lastPointerDownTimestamp = -1;\n #uiManager;\n static _initialized = false;\n static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor, SignatureEditor].map(type => [type._editorType, type]));\n constructor({\n uiManager,\n pageIndex,\n div,\n structTreeLayer,\n accessibilityManager,\n annotationLayer,\n drawLayer,\n textLayer,\n viewport,\n l10n\n }) {\n const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()];\n if (!AnnotationEditorLayer._initialized) {\n AnnotationEditorLayer._initialized = true;\n for (const editorType of editorTypes) {\n editorType.initialize(l10n, uiManager);\n }\n }\n uiManager.registerEditorTypes(editorTypes);\n this.#uiManager = uiManager;\n this.pageIndex = pageIndex;\n this.div = div;\n this.#accessibilityManager = accessibilityManager;\n this.#annotationLayer = annotationLayer;\n this.viewport = viewport;\n this.#textLayer = textLayer;\n this.drawLayer = drawLayer;\n this._structTree = structTreeLayer;\n this.#uiManager.addLayer(this);\n }\n updatePageIndex(newPageIndex) {\n for (const editor of this.#allEditorsIterator) {\n editor.updatePageIndex(newPageIndex);\n }\n this.pageIndex = newPageIndex;\n this.#uiManager.addLayer(this);\n }\n async setClonedFrom(clonedFrom) {\n if (!clonedFrom) {\n return;\n }\n const promises = [];\n for (const editor of clonedFrom.#allEditorsIterator) {\n const serialized = editor.serialize(true);\n if (!serialized) {\n continue;\n }\n serialized.isCopy = false;\n promises.push(this.deserialize(serialized).then(deserialized => {\n if (deserialized) {\n this.addOrRebuild(deserialized);\n }\n }));\n }\n await Promise.all(promises);\n }\n get isEmpty() {\n return this.#editors.size === 0;\n }\n get isInvisible() {\n return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE;\n }\n updateToolbar(options) {\n this.#uiManager.updateToolbar(options);\n }\n updateMode(mode = this.#uiManager.getMode()) {\n this.#cleanup();\n switch (mode) {\n case AnnotationEditorType.NONE:\n this.div.classList.toggle("nonEditing", true);\n this.disableTextSelection();\n this.togglePointerEvents(false);\n this.toggleAnnotationLayerPointerEvents(true);\n this.disableClick();\n return;\n case AnnotationEditorType.INK:\n this.disableTextSelection();\n this.togglePointerEvents(true);\n this.enableClick();\n break;\n case AnnotationEditorType.HIGHLIGHT:\n this.enableTextSelection();\n this.togglePointerEvents(false);\n this.disableClick();\n break;\n default:\n this.disableTextSelection();\n this.togglePointerEvents(true);\n this.enableClick();\n }\n this.toggleAnnotationLayerPointerEvents(false);\n const {\n classList\n } = this.div;\n classList.toggle("nonEditing", false);\n if (mode === AnnotationEditorType.POPUP) {\n classList.toggle("commentEditing", true);\n } else {\n classList.toggle("commentEditing", false);\n for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {\n classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType);\n }\n }\n this.div.hidden = false;\n }\n hasTextLayer(textLayer) {\n return textLayer === this.#textLayer?.div;\n }\n setEditingState(isEditing) {\n this.#uiManager.setEditingState(isEditing);\n }\n addCommands(params) {\n this.#uiManager.addCommands(params);\n }\n cleanUndoStack(type) {\n this.#uiManager.cleanUndoStack(type);\n }\n toggleDrawing(enabled = false) {\n this.div.classList.toggle("drawing", !enabled);\n }\n togglePointerEvents(enabled = false) {\n this.div.classList.toggle("disabled", !enabled);\n }\n toggleAnnotationLayerPointerEvents(enabled = false) {\n this.#annotationLayer?.togglePointerEvents(enabled);\n }\n get #allEditorsIterator() {\n return this.#editors.size !== 0 ? this.#editors.values() : this.#uiManager.getEditors(this.pageIndex);\n }\n async enable() {\n this.#isEnabling = true;\n this.div.tabIndex = 0;\n this.togglePointerEvents(true);\n this.div.classList.toggle("nonEditing", false);\n this.#textLayerDblClickAC?.abort();\n this.#textLayerDblClickAC = null;\n const annotationElementIds = new Set();\n for (const editor of this.#allEditorsIterator) {\n editor.enableEditing();\n editor.show(true);\n if (editor.annotationElementId) {\n this.#uiManager.removeChangedExistingAnnotation(editor);\n annotationElementIds.add(editor.annotationElementId);\n }\n }\n const annotationLayer = this.#annotationLayer;\n if (annotationLayer) {\n for (const editable of annotationLayer.getEditableAnnotations()) {\n editable.hide();\n if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) {\n continue;\n }\n if (annotationElementIds.has(editable.data.id)) {\n continue;\n }\n const editor = await this.deserialize(editable);\n if (!editor) {\n continue;\n }\n this.addOrRebuild(editor);\n editor.enableEditing();\n }\n }\n this.#isEnabling = false;\n this.#uiManager._eventBus.dispatch("editorsrendered", {\n source: this,\n pageNumber: this.pageIndex + 1\n });\n }\n disable() {\n this.#isDisabling = true;\n this.div.tabIndex = -1;\n this.togglePointerEvents(false);\n this.div.classList.toggle("nonEditing", true);\n if (this.#textLayer && !this.#textLayerDblClickAC) {\n this.#textLayerDblClickAC = new AbortController();\n const signal = this.#uiManager.combinedSignal(this.#textLayerDblClickAC);\n this.#textLayer.div.addEventListener("pointerdown", e => {\n const DBL_CLICK_THRESHOLD = 500;\n const {\n clientX,\n clientY,\n timeStamp\n } = e;\n const lastPointerDownTimestamp = this.#lastPointerDownTimestamp;\n if (timeStamp - lastPointerDownTimestamp > DBL_CLICK_THRESHOLD) {\n this.#lastPointerDownTimestamp = timeStamp;\n return;\n }\n this.#lastPointerDownTimestamp = -1;\n const {\n classList\n } = this.div;\n classList.toggle("getElements", true);\n const elements = document.elementsFromPoint(clientX, clientY);\n classList.toggle("getElements", false);\n if (!this.div.contains(elements[0])) {\n return;\n }\n let id;\n const regex = new RegExp(`^${AnnotationEditorPrefix}[0-9]+$`);\n for (const element of elements) {\n if (regex.test(element.id)) {\n id = element.id;\n break;\n }\n }\n if (!id) {\n return;\n }\n const editor = this.#editors.get(id);\n if (editor?.annotationElementId === null) {\n e.stopPropagation();\n e.preventDefault();\n editor.dblclick(e);\n }\n }, {\n signal,\n capture: true\n });\n }\n const annotationLayer = this.#annotationLayer;\n const needFakeAnnotation = [];\n if (annotationLayer) {\n const changedAnnotations = new Map();\n const resetAnnotations = new Map();\n for (const editor of this.#allEditorsIterator) {\n editor.disableEditing();\n if (!editor.annotationElementId) {\n needFakeAnnotation.push(editor);\n continue;\n }\n if (editor.serialize() !== null) {\n changedAnnotations.set(editor.annotationElementId, editor);\n continue;\n } else {\n resetAnnotations.set(editor.annotationElementId, editor);\n }\n this.getEditableAnnotation(editor.annotationElementId)?.show();\n editor.remove();\n }\n const editables = annotationLayer.getEditableAnnotations();\n for (const editable of editables) {\n const {\n id\n } = editable.data;\n if (this.#uiManager.isDeletedAnnotationElement(id)) {\n editable.updateEdited({\n deleted: true\n });\n continue;\n }\n let editor = resetAnnotations.get(id);\n if (editor) {\n editor.resetAnnotationElement(editable);\n editor.show(false);\n editable.show();\n continue;\n }\n editor = changedAnnotations.get(id);\n if (editor) {\n this.#uiManager.addChangedExistingAnnotation(editor);\n if (editor.renderAnnotationElement(editable)) {\n editor.show(false);\n }\n }\n editable.show();\n }\n }\n this.#cleanup();\n if (this.isEmpty) {\n this.div.hidden = true;\n }\n const {\n classList\n } = this.div;\n for (const editorType of AnnotationEditorLayer.#editorTypes.values()) {\n classList.remove(`${editorType._type}Editing`);\n }\n this.disableTextSelection();\n this.toggleAnnotationLayerPointerEvents(true);\n annotationLayer?.updateFakeAnnotations(needFakeAnnotation);\n this.#isDisabling = false;\n }\n getEditableAnnotation(id) {\n return this.#annotationLayer?.getEditableAnnotation(id) || null;\n }\n setActiveEditor(editor) {\n const currentActive = this.#uiManager.getActive();\n if (currentActive === editor) {\n return;\n }\n this.#uiManager.setActiveEditor(editor);\n }\n enableTextSelection() {\n this.div.tabIndex = -1;\n if (this.#textLayer?.div && !this.#textSelectionAC) {\n this.#textSelectionAC = new AbortController();\n const signal = this.#uiManager.combinedSignal(this.#textSelectionAC);\n this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), {\n signal\n });\n this.#textLayer.div.classList.add("highlighting");\n }\n }\n disableTextSelection() {\n this.div.tabIndex = 0;\n if (this.#textLayer?.div && this.#textSelectionAC) {\n this.#textSelectionAC.abort();\n this.#textSelectionAC = null;\n this.#textLayer.div.classList.remove("highlighting");\n }\n }\n #textLayerPointerDown(event) {\n this.#uiManager.unselectAll();\n const {\n target\n } = event;\n if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) {\n const {\n isMac\n } = FeatureTest.platform;\n if (event.button !== 0 || event.ctrlKey && isMac) {\n return;\n }\n this.#uiManager.showAllEditors("highlight", true, true);\n this.#textLayer.div.classList.add("free");\n this.toggleDrawing();\n HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", {\n target: this.#textLayer.div,\n x: event.x,\n y: event.y\n });\n this.#textLayer.div.addEventListener("pointerup", () => {\n this.#textLayer.div.classList.remove("free");\n this.toggleDrawing(true);\n }, {\n once: true,\n signal: this.#uiManager._signal\n });\n event.preventDefault();\n }\n }\n enableClick() {\n if (this.#clickAC) {\n return;\n }\n this.#clickAC = new AbortController();\n const signal = this.#uiManager.combinedSignal(this.#clickAC);\n this.div.addEventListener("pointerdown", this.pointerdown.bind(this), {\n signal\n });\n const pointerup = this.pointerup.bind(this);\n this.div.addEventListener("pointerup", pointerup, {\n signal\n });\n this.div.addEventListener("pointercancel", pointerup, {\n signal\n });\n }\n disableClick() {\n this.#clickAC?.abort();\n this.#clickAC = null;\n }\n attach(editor) {\n this.#editors.set(editor.id, editor);\n const {\n annotationElementId\n } = editor;\n if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) {\n this.#uiManager.removeDeletedAnnotationElement(editor);\n }\n }\n detach(editor) {\n this.#editors.delete(editor.id);\n this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);\n if (!this.#isDisabling && editor.annotationElementId) {\n this.#uiManager.addDeletedAnnotationElement(editor);\n }\n }\n remove(editor) {\n this.detach(editor);\n this.#uiManager.removeEditor(editor);\n editor.div.remove();\n editor.isAttachedToDOM = false;\n }\n changeParent(editor) {\n if (editor.parent === this) {\n return;\n }\n if (editor.parent && editor.annotationElementId) {\n this.#uiManager.addDeletedAnnotationElement(editor);\n AnnotationEditor.deleteAnnotationElement(editor);\n editor.annotationElementId = null;\n }\n this.attach(editor);\n editor.parent?.detach(editor);\n editor.setParent(this);\n if (editor.div && editor.isAttachedToDOM) {\n editor.div.remove();\n this.div.append(editor.div);\n }\n }\n add(editor) {\n if (editor.parent === this && editor.isAttachedToDOM) {\n return;\n }\n this.changeParent(editor);\n this.#uiManager.addEditor(editor);\n this.attach(editor);\n if (!editor.isAttachedToDOM) {\n const div = editor.render();\n this.div.append(div);\n editor.isAttachedToDOM = true;\n }\n editor.fixAndSetPosition();\n editor.onceAdded(!this.#isEnabling);\n this.#uiManager.addToAnnotationStorage(editor);\n editor._reportTelemetry(editor.telemetryInitialData);\n }\n moveEditorInDOM(editor) {\n if (!editor.isAttachedToDOM) {\n return;\n }\n const {\n activeElement\n } = document;\n if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) {\n editor._focusEventsAllowed = false;\n this.#editorFocusTimeoutId = setTimeout(() => {\n this.#editorFocusTimeoutId = null;\n if (!editor.div.contains(document.activeElement)) {\n editor.div.addEventListener("focusin", () => {\n editor._focusEventsAllowed = true;\n }, {\n once: true,\n signal: this.#uiManager._signal\n });\n activeElement.focus();\n } else {\n editor._focusEventsAllowed = true;\n }\n }, 0);\n }\n editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);\n }\n addOrRebuild(editor) {\n if (editor.needsToBeRebuilt()) {\n editor.parent ||= this;\n editor.rebuild();\n editor.show();\n } else {\n this.add(editor);\n }\n }\n addUndoableEditor(editor) {\n const cmd = () => editor._uiManager.rebuild(editor);\n const undo = () => {\n editor.remove();\n };\n this.addCommands({\n cmd,\n undo,\n mustExec: false\n });\n }\n getEditorByUID(uid) {\n for (const editor of this.#editors.values()) {\n if (editor.uid === uid) {\n return editor;\n }\n }\n return null;\n }\n getNextId() {\n return this.#uiManager.getId();\n }\n get #currentEditorType() {\n return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode());\n }\n combinedSignal(ac) {\n return this.#uiManager.combinedSignal(ac);\n }\n #createNewEditor(params) {\n const editorType = this.#currentEditorType;\n return editorType ? new editorType.prototype.constructor(params) : null;\n }\n canCreateNewEmptyEditor() {\n return this.#currentEditorType?.canCreateNewEmptyEditor();\n }\n async pasteEditor(options, params) {\n this.updateToolbar(options);\n await this.#uiManager.updateMode(options.mode);\n const {\n offsetX,\n offsetY\n } = this.#getCenterPoint();\n const id = this.getNextId();\n const editor = this.#createNewEditor({\n parent: this,\n id,\n x: offsetX,\n y: offsetY,\n uiManager: this.#uiManager,\n isCentered: true,\n ...params\n });\n if (editor) {\n this.add(editor);\n }\n }\n async deserialize(data) {\n return (await AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager)) || null;\n }\n createAndAddNewEditor(event, isCentered, data = {}) {\n const id = this.getNextId();\n const editor = this.#createNewEditor({\n parent: this,\n id,\n x: event.offsetX,\n y: event.offsetY,\n uiManager: this.#uiManager,\n isCentered,\n ...data\n });\n if (editor) {\n this.add(editor);\n }\n return editor;\n }\n get boundingClientRect() {\n return this.div.getBoundingClientRect();\n }\n #getCenterPoint() {\n const {\n x,\n y,\n width,\n height\n } = this.boundingClientRect;\n const tlX = Math.max(0, x);\n const tlY = Math.max(0, y);\n const brX = Math.min(window.innerWidth, x + width);\n const brY = Math.min(window.innerHeight, y + height);\n const centerX = (tlX + brX) / 2 - x;\n const centerY = (tlY + brY) / 2 - y;\n const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX];\n return {\n offsetX,\n offsetY\n };\n }\n addNewEditor(data = {}) {\n this.createAndAddNewEditor(this.#getCenterPoint(), true, data);\n }\n setSelected(editor) {\n this.#uiManager.setSelected(editor);\n }\n toggleSelected(editor) {\n this.#uiManager.toggleSelected(editor);\n }\n unselect(editor) {\n this.#uiManager.unselect(editor);\n }\n pointerup(event) {\n const {\n isMac\n } = FeatureTest.platform;\n if (event.button !== 0 || event.ctrlKey && isMac) {\n return;\n }\n if (event.target !== this.div) {\n return;\n }\n if (!this.#hadPointerDown) {\n return;\n }\n this.#hadPointerDown = false;\n if (this.#currentEditorType?.isDrawer && this.#currentEditorType.supportMultipleDrawings) {\n return;\n }\n if (!this.#allowClick) {\n this.#allowClick = true;\n return;\n }\n const currentMode = this.#uiManager.getMode();\n if (currentMode === AnnotationEditorType.STAMP || currentMode === AnnotationEditorType.SIGNATURE) {\n this.#uiManager.unselectAll();\n return;\n }\n this.createAndAddNewEditor(event, false);\n }\n pointerdown(event) {\n if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) {\n this.enableTextSelection();\n }\n if (this.#hadPointerDown) {\n this.#hadPointerDown = false;\n return;\n }\n const {\n isMac\n } = FeatureTest.platform;\n if (event.button !== 0 || event.ctrlKey && isMac) {\n return;\n }\n if (event.target !== this.div) {\n return;\n }\n this.#hadPointerDown = true;\n if (this.#currentEditorType?.isDrawer) {\n this.startDrawingSession(event);\n return;\n }\n const editor = this.#uiManager.getActive();\n this.#allowClick = !editor || editor.isEmpty();\n }\n startDrawingSession(event) {\n this.div.focus({\n preventScroll: true\n });\n if (this.#drawingAC) {\n this.#currentEditorType.startDrawing(this, this.#uiManager, false, event);\n return;\n }\n this.#uiManager.setCurrentDrawingSession(this);\n this.#drawingAC = new AbortController();\n const signal = this.#uiManager.combinedSignal(this.#drawingAC);\n this.div.addEventListener("blur", ({\n relatedTarget\n }) => {\n if (relatedTarget && !this.div.contains(relatedTarget)) {\n this.#focusedElement = null;\n this.commitOrRemove();\n }\n }, {\n signal\n });\n this.#currentEditorType.startDrawing(this, this.#uiManager, false, event);\n }\n pause(on) {\n if (on) {\n const {\n activeElement\n } = document;\n if (this.div.contains(activeElement)) {\n this.#focusedElement = activeElement;\n }\n return;\n }\n if (this.#focusedElement) {\n setTimeout(() => {\n this.#focusedElement?.focus();\n this.#focusedElement = null;\n }, 0);\n }\n }\n endDrawingSession(isAborted = false) {\n if (!this.#drawingAC) {\n return null;\n }\n this.#uiManager.setCurrentDrawingSession(null);\n this.#drawingAC.abort();\n this.#drawingAC = null;\n this.#focusedElement = null;\n return this.#currentEditorType.endDrawing(isAborted);\n }\n findNewParent(editor, x, y) {\n const layer = this.#uiManager.findParent(x, y);\n if (layer === null || layer === this) {\n return false;\n }\n layer.changeParent(editor);\n return true;\n }\n commitOrRemove() {\n if (this.#drawingAC) {\n this.endDrawingSession();\n return true;\n }\n return false;\n }\n onScaleChanging() {\n if (!this.#drawingAC) {\n return;\n }\n this.#currentEditorType.onScaleChangingWhenDrawing(this);\n }\n destroy() {\n this.commitOrRemove();\n if (this.#uiManager.getActive()?.parent === this) {\n this.#uiManager.commitOrRemove();\n this.#uiManager.setActiveEditor(null);\n }\n if (this.#editorFocusTimeoutId) {\n clearTimeout(this.#editorFocusTimeoutId);\n this.#editorFocusTimeoutId = null;\n }\n for (const editor of this.#editors.values()) {\n this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);\n editor.setParent(null);\n editor.isAttachedToDOM = false;\n editor.div.remove();\n }\n this.div = null;\n this.#editors.clear();\n this.#uiManager.removeLayer(this);\n }\n #cleanup() {\n for (const editor of this.#editors.values()) {\n if (editor.isEmpty()) {\n editor.remove();\n }\n }\n }\n render({\n viewport\n }) {\n this.viewport = viewport;\n setLayerDimensions(this.div, viewport);\n for (const editor of this.#uiManager.getEditors(this.pageIndex)) {\n this.add(editor);\n editor.rebuild();\n }\n this.updateMode();\n }\n update({\n viewport\n }) {\n this.#uiManager.commitOrRemove();\n this.#cleanup();\n const oldRotation = this.viewport.rotation;\n const rotation = viewport.rotation;\n this.viewport = viewport;\n setLayerDimensions(this.div, {\n rotation\n });\n if (oldRotation !== rotation) {\n for (const editor of this.#editors.values()) {\n editor.rotate(rotation);\n }\n }\n }\n get pageDimensions() {\n const {\n pageWidth,\n pageHeight\n } = this.viewport.rawDims;\n return [pageWidth, pageHeight];\n }\n get scale() {\n return this.#uiManager.viewParameters.realScale;\n }\n}\n\n;// ./src/display/draw_layer.js\n\n\n\n\nclass DrawLayer {\n #parent = null;\n #mapping = new Map();\n #toUpdate = new Map();\n static #id = 0;\n setParent(parent) {\n if (!this.#parent) {\n this.#parent = parent;\n return;\n }\n if (this.#parent !== parent) {\n if (this.#mapping.size > 0) {\n for (const root of this.#mapping.values()) {\n root.remove();\n parent.append(root);\n }\n }\n this.#parent = parent;\n }\n }\n static get _svgFactory() {\n return shadow(this, "_svgFactory", new DOMSVGFactory());\n }\n static #setBox(element, [x, y, width, height]) {\n const {\n style\n } = element;\n style.top = `${100 * y}%`;\n style.left = `${100 * x}%`;\n style.width = `${100 * width}%`;\n style.height = `${100 * height}%`;\n }\n #createSVG() {\n const svg = DrawLayer._svgFactory.create(1, 1, true);\n this.#parent.append(svg);\n svg.setAttribute("aria-hidden", true);\n return svg;\n }\n #createClipPath(defs, pathId) {\n const clipPath = DrawLayer._svgFactory.createElement("clipPath");\n defs.append(clipPath);\n const clipPathId = `clip_${pathId}`;\n clipPath.setAttribute("id", clipPathId);\n clipPath.setAttribute("clipPathUnits", "objectBoundingBox");\n const clipPathUse = DrawLayer._svgFactory.createElement("use");\n clipPath.append(clipPathUse);\n clipPathUse.setAttribute("href", `#${pathId}`);\n clipPathUse.classList.add("clip");\n return clipPathId;\n }\n #updateProperties(element, properties) {\n for (const [key, value] of Object.entries(properties)) {\n if (value === null) {\n element.removeAttribute(key);\n } else {\n element.setAttribute(key, value);\n }\n }\n }\n draw(properties, isPathUpdatable = false, hasClip = false) {\n const id = DrawLayer.#id++;\n const root = this.#createSVG();\n const defs = DrawLayer._svgFactory.createElement("defs");\n root.append(defs);\n const path = DrawLayer._svgFactory.createElement("path");\n defs.append(path);\n const pathId = `path_${id}`;\n path.setAttribute("id", pathId);\n path.setAttribute("vector-effect", "non-scaling-stroke");\n if (isPathUpdatable) {\n this.#toUpdate.set(id, path);\n }\n const clipPathId = hasClip ? this.#createClipPath(defs, pathId) : null;\n const use = DrawLayer._svgFactory.createElement("use");\n root.append(use);\n use.setAttribute("href", `#${pathId}`);\n this.updateProperties(root, properties);\n this.#mapping.set(id, root);\n return {\n id,\n clipPathId: `url(#${clipPathId})`\n };\n }\n drawOutline(properties, mustRemoveSelfIntersections) {\n const id = DrawLayer.#id++;\n const root = this.#createSVG();\n const defs = DrawLayer._svgFactory.createElement("defs");\n root.append(defs);\n const path = DrawLayer._svgFactory.createElement("path");\n defs.append(path);\n const pathId = `path_${id}`;\n path.setAttribute("id", pathId);\n path.setAttribute("vector-effect", "non-scaling-stroke");\n let maskId;\n if (mustRemoveSelfIntersections) {\n const mask = DrawLayer._svgFactory.createElement("mask");\n defs.append(mask);\n maskId = `mask_${id}`;\n mask.setAttribute("id", maskId);\n mask.setAttribute("maskUnits", "objectBoundingBox");\n const rect = DrawLayer._svgFactory.createElement("rect");\n mask.append(rect);\n rect.setAttribute("width", "1");\n rect.setAttribute("height", "1");\n rect.setAttribute("fill", "white");\n const use = DrawLayer._svgFactory.createElement("use");\n mask.append(use);\n use.setAttribute("href", `#${pathId}`);\n use.setAttribute("stroke", "none");\n use.setAttribute("fill", "black");\n use.setAttribute("fill-rule", "nonzero");\n use.classList.add("mask");\n }\n const use1 = DrawLayer._svgFactory.createElement("use");\n root.append(use1);\n use1.setAttribute("href", `#${pathId}`);\n if (maskId) {\n use1.setAttribute("mask", `url(#${maskId})`);\n }\n const use2 = use1.cloneNode();\n root.append(use2);\n use1.classList.add("mainOutline");\n use2.classList.add("secondaryOutline");\n this.updateProperties(root, properties);\n this.#mapping.set(id, root);\n return id;\n }\n finalizeDraw(id, properties) {\n this.#toUpdate.delete(id);\n this.updateProperties(id, properties);\n }\n updateProperties(elementOrId, properties) {\n if (!properties) {\n return;\n }\n const {\n root,\n bbox,\n rootClass,\n path\n } = properties;\n const element = typeof elementOrId === "number" ? this.#mapping.get(elementOrId) : elementOrId;\n if (!element) {\n return;\n }\n if (root) {\n this.#updateProperties(element, root);\n }\n if (bbox) {\n DrawLayer.#setBox(element, bbox);\n }\n if (rootClass) {\n const {\n classList\n } = element;\n for (const [className, value] of Object.entries(rootClass)) {\n classList.toggle(className, value);\n }\n }\n if (path) {\n const defs = element.firstElementChild;\n const pathElement = defs.firstElementChild;\n this.#updateProperties(pathElement, path);\n }\n }\n updateParent(id, layer) {\n if (layer === this) {\n return;\n }\n const root = this.#mapping.get(id);\n if (!root) {\n return;\n }\n layer.#parent.append(root);\n this.#mapping.delete(id);\n layer.#mapping.set(id, root);\n }\n remove(id) {\n this.#toUpdate.delete(id);\n if (this.#parent === null) {\n return;\n }\n this.#mapping.get(id).remove();\n this.#mapping.delete(id);\n }\n destroy() {\n this.#parent = null;\n for (const root of this.#mapping.values()) {\n root.remove();\n }\n this.#mapping.clear();\n this.#toUpdate.clear();\n }\n}\n\n;// ./src/pdf.js\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{\n globalThis._pdfjsTestingUtils = {\n HighlightOutliner: HighlightOutliner\n };\n}\nglobalThis.pdfjsLib = {\n AbortException: AbortException,\n AnnotationEditorLayer: AnnotationEditorLayer,\n AnnotationEditorParamsType: AnnotationEditorParamsType,\n AnnotationEditorType: AnnotationEditorType,\n AnnotationEditorUIManager: AnnotationEditorUIManager,\n AnnotationLayer: AnnotationLayer,\n AnnotationMode: AnnotationMode,\n AnnotationType: AnnotationType,\n applyOpacity: applyOpacity,\n build: build,\n ColorPicker: ColorPicker,\n createValidAbsoluteUrl: createValidAbsoluteUrl,\n CSSConstants: CSSConstants,\n DOMSVGFactory: DOMSVGFactory,\n DrawLayer: DrawLayer,\n FeatureTest: FeatureTest,\n fetchData: fetchData,\n findContrastColor: findContrastColor,\n getDocument: getDocument,\n getFilenameFromUrl: getFilenameFromUrl,\n getPdfFilenameFromUrl: getPdfFilenameFromUrl,\n getRGB: getRGB,\n getUuid: getUuid,\n getXfaPageViewport: getXfaPageViewport,\n GlobalWorkerOptions: GlobalWorkerOptions,\n ImageKind: ImageKind,\n InvalidPDFException: InvalidPDFException,\n isDataScheme: isDataScheme,\n isPdfFile: isPdfFile,\n isValidExplicitDest: isValidExplicitDest,\n makeArr: makeArr,\n makeMap: makeMap,\n makeObj: makeObj,\n MathClamp: MathClamp,\n noContextMenu: noContextMenu,\n normalizeUnicode: normalizeUnicode,\n OPS: OPS,\n OutputScale: OutputScale,\n PasswordResponses: PasswordResponses,\n PDFDataRangeTransport: PDFDataRangeTransport,\n PDFDateString: PDFDateString,\n PDFWorker: PDFWorker,\n PermissionFlag: PermissionFlag,\n PixelsPerInch: PixelsPerInch,\n RenderingCancelledException: RenderingCancelledException,\n renderRichText: renderRichText,\n ResponseException: ResponseException,\n setLayerDimensions: setLayerDimensions,\n shadow: shadow,\n SignatureExtractor: SignatureExtractor,\n stopEvent: stopEvent,\n SupportedImageMimeTypes: SupportedImageMimeTypes,\n TextLayer: TextLayer,\n TouchManager: TouchManager,\n updateUrlHash: updateUrlHash,\n Util: Util,\n VerbosityLevel: VerbosityLevel,\n version: version,\n XfaLayer: XfaLayer\n};\n\nexport { AbortException, AnnotationEditorLayer, AnnotationEditorParamsType, AnnotationEditorType, AnnotationEditorUIManager, AnnotationLayer, AnnotationMode, AnnotationType, CSSConstants, ColorPicker, DOMSVGFactory, DrawLayer, FeatureTest, GlobalWorkerOptions, ImageKind, InvalidPDFException, MathClamp, OPS, OutputScale, PDFDataRangeTransport, PDFDateString, PDFWorker, PasswordResponses, PermissionFlag, PixelsPerInch, RenderingCancelledException, ResponseException, SignatureExtractor, SupportedImageMimeTypes, TextLayer, TouchManager, Util, VerbosityLevel, XfaLayer, applyOpacity, build, createValidAbsoluteUrl, fetchData, findContrastColor, getDocument, getFilenameFromUrl, getPdfFilenameFromUrl, getRGB, getUuid, getXfaPageViewport, isDataScheme, isPdfFile, isValidExplicitDest, makeArr, makeMap, makeObj, noContextMenu, normalizeUnicode, renderRichText, setLayerDimensions, shadow, stopEvent, updateUrlHash, version };\n\n//# sourceMappingURL=pdf.mjs.map';export{n as default};