diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 162301b43..e7519e060 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -136,7 +136,7 @@ jobs: - typescript runs-on: ubuntu-latest container: - image: mcr.microsoft.com/playwright:v1.62.1-noble + image: mcr.microsoft.com/playwright:v1.63.0-noble timeout-minutes: 20 steps: - name: Check out diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ec7fa0c0..62f8c00dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,18 @@ ## Unreleased -- Updated pnpm to 11.25.0, Node.js types, Oxc tooling, Wrangler, and the Pages/AWS credential actions; aligned both Docker builders with the source toolchains while preserving runtime minimums and the dependency release-age gate. +**Highlights:** Complete attachment delivery and reliable unread and reaction controls. + +- Committed channel and direct-message attachments before creation events, preserved complete attachments on nonce replay, and kept already-committed channel sends recoverable after moderation changes. Thanks @sercada. +- Kept the unread bar readable and clickable above message menus and reaction pickers. Thanks @isaiahknight-va. +- Fixed removal of percent-containing reaction keys without double-decoding them, and clarified glyph-based bot reactions while preserving custom strings. Thanks @isaiahknight-va. +- Kept the mobile thread drawer above raised message rows and prevented the navigation toggle from covering its header. Thanks @isaiahknight-va. +- Updated in-app brand tiles to use the Keystroke mark. +- Updated PDF.js to 6.3.289, virtua to 0.51.0, and Electron to 43.6.0 for rendering, scrolling, and desktop runtime fixes while retaining the macOS 12 minimum and dependency release-age gate. - Updated the server build toolchain to Go 1.27.1, SQLite driver to 1.58.0, and Go cryptography dependency to 0.56.0 while retaining the Go 1.26.6 minimum and existing database and password formats. +- Updated Playwright to 1.63.0 and Wrangler to 4.129.0 alongside pnpm 11.25.0, Node.js types, Oxc tooling, and the Pages/AWS credential actions; aligned Docker builders with the source toolchains while preserving runtime minimums and the dependency release-age gate. + +Thanks @KrasimirKralev for member-directory validation coverage. ## v0.4.0 - 2026-09-02 diff --git a/apps/api/internal/webassets/dist/200.html b/apps/api/internal/webassets/dist/200.html index 04e68dee6..abd70f126 100644 --- a/apps/api/internal/webassets/dist/200.html +++ b/apps/api/internal/webassets/dist/200.html @@ -103,7 +103,7 @@ - + @@ -125,7 +125,7 @@ Promise.all([ import("/_app/immutable/entry/start.W_KKVBz4.js"), - import("/_app/immutable/entry/app.CuIU8RJQ.js") + import("/_app/immutable/entry/app.CmNQCuu5.js") ]).then(([kit, app]) => { kit.start(app, element); }); diff --git a/apps/api/internal/webassets/dist/_app/immutable/assets/pdf.worker.CLesOks4.mjs b/apps/api/internal/webassets/dist/_app/immutable/assets/pdf.worker.TGcf_-kp.mjs similarity index 98% rename from apps/api/internal/webassets/dist/_app/immutable/assets/pdf.worker.CLesOks4.mjs rename to apps/api/internal/webassets/dist/_app/immutable/assets/pdf.worker.TGcf_-kp.mjs index 66ae0d0b2..ab24e0df4 100644 --- a/apps/api/internal/webassets/dist/_app/immutable/assets/pdf.worker.CLesOks4.mjs +++ b/apps/api/internal/webassets/dist/_app/immutable/assets/pdf.worker.TGcf_-kp.mjs @@ -21,8 +21,8 @@ */ /** - * pdfjsVersion = 6.2.108 - * pdfjsBuild = 0365cbde0 + * pdfjsVersion = 6.3.289 + * pdfjsBuild = 1c8020a7d */ ;// ./src/shared/util.js @@ -529,7 +529,9 @@ class FeatureTest { } class Util { static get hexNums() { - return shadow(this, "hexNums", Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0"))); + return shadow(this, "hexNums", Array.from({ + length: 256 + }, (_, n) => n.toString(16).padStart(2, "0"))); } static makeHexColor(r, g, b) { return `#${this.hexNums[r]}${this.hexNums[g]}${this.hexNums[b]}`; @@ -817,9 +819,7 @@ class Cmd { return CmdCache[cmd] ||= new Cmd(cmd); } } -const nonSerializable = function nonSerializableClosure() { - return nonSerializable; -}; +const nonSerializable = () => nonSerializable; class Dict { __nonSerializable__ = nonSerializable; #map = new Map(); @@ -835,27 +835,24 @@ class Dict { get size() { return this.#map.size; } - #getValue(isAsync, key1, key2, key3) { + #getValue(isAsync, key1, key2) { let value = this.#map.get(key1); if (value === undefined && key2 !== undefined) { value = this.#map.get(key2); - if (value === undefined && key3 !== undefined) { - value = this.#map.get(key3); - } } if (value instanceof Ref && this.xref) { return isAsync ? this.xref.fetchAsync(value, this.suppressEncryption) : this.xref.fetch(value, this.suppressEncryption); } return value; } - get(key1, key2, key3) { - return this.#getValue(false, key1, key2, key3); + get(key1, key2) { + return this.#getValue(false, key1, key2); } - async getAsync(key1, key2, key3) { - return this.#getValue(true, key1, key2, key3); + async getAsync(key1, key2) { + return this.#getValue(true, key1, key2); } - getArray(key1, key2, key3) { - let value = this.#getValue(false, key1, key2, key3); + getArray(key1, key2) { + let value = this.#getValue(false, key1, key2); if (Array.isArray(value)) { value = value.slice(); for (let i = 0, ii = value.length; i < ii; i++) { @@ -1005,44 +1002,49 @@ class Ref { } } class RefSet { + #set = new Set(); constructor(parent = null) { - this._set = new Set(parent?._set); + if (parent) { + for (const refStr of parent) { + this.#set.add(refStr); + } + } } has(ref) { - return this._set.has(ref.toString()); + return this.#set.has(ref.toString()); } put(ref) { - this._set.add(ref.toString()); + this.#set.add(ref.toString()); } remove(ref) { - this._set.delete(ref.toString()); + this.#set.delete(ref.toString()); } [Symbol.iterator]() { - return this._set.values(); + return this.#set.keys(); } clear() { - this._set.clear(); + this.#set.clear(); } } -class RefSetCache { - _map = new Map(); +class RefMap { + #map = new Map(); get size() { - return this._map.size; + return this.#map.size; } get(ref) { - return this._map.get(ref.toString()); + return this.#map.get(ref.toString()); } has(ref) { - return this._map.has(ref.toString()); + return this.#map.has(ref.toString()); } put(ref, obj) { - this._map.set(ref.toString(), obj); + this.#map.set(ref.toString(), obj); } putAlias(ref, aliasRef) { - this._map.set(ref.toString(), this.get(aliasRef)); + this.#map.set(ref.toString(), this.get(aliasRef)); } getOrPutComputed(ref, callback) { - const map = this._map, + const map = this.#map, refStr = ref.toString(); if (!map.has(refStr)) { map.set(refStr, callback(ref)); @@ -1050,21 +1052,21 @@ class RefSetCache { return map.get(refStr); } [Symbol.iterator]() { - return this._map.values(); + return this.#map.values(); } clear() { - this._map.clear(); + this.#map.clear(); } *values() { - yield* this._map.values(); + yield* this.#map.values(); } *items() { - for (const [ref, value] of this._map) { + for (const [ref, value] of this.#map) { yield [Ref.fromString(ref), value]; } } *keys() { - for (const ref of this._map.keys()) { + for (const ref of this.#map.keys()) { yield Ref.fromString(ref); } } @@ -1118,7 +1120,7 @@ class BaseStream { get canAsyncDecodeImageFromBuffer() { return false; } - async getTransferableImage() { + async getTransferableImage(width, height) { return null; } peekByte() { @@ -1177,16 +1179,42 @@ class BaseStream { } } +;// ./src/shared/css_utils.js +const CONTROL_CHAR_REGEXP = /\p{Cc}/u; +function isCSSString(str) { + const quote = str[0]; + if (str.length < 2 || quote !== `"` && quote !== `'` || str.at(-1) !== quote) { + return false; + } + const end = str.length - 1; + for (let i = 1; i < end; i++) { + const char = str[i]; + if (char === quote || CONTROL_CHAR_REGEXP.test(char)) { + return false; + } + if (char === "\\") { + if (++i >= end || CONTROL_CHAR_REGEXP.test(str[i])) { + return false; + } + } + } + return true; +} +function serializeFontFamily(fontFamily) { + if (isCSSString(fontFamily)) { + return fontFamily; + } + const escaped = fontFamily.replaceAll(/["\\\p{Cc}]/gu, char => char === `"` || char === "\\" ? `\\${char}` : `\\${char.codePointAt(0).toString(16)} `); + return `"${escaped}"`; +} + ;// ./src/core/string_utils.js function isAscii(str) { return typeof str === "string" && (!str || /^[\x00-\x7F]*$/.test(str)); } function stringToAsciiOrUTF16BE(str) { - if (str === null || str === undefined) { - return str; - } - return isAscii(str) ? str : stringToUTF16String(str, true); + return str === null || str === undefined || isAscii(str) ? str : stringToUTF16String(str, true); } function stringToUTF16HexString(str) { const buf = []; @@ -1208,6 +1236,7 @@ function stringToUTF16String(str, bigEndian = false) { return buf.join(""); } const PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac]; +const PDFStringTextDecoders = Object.create(null); function stringToPDFString(str, keepEscapeSequence = false) { if (str[0] >= "\xEF") { let encoding; @@ -1226,7 +1255,7 @@ function stringToPDFString(str, keepEscapeSequence = false) { } if (encoding) { try { - const decoder = new TextDecoder(encoding, { + const decoder = PDFStringTextDecoders[encoding] ??= new TextDecoder(encoding, { fatal: true }); const buffer = stringToBytes(str); @@ -1258,16 +1287,17 @@ function stringToPDFString(str, keepEscapeSequence = false) { + const PDF_VERSION_REGEXP = /^[1-9]\.\d$/; const MAX_INT_32 = 2 ** 31 - 1; const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; const RESOURCES_KEYS_OPERATOR_LIST = ["ColorSpace", "ExtGState", "Font", "Pattern", "Properties", "Shading", "XObject"]; const RESOURCES_KEYS_TEXT_CONTENT = ["ExtGState", "Font", "Properties", "XObject"]; -function getLookupTableFactory(initializer) { +function getLookupTableFactory(initializer, useArray = false) { let lookup; return function () { if (initializer) { - lookup = Object.create(null); + lookup = useArray ? [] : Object.create(null); initializer(lookup); initializer = null; } @@ -1434,7 +1464,7 @@ function lookupNormalRect(arr, fallback) { return isNumberArray(arr, 4) ? Util.normalizeRect(arr) : fallback; } function parseXFAPath(path) { - const positionPattern = /(.+)\[(\d+)\]$/; + const positionPattern = /^(.+)\[(\d+)\]$/; return path.split(".").map(component => { const m = component.match(positionPattern); if (m) { @@ -1518,7 +1548,7 @@ function _collectJS(entry, xref, list, parents) { } } function collectActions(xref, dict, eventType) { - const actions = Object.create(null); + const actions = new Map(); const additionalActionsDicts = getInheritableProperty({ dict, key: "AA", @@ -1539,7 +1569,7 @@ function collectActions(xref, dict, eventType) { const list = []; _collectJS(rawActionDict, xref, list, parents); if (list.length > 0) { - actions[action] = list; + actions.set(action, list); } } } @@ -1550,10 +1580,10 @@ function collectActions(xref, dict, eventType) { const list = []; _collectJS(actionDict, xref, list, parents); if (list.length > 0) { - actions.Action = list; + actions.set("Action", list); } } - return Object.keys(actions).length ? actions : null; + return actions.size ? actions : null; } const XMLEntities = { 0x3c: "<", @@ -1614,6 +1644,12 @@ function validateFontName(fontFamily, mustWarn = false) { } return false; } + if (CONTROL_CHAR_REGEXP.test(fontFamily)) { + if (mustWarn) { + warn(`FontFamily contains control characters: ${fontFamily}.`); + } + return false; + } } else { for (const ident of fontFamily.split(/[ \t]+/)) { if (/^(?:\d|-[\d-])/.test(ident) || !/^[\w\\-]+$/.test(ident)) { @@ -1626,6 +1662,9 @@ function validateFontName(fontFamily, mustWarn = false) { } return true; } +function normalizeCSSFontFamily(fontFamily) { + return fontFamily.replaceAll(/( +)(\d)?/g, (_, spaces, digit) => digit ?? " "); +} function validateCSSFont(cssFontInfo) { const DEFAULT_CSS_FONT_OBLIQUE = "14"; const DEFAULT_CSS_FONT_WEIGHT = "400"; @@ -2076,9 +2115,6 @@ class ColorSpace { destOffset += 3 + alpha01; } } - getOutputLength(inputLength, alpha01) { - unreachable("Should not call ColorSpace.getOutputLength"); - } isPassthrough(bits) { return false; } @@ -2212,9 +2248,6 @@ class AlternateCS extends ColorSpace { base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01); } } - getOutputLength(inputLength, alpha01) { - return this.base.getOutputLength(inputLength * this.base.numComps / this.numComps, alpha01); - } } class PatternCS extends ColorSpace { constructor(baseCS) { @@ -2265,9 +2298,6 @@ class IndexedCS extends ColorSpace { destOffset += alpha01; } } - getOutputLength(inputLength, alpha01) { - return inputLength * (3 + alpha01); - } isDefaultDecode(decode, bpc) { if (isDefaultDecodeHelper(decode, 2)) { return true; @@ -2299,9 +2329,6 @@ class DeviceGrayCS extends ColorSpace { q += alpha01; } } - getOutputLength(inputLength, alpha01) { - return inputLength * (3 + alpha01); - } } class DeviceRgbCS extends ColorSpace { constructor() { @@ -2327,9 +2354,6 @@ class DeviceRgbCS extends ColorSpace { q += alpha01; } } - getOutputLength(inputLength, alpha01) { - return inputLength * (3 + alpha01) / 3 | 0; - } isPassthrough(bits) { return bits === 8; } @@ -2338,9 +2362,6 @@ class DeviceRgbaCS extends ColorSpace { constructor() { super("DeviceRGBA", 4); } - getOutputLength(inputLength, _alpha01) { - return inputLength * 4; - } isPassthrough(bits) { return bits === 8; } @@ -2376,9 +2397,6 @@ class DeviceCmykCS extends ColorSpace { destOffset += 3 + alpha01; } } - getOutputLength(inputLength, alpha01) { - return inputLength / 4 * (3 + alpha01) | 0; - } } class CalGrayCS extends ColorSpace { constructor(whitePoint, blackPoint, gamma) { @@ -2424,9 +2442,6 @@ class CalGrayCS extends ColorSpace { destOffset += 3 + alpha01; } } - getOutputLength(inputLength, alpha01) { - return inputLength * (3 + alpha01); - } } class CalRGBCS extends ColorSpace { static #BRADFORD_SCALE_MATRIX = new Float32Array([0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296]); @@ -2575,9 +2590,6 @@ class CalRGBCS extends ColorSpace { destOffset += 3 + alpha01; } } - getOutputLength(inputLength, alpha01) { - return inputLength * (3 + alpha01) / 3 | 0; - } } class LabCS extends ColorSpace { constructor(whitePoint, blackPoint, range) { @@ -2659,9 +2671,6 @@ class LabCS extends ColorSpace { destOffset += 3 + alpha01; } } - getOutputLength(inputLength, alpha01) { - return inputLength * (3 + alpha01) / 3 | 0; - } isDefaultDecode(decode, bpc) { return true; } @@ -2758,9 +2767,6 @@ class IccColorSpace extends ColorSpace { qcms_convert_array(this.#transformer, src, alpha01 === 1); QCMS._destBuffer = null; } - getOutputLength(inputLength, alpha01) { - return inputLength / this.numComps * (3 + alpha01) | 0; - } static setOptions({ useWasm, useWorkerFetch, @@ -2836,10 +2842,7 @@ class Stream extends BaseStream { return this.length === 0; } getByte() { - if (this.pos >= this.end) { - return -1; - } - return this.bytes[this.pos++]; + return this.pos >= this.end ? -1 : this.bytes[this.pos++]; } getBytes(length) { const pos = this.pos; @@ -3039,10 +3042,7 @@ class ChunkedStream extends Stream { }; Object.defineProperty(ChunkedStreamSubstream.prototype, "isDataLoaded", { get() { - if (this.numChunksLoaded === this.numChunks) { - return true; - } - return this.getMissingChunks().length === 0; + return this.numChunksLoaded === this.numChunks || this.getMissingChunks().length === 0; }, configurable: true }); @@ -3425,12 +3425,14 @@ class ImageResizer { const maxArea = this.MAX_AREA = this.#goodSquareLength ** 2; return area > maxArea; } - static getReducePowerForJPX(width, height, componentsCount) { + static getReducePower(width, height, maxArea = Infinity) { + if (!Number.isInteger(width) || width <= 0 || !Number.isInteger(height) || height <= 0) { + return 0; + } const area = width * height; - const maxJPXArea = 2 ** 30 / (componentsCount * 4); if (!this.needsToBeResized(width, height)) { - if (area > maxJPXArea) { - return Math.ceil(Math.log2(area / maxJPXArea)); + if (area > maxArea) { + return Math.ceil(Math.log2(area / maxArea)); } return 0; } @@ -3438,8 +3440,11 @@ class ImageResizer { MAX_DIM, MAX_AREA } = this; - const minFactor = Math.max(width / MAX_DIM, height / MAX_DIM, Math.sqrt(area / Math.min(maxJPXArea, MAX_AREA))); - return Math.ceil(Math.log2(minFactor)); + const minFactor = Math.max(width / MAX_DIM, height / MAX_DIM, Math.sqrt(area / Math.min(maxArea, MAX_AREA))); + return Math.max(0, Math.ceil(Math.log2(minFactor))); + } + static getReducePowerForJPX(width, height, componentsCount) { + return this.getReducePower(width, height, 2 ** 30 / (componentsCount * 4)); } static get MAX_DIM() { return shadow(this, "MAX_DIM", this._guessMax(MIN_IMAGE_DIM, MAX_IMAGE_DIM, 0, 1)); @@ -3832,10 +3837,7 @@ class DecodeStream extends BaseStream { } async getImageData(length, decoderOptions) { if (!this.canAsyncDecodeImageFromBuffer) { - if (this.isAsyncDecoder) { - return this.decodeImage(null, length, decoderOptions); - } - return this.getBytes(length, decoderOptions); + return this.isAsyncDecoder ? this.decodeImage(null, length, decoderOptions) : this.getBytes(length, decoderOptions); } const data = await this.stream.asyncGetBytes(); return this.decodeImage(data, length, decoderOptions); @@ -4813,16 +4815,17 @@ function skipData(data, view, offset) { return endOffset; } class JpegImage { - constructor({ - decodeTransform = null, - colorTransform = -1 - } = {}) { - this._decodeTransform = decodeTransform; - this._colorTransform = colorTransform; + constructor(options) { + this._colorTransform = options?.colorTransform ?? -1; } static canUseImageDecoder(data, colorTransform = -1) { const view = new DataView(data.buffer, data.byteOffset, data.byteLength); - let exifOffsets = null; + const info = { + width: 0, + height: 0, + exifStart: 0, + exifEnd: 0 + }; let offset = 0; let numComponents = null; let fileMarker = view.getUint16(offset); @@ -4842,13 +4845,11 @@ class JpegImage { } = readDataBlock(data, view, offset); offset = newOffset; if (appData[0] === 0x45 && appData[1] === 0x78 && appData[2] === 0x69 && appData[3] === 0x66 && appData[4] === 0 && appData[5] === 0) { - if (exifOffsets) { + if (info.exifStart) { throw new JpegError("Duplicate EXIF-blocks found."); } - exifOffsets = { - exifStart: oldOffset + 6, - exifEnd: newOffset - }; + info.exifStart = oldOffset + 6; + info.exifEnd = newOffset; } fileMarker = view.getUint16(offset); offset += 2; @@ -4856,6 +4857,8 @@ class JpegImage { case 0xffc0: case 0xffc1: case 0xffc2: + info.height = view.getUint16(offset + (2 + 1)); + info.width = view.getUint16(offset + (2 + 1 + 2)); numComponents = data[offset + (2 + 1 + 2 + 2)]; break markerLoop; case 0xffff: @@ -4874,7 +4877,7 @@ class JpegImage { if (numComponents === 3 && colorTransform === 0) { return null; } - return exifOffsets || {}; + return info; } parse(data, { dnlScanLines = null @@ -5128,7 +5131,7 @@ class JpegImage { this.numComponents = this.components.length; return undefined; } - #getLinearizedBlockData(width, height, isSourcePDF) { + #getLinearizedBlockData(width, height) { const scaleX = this.width / width, scaleY = this.height / height; let component, componentScaleX, componentScaleY, blocksPerScanline; @@ -5165,14 +5168,6 @@ class JpegImage { } } } - let transform = this._decodeTransform; - if (transform) { - for (i = 0; i < dataLength;) { - for (j = 0, k = 0; j < numComponents; j++, i++, k += 2) { - data[i] = (data[i] * transform[k] >> 8) + transform[k + 1]; - } - } - } return data; } get _isColorConversionNeeded() { @@ -5254,13 +5249,12 @@ class JpegImage { width, height, forceRGBA = false, - forceRGB = false, - isSourcePDF = true + forceRGB = false }) { if (this.numComponents > 4) { throw new JpegError("Unsupported color mode"); } - const data = this.#getLinearizedBlockData(width, height, isSourcePDF); + const data = this.#getLinearizedBlockData(width, height); if (this.numComponents === 1 && (forceRGBA || forceRGB)) { const len = data.length * (forceRGBA ? 4 : 3); const rgbaData = new Uint8ClampedArray(len); @@ -5305,6 +5299,7 @@ class JpegImage { + class JpegStream extends DecodeStream { static #isImageDecoderSupported = FeatureTest.isImageDecoderSupported; constructor(stream, maybeLength, params) { @@ -5331,27 +5326,8 @@ class JpegStream extends DecodeStream { } get jpegOptions() { const jpegOptions = { - decodeTransform: undefined, colorTransform: undefined }; - const decodeArr = this.dict.getArray("D", "Decode"); - if ((this.forceRGBA || this.forceRGB) && Array.isArray(decodeArr)) { - const bitsPerComponent = this.dict.get("BPC", "BitsPerComponent") || 8; - const decodeArrLength = decodeArr.length; - const transform = new Int32Array(decodeArrLength); - let transformNeeded = false; - const maxValue = (1 << bitsPerComponent) - 1; - for (let i = 0; i < decodeArrLength; i += 2) { - transform[i] = (decodeArr[i + 1] - decodeArr[i]) * 256 | 0; - transform[i + 1] = decodeArr[i] * maxValue | 0; - if (transform[i] !== 256 || transform[i + 1] !== 0) { - transformNeeded = true; - } - } - if (transformNeeded) { - jpegOptions.decodeTransform = transform; - } - } if (this.params instanceof Dict) { const colorTransform = this.params.get("ColorTransform"); if (Number.isInteger(colorTransform)) { @@ -5392,14 +5368,11 @@ class JpegStream extends DecodeStream { get canAsyncDecodeImageFromBuffer() { return this.stream.isAsync; } - async getTransferableImage() { + async getTransferableImage(width, height) { if (!(await JpegStream.canUseImageDecoder)) { return null; } const jpegOptions = this.jpegOptions; - if (jpegOptions.decodeTransform) { - return null; - } let decoder; try { const bytes = this.canAsyncDecodeImageFromBuffer && (await this.stream.asyncGetBytes()) || this.bytes; @@ -5411,15 +5384,29 @@ class JpegStream extends DecodeStream { if (!useImageDecoder) { return null; } + const { + width: frameWidth, + height: frameHeight + } = useImageDecoder; + const reducePower = ImageResizer.getReducePower(frameWidth, frameHeight); + if ((frameWidth !== width || frameHeight !== height) && (reducePower || !frameHeight)) { + return null; + } if (useImageDecoder.exifStart) { data = data.slice(); data.fill(0x00, useImageDecoder.exifStart, useImageDecoder.exifEnd); } - decoder = new ImageDecoder({ + const init = { data, type: "image/jpeg", preferAnimation: false - }); + }; + if (reducePower) { + const factor = 2 ** reducePower; + init.desiredWidth = Math.ceil(frameWidth / factor); + init.desiredHeight = Math.ceil(frameHeight / factor); + } + decoder = new ImageDecoder(init); return (await decoder.decode()).image; } catch (reason) { warn(`getTransferableImage - failed: "${reason}".`); @@ -10913,10 +10900,9 @@ class LZWStream extends DecodeStream { decodedSizeDelta = blockSize; let estimatedDecodedSize = blockSize * 2; let i, j, q; - const lzwState = this.lzwState; - if (!lzwState) { - return; - } + const { + lzwState + } = this; const earlyChange = lzwState.earlyChange; let nextCode = lzwState.nextCode; const dictionaryValues = lzwState.dictionaryValues; @@ -11179,7 +11165,7 @@ class RunLengthStream extends DecodeStream { } readBlock() { const repeatHeader = this.stream.getBytes(2); - if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] === 128) { + if (repeatHeader.length < 2 || repeatHeader[0] === 128) { this.eof = true; return; } @@ -11234,6 +11220,8 @@ function getInlineImageCacheKey(bytes) { return ii + "_" + String.fromCharCode.apply(null, strBuf); } class Parser { + #imageCache = null; + #imageId = 0; constructor({ lexer, xref, @@ -11244,8 +11232,6 @@ class Parser { this.xref = xref; this.allowStreams = allowStreams; this.recoveryMode = recoveryMode; - this.imageCache = Object.create(null); - this._imageId = 0; this.refill(); } refill() { @@ -11332,10 +11318,7 @@ class Parser { return buf1; } if (typeof buf1 === "string") { - if (cipherTransform) { - return cipherTransform.decryptString(buf1); - } - return buf1; + return cipherTransform ? cipherTransform.decryptString(buf1) : buf1; } return buf1; } @@ -11577,7 +11560,7 @@ class Parser { makeInlineImage(cipherTransform) { const lexer = this.lexer; const stream = lexer.stream; - const dictMap = Object.create(null); + const dict = new Dict(this.xref); let dictLength; while (!isCmd(this.buf1, "ID") && this.buf1 !== EOF) { if (!(this.buf1 instanceof Name)) { @@ -11588,12 +11571,12 @@ class Parser { if (this.buf1 === EOF) { break; } - dictMap[key] = this.getObj(cipherTransform); + dict.set(key, this.getObj(cipherTransform)); } if (lexer.beginInlineImagePos !== -1) { dictLength = stream.pos - lexer.beginInlineImagePos; } - const filter = this.#fetchIfRef(dictMap.F || dictMap.Filter); + const filter = dict.get("F", "Filter"); let filterName; if (filter instanceof Name) { filterName = filter.name; @@ -11627,27 +11610,23 @@ class Parser { stream.pos = lexer.beginInlineImagePos; cacheKey = getInlineImageCacheKey(stream.getBytes(dictLength + length)); stream.pos = initialStreamPos; - const cacheEntry = this.imageCache[cacheKey]; - if (cacheEntry !== undefined) { + const cacheEntry = this.#imageCache?.get(cacheKey); + if (cacheEntry) { this.buf2 = Cmd.get("EI"); this.shift(); cacheEntry.reset(); return cacheEntry; } } - const dict = new Dict(this.xref); - for (const key in dictMap) { - dict.set(key, dictMap[key]); - } let imageStream = stream.makeSubStream(startPos, length, dict); if (cipherTransform && !this.#hasCryptFilter(filter)) { imageStream = cipherTransform.createStream(imageStream, length); } imageStream = this.filter(imageStream, dict, length, cipherTransform); imageStream.dict = dict; - if (cacheKey !== undefined) { - imageStream.cacheKey = `inline_img_${++this._imageId}`; - this.imageCache[cacheKey] = imageStream; + if (cacheKey) { + imageStream.cacheKey = `inline_img_${++this.#imageId}`; + (this.#imageCache ??= new Map()).set(cacheKey, imageStream); } this.buf2 = Cmd.get("EI"); this.shift(); @@ -11657,15 +11636,7 @@ class Parser { return this.xref ? this.xref.fetchIfRef(obj) : obj; } #hasCryptFilter(filter) { - if (!Array.isArray(filter)) { - return isName(filter, "Crypt"); - } - for (const f of filter) { - if (isName(this.#fetchIfRef(f), "Crypt")) { - return true; - } - } - return false; + return Array.isArray(filter) ? filter.some(f => isName(this.#fetchIfRef(f), "Crypt")) : isName(filter, "Crypt"); } #findStreamLength(startPos) { const { @@ -17308,6 +17279,9 @@ const getSpecialPUASymbols = getLookupTableFactory(function (t) { t[63194] = 0x00ae; t[63722] = 0x2122; t[63195] = 0x2122; + t[63718] = 0x23d0; + t[63719] = 0x23af; + t[63733] = 0x23ae; t[63729] = 0x23a7; t[63730] = 0x23a8; t[63731] = 0x23a9; @@ -18816,10 +18790,7 @@ class CFFFDSelect { this.fdSelect = fdSelect; } getFDIndex(glyphIndex) { - if (glyphIndex < 0 || glyphIndex >= this.fdSelect.length) { - return -1; - } - return this.fdSelect[glyphIndex]; + return glyphIndex < 0 || glyphIndex >= this.fdSelect.length ? -1 : this.fdSelect[glyphIndex]; } } class CFFOffsetTracker { @@ -19241,6 +19212,7 @@ class CFFCompiler { ;// ./src/core/standard_fonts.js + const getStdFontMap = getLookupTableFactory(function (t) { t["Times-Roman"] = "Times-Roman"; t.Helvetica = "Helvetica"; @@ -19531,6 +19503,16 @@ const getSymbolsFonts = getLookupTableFactory(function (t) { t["Wingdings-Bold"] = true; t["Wingdings-Regular"] = true; }); +const getGlyphMapForMacOrderedFonts = getLookupTableFactory(function (t) { + const glyphsUnicode = getGlyphsUnicode(); + t[2] = 10; + for (let gid = 3; gid < MacStandardGlyphOrdering.length; gid++) { + const unicode = glyphsUnicode[MacStandardGlyphOrdering[gid]]; + if (unicode !== undefined) { + t[gid] = unicode; + } + } +}); const getGlyphMapForStandardFonts = getLookupTableFactory(function (t) { t[2] = 10; t[3] = 32; @@ -20029,6 +20011,83 @@ const getGlyphMapForStandardFonts = getLookupTableFactory(function (t) { t[3393] = 1159; t[3416] = 8377; }); +const getSupplementalGlyphMapForTrebuchetMS = getLookupTableFactory(function (t) { + t[151] = 956; + t[159] = 937; + t[168] = 916; + t[189] = 8364; + t[195] = 8729; + t[218] = 713; + t[236] = 222; + t[237] = 254; + t[238] = 8722; + t[239] = 185; + t[240] = 178; + t[241] = 179; + t[242] = 189; + t[243] = 188; + t[244] = 190; + t[245] = 181; + t[246] = 8486; + t[247] = 8710; + t[248] = 253; + t[249] = 215; + t[250] = 173; + t[253] = 8355; + t[254] = 286; + t[255] = 287; + t[256] = 304; + t[257] = 350; + t[258] = 351; + t[259] = 262; + t[260] = 263; + t[261] = 268; + t[262] = 269; + t[263] = 273; + t[264] = 175; + t[266] = 183; + t[267] = 258; + t[268] = 259; + t[269] = 260; + t[270] = 261; + t[271] = 270; + t[272] = 271; + t[273] = 272; + t[274] = 280; + t[275] = 281; + t[276] = 282; + t[277] = 283; + t[278] = 313; + t[279] = 314; + t[280] = 317; + t[281] = 318; + t[282] = 319; + t[283] = 320; + t[284] = 323; + t[285] = 324; + t[286] = 327; + t[287] = 328; + t[288] = 336; + t[289] = 337; + t[290] = 340; + t[291] = 341; + t[292] = 344; + t[293] = 345; + t[294] = 346; + t[295] = 347; + t[296] = 538; + t[297] = 539; + t[298] = 356; + t[299] = 357; + t[300] = 366; + t[301] = 367; + t[302] = 368; + t[303] = 369; + t[304] = 377; + t[305] = 378; + t[306] = 379; + t[307] = 380; +}); const getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function (t) { t[227] = 322; t[264] = 261; @@ -20856,10 +20915,7 @@ class IdentityToUnicodeMap { return this.firstChar <= i && i <= this.lastChar; } get(i) { - if (this.firstChar <= i && i <= this.lastChar) { - return String.fromCharCode(i); - } - return undefined; + return this.firstChar <= i && i <= this.lastChar ? String.fromCharCode(i) : undefined; } charCodeOf(v) { return Number.isInteger(v) && v >= this.firstChar && v <= this.lastChar ? v : -1; @@ -20973,6 +21029,7 @@ class CFFFont { } ;// ./src/shared/obj_bin_transform_utils.js + class CSS_FONT_INFO { static strings = ["fontFamily", "fontWeight", "italicAngle"]; } @@ -20999,12 +21056,22 @@ class PATTERN_INFO { static N_STOP = 12; static N_FIGURES = 16; } +class InfoUtils { + static get decoder() { + return shadow(this, "decoder", new TextDecoder()); + } + static get encoder() { + return shadow(this, "encoder", new TextEncoder()); + } +} ;// ./src/core/obj_bin_transform_core.js function compileCssFontInfo(info) { - const encoder = new TextEncoder(); + const { + encoder + } = InfoUtils; const encodedStrings = {}; let stringsLength = 0; for (const prop of CSS_FONT_INFO.strings) { @@ -21027,7 +21094,9 @@ function compileCssFontInfo(info) { return buffer; } function compileSystemFontInfo(info) { - const encoder = new TextEncoder(); + const { + encoder + } = InfoUtils; const encodedStrings = {}; let stringsLength = 0; for (const prop of SYSTEM_FONT_INFO.strings) { @@ -21075,7 +21144,9 @@ function compileSystemFontInfo(info) { function compileFontInfo(font) { const systemFontInfoBuffer = font.systemFontInfo ? compileSystemFontInfo(font.systemFontInfo) : null; const cssFontInfoBuffer = font.cssFontInfo ? compileCssFontInfo(font.cssFontInfo) : null; - const encoder = new TextEncoder(); + const { + encoder + } = InfoUtils; const encodedStrings = {}; let stringsLength = 0; for (const prop of FONT_INFO.strings) { @@ -26258,6 +26329,7 @@ class Type1Font { + const PRIVATE_USE_AREAS = [[0xe000, 0xf8ff], [0x100000, 0x10fffd]]; const PDF_GLYPH_SPACE_UNITS = 1000; const EXPORT_DATA_PROPERTIES = ["ascent", "bbox", "black", "bold", "cssFontInfo", "data", "defaultVMetrics", "defaultWidth", "descent", "disableFontFace", "fallbackName", "fontExtraProperties", "fontMatrix", "isInvalidPDFjsFont", "isType3Font", "italic", "loadedName", "mimetype", "missingFile", "name", "remeasure", "systemFontInfo", "vertical"]; @@ -26469,6 +26541,14 @@ function applyStandardFontGlyphMap(map, glyphMap) { map[+charCode] = glyphMap[charCode]; } } +const getSymbolGlyphIdEncoding = getLookupTableFactory(t => { + let glyphId = 3; + for (const [firstCharCode, lastCharCode] of [[0x20, 0x7e], [0xa1, 0xfe]]) { + for (let charCode = firstCharCode; charCode <= lastCharCode; charCode++) { + t[glyphId++] = SymbolSetEncoding[charCode]; + } + } +}, true); function buildToFontChar(encoding, glyphsUnicodeMap, differences) { const toFontChar = []; let unicode; @@ -26901,7 +26981,7 @@ function createPostscriptName(name) { function createNameTable(name, proto) { proto ||= [[], []]; const strings = [proto[0][0] || "Original licence", proto[0][1] || name, proto[0][2] || "Unknown", proto[0][3] || "uniqueID", proto[0][4] || name, proto[0][5] || "Version 0.11", proto[0][6] || createPostscriptName(name), proto[0][7] || "Unknown", proto[0][8] || "Unknown", proto[0][9] || "Unknown"]; - const stringsBytes = strings.map(s => stringToBytes(s)); + const stringsBytes = strings.map(stringToBytes); const stringsUnicodeBytes = new Array(strings.length); let i, ii, j, jj, str; for (i = 0, ii = strings.length; i < ii; i++) { @@ -27140,11 +27220,16 @@ class Font { if ((isStandardFont || isMappedToStandardFont) && type === "CIDFontType2" && this.cidEncoding.startsWith("Identity-")) { const cidToGidMap = properties.cidToGidMap; const map = []; - applyStandardFontGlyphMap(map, getGlyphMapForStandardFonts()); - if (/Arial-?Black/i.test(name)) { - applyStandardFontGlyphMap(map, getSupplementalGlyphMapForArialBlack()); - } else if (/Calibri/i.test(name)) { - applyStandardFontGlyphMap(map, getSupplementalGlyphMapForCalibri()); + if (/Trebuchet/i.test(name)) { + applyStandardFontGlyphMap(map, getGlyphMapForMacOrderedFonts()); + applyStandardFontGlyphMap(map, getSupplementalGlyphMapForTrebuchetMS()); + } else { + applyStandardFontGlyphMap(map, getGlyphMapForStandardFonts()); + if (/Arial-?Black/i.test(name)) { + applyStandardFontGlyphMap(map, getSupplementalGlyphMapForArialBlack()); + } else if (/Calibri/i.test(name)) { + applyStandardFontGlyphMap(map, getSupplementalGlyphMapForCalibri()); + } } if (cidToGidMap) { for (const charCode in map) { @@ -27170,7 +27255,8 @@ class Font { this.toFontChar = map; this.toUnicode = new ToUnicodeMap(map); } else if (/Symbol/i.test(fontName)) { - this.toFontChar = buildToFontChar(SymbolSetEncoding, getGlyphsUnicode(), this.differences); + const isCidKeyed = this.composite && this.cidEncoding.startsWith("Identity-"); + this.toFontChar = buildToFontChar(isCidKeyed ? getSymbolGlyphIdEncoding() : SymbolSetEncoding, getGlyphsUnicode(), this.differences); } else if (/Dingbats/i.test(fontName)) { this.toFontChar = buildToFontChar(ZapfDingbatsEncoding, getDingbatsGlyphsUnicode(), this.differences); } else if (isStandardFont || isMappedToStandardFont) { @@ -29296,7 +29382,7 @@ class lexer_Lexer { this.data = data; this.pos = 0; this.len = data.length; - this._numberPattern = /[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/iy; + this._numberPattern = /[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?/iy; this._identifierPattern = /[a-z]+/y; } _skipComment() { @@ -30994,7 +31080,7 @@ class PSStackBasedInterpreter { const base = this.#sp - nOut; for (let i = 0; i < nOut; i++) { const v = base + i >= 0 ? this.#stack[base + i] : 0; - dest[destOffset + i] = MathClamp(range[i * 2 + 1], range[i * 2], v); + dest[destOffset + i] = MathClamp(v, range[i * 2], range[i * 2 + 1]); } }; } @@ -31013,6 +31099,7 @@ function buildPostScriptJsFunction(source, domain, range, forceInterpreter = fal ;// ./src/core/postscript/wasm_compiler.js + const wasm_compiler_OP = { if: 0x04, else: 0x05, @@ -31078,7 +31165,7 @@ function unsignedLEB128(n) { return out; } function encodeASCIIString(s) { - return [...unsignedLEB128(s.length), ...Array.from(s, c => c.charCodeAt(0))]; + return [...unsignedLEB128(s.length), ...stringToBytes(s)]; } function section(id, data) { return [id, ...unsignedLEB128(data.length), ...data]; @@ -31809,7 +31896,7 @@ class BaseLocalCache { this._nameRefMap = new Map(); this._imageMap = new Map(); } - this._imageCache = new RefSetCache(); + this._imageCache = new RefMap(); } getByName(name) { if (this._onlyRefs) { @@ -31960,8 +32047,8 @@ class GlobalImageCache { static MAX_BYTE_SIZE = 5e7; #decodeFailedSet = new RefSet(); constructor() { - this._refCache = new RefSetCache(); - this._imageCache = new RefSetCache(); + this._refCache = new RefMap(); + this._imageCache = new RefMap(); } get #byteSize() { let byteSize = 0; @@ -33675,14 +33762,14 @@ class PDFImage { } return imgData; } - if (!forceRGBA) { + if (!forceRGBA && !this.smask && !this.mask) { let kind; if (this.colorSpace.name === "DeviceGray" && bpc === 1) { kind = ImageKind.GRAYSCALE_1BPP; } else if (this.colorSpace.name === "DeviceRGB" && bpc === 8 && !this.needsDecode) { kind = ImageKind.RGB_24BPP; } - if (kind && !this.smask && !this.mask && drawWidth === originalWidth && drawHeight === originalHeight) { + if (kind && drawWidth === originalWidth && drawHeight === originalHeight) { const image = await this.#getImage(originalWidth, originalHeight); if (image) { return image; @@ -33713,28 +33800,32 @@ class PDFImage { } return imgData; } - if (this.image instanceof JpegStream && !this.smask && !this.mask && !this.needsDecode) { - let imageLength = originalHeight * rowBytes; - if (isOffscreenCanvasSupported && !mustBeResized) { - let isHandled = false; - switch (this.colorSpace.name) { - case "DeviceGray": - imageLength *= 4; - isHandled = true; - break; - case "DeviceRGB": - imageLength = imageLength / 3 * 4; - isHandled = true; - break; - case "DeviceCMYK": - isHandled = true; - break; - } - if (isHandled) { + if (this.image instanceof JpegStream && !this.needsDecode) { + let isHandled = false; + switch (this.colorSpace.name) { + case "DeviceGray": + case "DeviceRGB": + case "DeviceCMYK": + isHandled = true; + break; + } + if (isHandled) { + if (isOffscreenCanvasSupported) { const image = await this.#getImage(drawWidth, drawHeight); if (image) { return image; } + } + let imageLength = originalHeight * rowBytes; + if (isOffscreenCanvasSupported && !mustBeResized) { + switch (this.colorSpace.name) { + case "DeviceGray": + imageLength *= 4; + break; + case "DeviceRGB": + imageLength = imageLength / 3 * 4; + break; + } const rgba = await this.getImageBytes(imageLength, { drawWidth, drawHeight, @@ -33743,24 +33834,20 @@ class PDFImage { }); return this.createBitmap(ImageKind.RGBA_32BPP, drawWidth, drawHeight, rgba); } - } else { - switch (this.colorSpace.name) { - case "DeviceGray": - imageLength *= 3; - case "DeviceRGB": - case "DeviceCMYK": - imgData.kind = ImageKind.RGB_24BPP; - imgData.data = await this.getImageBytes(imageLength, { - drawWidth, - drawHeight, - forceRGB: true, - internal: mustBeResized - }); - if (mustBeResized) { - return ImageResizer.createImage(imgData); - } - return imgData; + if (this.colorSpace.name === "DeviceGray") { + imageLength *= 3; + } + imgData.kind = ImageKind.RGB_24BPP; + imgData.data = await this.getImageBytes(imageLength, { + drawWidth, + drawHeight, + forceRGB: true, + internal: mustBeResized + }); + if (mustBeResized) { + return ImageResizer.createImage(imgData); } + return imgData; } } } @@ -33942,14 +34029,14 @@ class PDFImage { }; } async #getImage(width, height) { - const bitmap = await this.image.getTransferableImage(); + const bitmap = await this.image.getTransferableImage(width, height); if (!bitmap) { return null; } return { data: null, - width, - height, + width: bitmap.displayWidth ?? width, + height: bitmap.displayHeight ?? height, bitmap, interpolate: this.interpolate }; @@ -34586,6 +34673,17 @@ class PartialEvaluator { } } } + #createTransferMap(fn) { + const transferFn = this._pdfFunctionFactory.create(fn), + tmp = new Float32Array(1); + return Uint8Array.from({ + length: 256 + }, (_, i) => { + tmp[0] = i / 255; + transferFn(tmp, 0, tmp, 0); + return tmp[0] * 255 | 0; + }); + } handleSMask(smask, resources, operatorList, task, stateManager, localColorSpaceCache, seenRefs) { const smaskContent = smask.get("G"); const smaskOptions = { @@ -34594,15 +34692,7 @@ class PartialEvaluator { }; const transferObj = smask.get("TR"); if (isPDFFunction(transferObj)) { - const transferFn = this._pdfFunctionFactory.create(transferObj); - const transferMap = new Uint8Array(256); - const tmp = new Float32Array(1); - for (let i = 0; i < 256; i++) { - tmp[0] = i / 255; - transferFn(tmp, 0, tmp, 0); - transferMap[i] = tmp[0] * 255 | 0; - } - smaskOptions.transferMap = transferMap; + smaskOptions.transferMap = this.#createTransferMap(transferObj); } return this.buildFormXObject(resources, smaskContent, smaskOptions, operatorList, task, stateManager.state.clone({ newPath: true @@ -34611,10 +34701,7 @@ class PartialEvaluator { handleTransferFunction(tr) { let transferArray; if (Array.isArray(tr)) { - transferArray = tr; - if (tr.length > 1 && tr.every(map => map === tr[0])) { - transferArray = [tr[0]]; - } + transferArray = tr.length > 1 && tr.every(map => map === tr[0]) ? [tr[0]] : tr; } else if (isPDFFunction(tr)) { transferArray = [tr]; } else { @@ -34632,15 +34719,7 @@ class PartialEvaluator { } else if (!isPDFFunction(transferObj)) { return null; } - const transferFn = this._pdfFunctionFactory.create(transferObj); - const transferMap = new Uint8Array(256), - tmp = new Float32Array(1); - for (let j = 0; j < 256; j++) { - tmp[0] = j / 255; - transferFn(tmp, 0, tmp, 0); - transferMap[j] = tmp[0] * 255 | 0; - } - transferMaps.push(transferMap); + transferMaps.push(this.#createTransferMap(transferObj)); numEffectfulFns++; } if (!(numFns === 1 || numFns === 4)) { @@ -34781,11 +34860,11 @@ class PartialEvaluator { } break; case "TR": + if (gState.has("TR2")) { + break; + } case "TR2": { - if (key === "TR" && gState.has("TR2")) { - break; - } const transferMaps = this.handleTransferFunction(value); gStateObj.push(["TR", transferMaps]); break; @@ -35149,11 +35228,17 @@ class PartialEvaluator { const stateManager = new StateManager(initialState); const preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager); const timeSlotManager = new TimeSlotManager(); + let markedContentLevel = 0; function closePendingRestoreOPS(argument) { for (let i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) { operatorList.addOp(OPS.restore, []); } } + function closePendingMarkedContentOPS() { + for (; markedContentLevel > 0; markedContentLevel--) { + operatorList.addOp(OPS.endMarkedContent, []); + } + } return new Promise(function promiseBody(resolve, reject) { const next = function (promise) { Promise.all([promise, operatorList.ready]).then(function () { @@ -35167,7 +35252,7 @@ class PartialEvaluator { task.ensureNotTerminated(); timeSlotManager.reset(); const operation = {}; - let stop, i, ii, cs, name, isValidName; + let stop, cs, name, isValidName; while (!(stop = timeSlotManager.check())) { operation.args = null; if (!preprocessor.read(operation)) { @@ -35607,6 +35692,7 @@ class PartialEvaluator { case OPS.endCompat: continue; case OPS.beginMarkedContentProps: + markedContentLevel++; if (!(args[0] instanceof Name)) { warn(`Expected name for beginMarkedContentProps arg0=${args[0]}`); operatorList.addOp(OPS.beginMarkedContentProps, ["OC", null]); @@ -35631,18 +35717,26 @@ class PartialEvaluator { args = [args[0].name, args[1] instanceof Dict ? args[1].get("MCID") : null]; break; case OPS.beginMarkedContent: + if (args?.some(arg => arg instanceof Dict)) { + warn(`getOperatorList - ignoring operator: ${fn}`); + continue; + } + markedContentLevel++; + break; case OPS.endMarkedContent: + if (args?.some(arg => arg instanceof Dict)) { + warn(`getOperatorList - ignoring operator: ${fn}`); + continue; + } + if (markedContentLevel === 0) { + continue; + } + markedContentLevel--; + break; default: - if (args !== null) { - for (i = 0, ii = args.length; i < ii; i++) { - if (args[i] instanceof Dict) { - break; - } - } - if (i < ii) { - warn("getOperatorList - ignoring operator: " + fn); - continue; - } + if (args?.some(arg => arg instanceof Dict)) { + warn(`getOperatorList - ignoring operator: ${fn}`); + continue; } } operatorList.addOp(fn, args); @@ -35651,6 +35745,7 @@ class PartialEvaluator { next(deferred); return; } + closePendingMarkedContentOPS(); closePendingRestoreOPS(); resolve(); }).catch(reason => { @@ -35659,6 +35754,7 @@ class PartialEvaluator { } if (this.options.ignoreErrors) { warn(`getOperatorList - ignoring errors during "${task.name}" ` + `task: "${reason}".`); + closePendingMarkedContentOPS(); closePendingRestoreOPS(); return; } @@ -35675,7 +35771,6 @@ class PartialEvaluator { seenStyles = new Set(), viewBox, lang = null, - markedContentData = null, disableNormalization = false, keepWhiteSpace = false, prevRefs = null, @@ -35698,11 +35793,8 @@ class PartialEvaluator { } resources ||= Dict.empty; stateManager ||= new StateManager(new TextState()); - if (includeMarkedContent) { - markedContentData ||= { - level: 0 - }; - } + let markedContentLevel = 0; + let textMarkedContentLevel = null; const textContent = { items: [], styles: Object.create(null), @@ -36168,6 +36260,17 @@ class PartialEvaluator { textContentItem.initialized = false; textContentItem.str.length = 0; } + function closePendingMarkedContentItems(level = 0) { + if (!includeMarkedContent || markedContentLevel <= level) { + return; + } + flushTextContentItem(); + for (; markedContentLevel > level; markedContentLevel--) { + textContent.items.push({ + type: "endMarkedContent" + }); + } + } function enqueueChunk(batch = false) { const length = textContent.items.length; if (length === 0) { @@ -36255,6 +36358,13 @@ class PartialEvaluator { case OPS.beginText: textState.textMatrix = IDENTITY_MATRIX.slice(); textState.textLineMatrix = IDENTITY_MATRIX.slice(); + textMarkedContentLevel = markedContentLevel; + break; + case OPS.endText: + if (textMarkedContentLevel !== null) { + closePendingMarkedContentItems(textMarkedContentLevel); + textMarkedContentLevel = null; + } break; case OPS.showSpacedText: if (!stateManager.state.font) { @@ -36376,7 +36486,6 @@ class PartialEvaluator { seenStyles, viewBox, lang, - markedContentData, disableNormalization, keepWhiteSpace, prevRefs: seenRefs @@ -36439,7 +36548,7 @@ class PartialEvaluator { case OPS.beginMarkedContent: flushTextContentItem(); if (includeMarkedContent) { - markedContentData.level++; + markedContentLevel++; textContent.items.push({ type: "beginMarkedContent", tag: args[0] instanceof Name ? args[0].name : null @@ -36449,7 +36558,7 @@ class PartialEvaluator { case OPS.beginMarkedContentProps: flushTextContentItem(); if (includeMarkedContent) { - markedContentData.level++; + markedContentLevel++; const mcid = args[1] instanceof Dict ? args[1].get("MCID") : null; textContent.items.push({ type: "beginMarkedContentProps", @@ -36461,10 +36570,10 @@ class PartialEvaluator { case OPS.endMarkedContent: flushTextContentItem(); if (includeMarkedContent) { - if (markedContentData.level === 0) { + if (markedContentLevel === 0) { break; } - markedContentData.level--; + markedContentLevel--; textContent.items.push({ type: "endMarkedContent" }); @@ -36481,6 +36590,7 @@ class PartialEvaluator { return; } flushTextContentItem(); + closePendingMarkedContentItems(); enqueueChunk(); resolve(); }).catch(reason => { @@ -36490,6 +36600,7 @@ class PartialEvaluator { if (this.options.ignoreErrors) { warn(`getTextContent - ignoring errors during "${task.name}" ` + `task: "${reason}".`); flushTextContentItem(); + closePendingMarkedContentItems(); enqueueChunk(); return; } @@ -37412,70 +37523,69 @@ class TranslatedFont { this.font.disableFontFace = true; PartialEvaluator.buildFontPaths(this.font, this.font.glyphCacheValues, handler, evaluatorOptions); } - loadType3Data(evaluator, resources, task, seenRefs = null) { + async loadType3Data(evaluator, resources, task, seenRefs = null) { if (this.#type3Loaded) { return this.#type3Loaded; } const { + dict, font, type3Dependencies } = this; assert(font.isType3Font, "Must be a Type3 font."); + const { + promise, + resolve + } = Promise.withResolvers(); + this.#type3Loaded = promise; const type3Evaluator = evaluator.clone({ ignoreErrors: false }); const type3FontRefs = new RefSet(evaluator.type3FontRefs); - if (this.dict.objId && !type3FontRefs.has(this.dict.objId)) { - type3FontRefs.put(this.dict.objId); + if (dict.objId) { + type3FontRefs.put(dict.objId); } type3Evaluator.type3FontRefs = type3FontRefs; - let loadCharProcsPromise = Promise.resolve(); - const charProcs = this.dict.get("CharProcs"); - const fontResources = this.dict.get("Resources") || resources; - const charProcOperatorList = Object.create(null); - const [x0, y0, x1, y1] = font.bbox, - width = x1 - x0, - height = y1 - y0; - const fontBBoxSize = Math.hypot(width, height); + const charProcs = dict.get("CharProcs"); + const fontResources = dict.get("Resources") || resources; + const charProcOperatorList = new Map(); + const [x0, y0, x1, y1] = font.bbox; + const fontBBoxSize = Math.hypot(x1 - x0, y1 - y0); for (const key of charProcs.getKeys()) { - loadCharProcsPromise = loadCharProcsPromise.then(() => { - const glyphStream = charProcs.get(key); + try { const operatorList = new OperatorList(); - return type3Evaluator.getOperatorList({ - stream: glyphStream, + await type3Evaluator.getOperatorList({ + stream: charProcs.get(key), task, resources: fontResources, operatorList, prevRefs: seenRefs - }).then(() => { - switch (operatorList.fnArray[0]) { - case OPS.setCharWidthAndBounds: - this.#removeType3ColorOperators(operatorList, fontBBoxSize); - break; - case OPS.setCharWidth: - if (!fontBBoxSize) { - this.#guessType3FontBBox(operatorList); - } - break; - } - charProcOperatorList[key] = operatorList.getIR(); - for (const dependency of operatorList.dependencies) { - type3Dependencies.add(dependency); - } - }).catch(function (reason) { - warn(`Type3 font resource "${key}" is not available.`); - const dummyOperatorList = new OperatorList(); - charProcOperatorList[key] = dummyOperatorList.getIR(); }); - }); - } - this.#type3Loaded = loadCharProcsPromise.then(() => { - font.charProcOperatorList = charProcOperatorList; - if (this._bbox) { - font.isCharBBox = true; - font.bbox = this._bbox; + switch (operatorList.fnArray[0]) { + case OPS.setCharWidthAndBounds: + this.#removeType3ColorOperators(operatorList, fontBBoxSize); + break; + case OPS.setCharWidth: + if (!fontBBoxSize) { + this.#guessType3FontBBox(operatorList); + } + break; + } + charProcOperatorList.set(key, operatorList.getIR()); + for (const dependency of operatorList.dependencies) { + type3Dependencies.add(dependency); + } + } catch { + warn(`Type3 font resource "${key}" is not available.`); + charProcOperatorList.set(key, new OperatorList().getIR()); } - }); + } + font.charProcOperatorList = charProcOperatorList; + if (this._bbox) { + font.isCharBBox = true; + font.bbox = this._bbox; + } + resolve(); return this.#type3Loaded; } #removeType3ColorOperators(operatorList, fontBBoxSize = NaN) { @@ -38729,9 +38839,6 @@ class FileSpec { return; } this.root = root; - if (root.has("FS")) { - this.fs = root.get("FS"); - } if (root.has("RF")) { warn("Related file specifications are not supported"); } @@ -38824,15 +38931,13 @@ function isWhitespaceString(s) { } class XMLParserBase { static get _entityRegex() { - return shadow(this, "_entityRegex", /&(?:#x([^;]+)|#([^;]+)|([^;]+));/g); + return shadow(this, "_entityRegex", /&(?:#x([^;&]+)|#([^;&]+)|([^;&]+));/g); } _resolveEntities(s) { - return s.replaceAll(XMLParserBase._entityRegex, (_, hex, dec, entity) => { - if (hex) { - return String.fromCodePoint(parseInt(hex, 16)); - } - if (dec) { - return String.fromCodePoint(parseInt(dec, 10)); + return s.replaceAll(XMLParserBase._entityRegex, (all, hex, dec, entity) => { + if (hex || dec) { + const code = hex ? parseInt(hex, 16) : parseInt(dec, 10); + return code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : all; } switch (entity) { case "lt": @@ -39055,10 +39160,7 @@ class SimpleDOMNode { return childNodes[index + 1]; } get textContent() { - if (!this.childNodes) { - return this.nodeValue || ""; - } - return this.childNodes.map(child => child.textContent).join(""); + return !this.childNodes ? this.nodeValue || "" : this.childNodes.map(child => child.textContent).join(""); } get children() { return this.childNodes || []; @@ -39411,6 +39513,7 @@ function soundStreamToWav(stream, samples) { const MAX_DEPTH = 40; +const TABLE_SPAN_ATTRIBUTES = [["RowSpan", "rowSpan"], ["ColSpan", "colSpan"]]; const StructElementType = { PAGE_CONTENT: 1, STREAM_CONTENT: 2, @@ -39461,15 +39564,14 @@ class StructTreeRoot { } return this.kidRefToPosition ? this.kidRefToPosition.get(kidRef) ?? NaN : -1; } - #addIdToPage(pageRef, id, type) { + #addIdToPage(pageRef, id, type, objId) { if (!(pageRef instanceof Ref) || id < 0) { return; } - this.structParentIds ||= new RefSetCache(); - this.structParentIds.getOrPutComputed(pageRef, makeArr).push([id, type]); + (this.structParentIds ??= new RefMap()).getOrPutComputed(pageRef, makeArr).push([id, type, objId]); } - addAnnotationIdToPage(pageRef, id) { - this.#addIdToPage(pageRef, id, StructElementType.ANNOTATION); + addAnnotationIdToPage(pageRef, id, ref) { + this.#addIdToPage(pageRef, id, StructElementType.ANNOTATION, ref instanceof Ref ? ref.toString() : null); } static async canCreateStructureTree({ catalogRef, @@ -39516,7 +39618,7 @@ class StructTreeRoot { changes }) { const root = await pdfManager.ensureCatalog("cloneDict"); - const cache = new RefSetCache(); + const cache = new RefMap(); cache.put(catalogRef, root); const structTreeRootRef = xref.getNewTemporaryRef(); root.set("StructTreeRoot", structTreeRootRef); @@ -39627,7 +39729,7 @@ class StructTreeRoot { xref } = this; const structTreeRoot = this.dict.clone(); - const cache = new RefSetCache(); + const cache = new RefMap(); cache.put(structTreeRootRef, structTreeRoot); let parentTreeRef = structTreeRoot.getRaw("ParentTree"); let parentTree; @@ -39912,16 +40014,120 @@ class StructElementNode { } return stringToUTF8String(fileStream.getString()); } - const A = this.dict.get("A"); - if (A instanceof Dict) { - const O = A.get("O"); - if (isName(O, "MSFT_Office")) { - const mathml = A.get("MSFT_MathML"); + for (const attributes of this.attributes) { + if (isName(attributes.get("O"), "MSFT_Office")) { + const mathml = attributes.get("MSFT_MathML"); return mathml ? stringToPDFString(mathml) : null; } } return null; } + #collectAttributes(value, attributes) { + const pending = [value]; + const visited = new RefSet(); + while (pending.length > 0) { + value = pending.pop(); + if (value instanceof Ref) { + if (visited.has(value)) { + continue; + } + visited.put(value); + value = this.xref.fetch(value); + } + if (value instanceof BaseStream) { + value = value.dict; + } + if (value instanceof Dict) { + attributes.push(value); + continue; + } + if (!Array.isArray(value)) { + continue; + } + for (let i = value.length - 1; i >= 0; i--) { + if (!Number.isInteger(value[i])) { + pending.push(value[i]); + } + } + } + } + get attributes() { + const attributes = []; + const classes = this.dict.getArray("C"); + if (classes !== undefined) { + const classMap = this.tree.rootDict?.get("ClassMap"); + if (classMap instanceof Dict) { + for (const className of Array.isArray(classes) ? classes : [classes]) { + if (className instanceof Name) { + this.#collectAttributes(classMap.getRaw(className.name), attributes); + } + } + } + } + this.#collectAttributes(this.dict.getRaw("A"), attributes); + return shadow(this, "attributes", attributes); + } + get tableAttributes() { + const { + role + } = this; + if (role !== "Table" && role !== "TH" && role !== "TD") { + return null; + } + const map = new Map(); + for (const attributes of this.attributes) { + if (!isName(attributes.get("O"), "Table")) { + continue; + } + if (role === "Table") { + if (attributes.has("Summary")) { + const summary = attributes.get("Summary"); + if (typeof summary === "string" && summary) { + map.set("summary", stringToPDFString(summary)); + } else { + map.delete("summary"); + } + } + continue; + } + for (const [key, name] of TABLE_SPAN_ATTRIBUTES) { + if (!attributes.has(key)) { + continue; + } + const value = attributes.get(key); + if (Number.isInteger(value) && value > 1) { + map.set(name, value); + } else { + map.delete(name); + } + } + if (attributes.has("Headers")) { + map.delete("headers"); + const headers = attributes.getArray("Headers"); + if (Array.isArray(headers)) { + const ids = headers.filter(header => typeof header === "string").map(stringToPDFString); + if (ids.length > 0) { + map.set("headers", ids); + } + } + } + if (role === "TH" && attributes.has("Scope")) { + map.delete("scope"); + const scope = attributes.get("Scope"); + if (scope instanceof Name && ["Row", "Column", "Both"].includes(scope.name)) { + map.set("scope", scope.name); + } + } + if (role === "TH" && attributes.has("Short")) { + map.delete("short"); + const short = attributes.get("Short"); + if (typeof short === "string" && short) { + map.set("short", stringToPDFString(short)); + } + } + } + return map.size ? map : null; + } parseKids() { let pageObjId = null; const objRef = this.dict.getRaw("Pg"); @@ -40066,12 +40272,18 @@ class StructTreePage { if (!ids) { return; } - for (const [elemId, type] of ids) { + for (const [elemId, type, objId] of ids) { const obj = parentTree.get(elemId); - if (obj) { - const elem = this.addNode(this.xref.fetchIfRef(obj), map); - if (elem?.kids?.length === 1 && elem.kids[0].type === StructElementType.OBJECT) { - elem.kids[0].type = type; + if (!obj) { + continue; + } + const elem = this.addNode(this.xref.fetchIfRef(obj), map); + if (!elem || !objId) { + continue; + } + for (const kid of elem.kids) { + if (kid.type === StructElementType.OBJECT && kid.refObjId === objId) { + kid.type = type; } } } @@ -40156,6 +40368,13 @@ class StructTreePage { if (typeof alt === "string") { obj.alt = stringToPDFString(alt); } + const structId = node.dict.get("ID"); + if (obj.role === "TH" && typeof structId === "string" && structId) { + obj.structId = stringToPDFString(structId); + } + node.tableAttributes?.forEach((val, key) => { + obj[key] = val; + }); if (obj.role === "Formula") { try { const { @@ -40171,19 +40390,19 @@ class StructTreePage { warn(`Ignoring mathML: "${ex}".`); } } - const a = node.dict.get("A"); - if (a instanceof Dict) { - const bbox = lookupNormalRect(a.getArray("BBox"), null); - if (bbox) { - obj.bbox = bbox; - } else { - const width = a.get("Width"); - const height = a.get("Height"); - if (typeof width === "number" && width > 0 && typeof height === "number" && height > 0) { - obj.bbox = [0, 0, width, height]; - } + let bbox = null, + size = null; + for (const a of node.attributes) { + bbox = lookupNormalRect(a.getArray("BBox"), bbox); + const width = a.get("Width"); + const height = a.get("Height"); + if (typeof width === "number" && width > 0 && typeof height === "number" && height > 0) { + size = [0, 0, width, height]; } } + if (bbox || size) { + obj.bbox = bbox ?? size; + } const lang = node.dict.get("Lang"); if (typeof lang === "string") { obj.lang = stringToPDFString(lang); @@ -40262,18 +40481,18 @@ function fetchRemoteDest(action) { } class Catalog { #actualNumPages = null; - #annotationAttachmentIdByRef = new RefSetCache(); + #annotationAttachmentIdByRef = new RefMap(); #annotationAttachmentRefById = new Map(); #soundAttachmentIds = new Set(); #catDict = null; builtInCMapCache = new Map(); - fontCache = new RefSetCache(); + fontCache = new RefMap(); globalColorSpaceCache = new GlobalColorSpaceCache(); globalImageCache = new GlobalImageCache(); nonBlendModesSet = new RefSet(); - pageDictCache = new RefSetCache(); - pageIndexCache = new RefSetCache(); - pageKidsCountCache = new RefSetCache(); + pageDictCache = new RefMap(); + pageIndexCache = new RefMap(); + pageKidsCountCache = new RefMap(); standardFontDataCache = new Map(); systemFontCache = new Map(); constructor(pdfManager, xref) { @@ -40396,16 +40615,10 @@ class Catalog { if (!(obj instanceof Dict)) { return null; } - const markInfo = { - Marked: false, - UserProperties: false, - Suspects: false - }; - for (const key in markInfo) { - const value = obj.get(key); - if (typeof value === "boolean") { - markInfo[key] = value; - } + const markInfo = new Map(); + for (const key of ["Marked", "UserProperties", "Suspects"]) { + const val = obj.get(key); + markInfo.set(key, typeof val === "boolean" ? val : false); } return markInfo; } @@ -40571,11 +40784,10 @@ class Catalog { return null; } flags += 2 ** 32; - const permissions = []; - for (const key in PermissionFlag) { - const value = PermissionFlag[key]; + const permissions = new Set(); + for (const value of Object.values(PermissionFlag)) { if (flags & value) { - permissions.push(value); + permissions.add(value); } } return permissions; @@ -40595,7 +40807,7 @@ class Catalog { if (!Array.isArray(groupsData)) { return shadow(this, "optionalContentConfig", null); } - const groupRefCache = new RefSetCache(); + const groupRefCache = new RefMap(); for (const groupRef of groupsData) { if (!(groupRef instanceof Ref) || groupRefCache.has(groupRef)) { continue; @@ -40907,11 +41119,8 @@ class Catalog { case "A": case "a": const LIMIT = 26; - const A_UPPER_CASE = 0x41, - A_LOWER_CASE = 0x61; - const baseCharCode = style === "a" ? A_LOWER_CASE : A_UPPER_CASE; const letterIndex = currentIndex - 1; - const character = String.fromCharCode(baseCharCode + letterIndex % LIMIT); + const character = String.fromCharCode(style.charCodeAt(0) + letterIndex % LIMIT); currentLabel = character.repeat(Math.floor(letterIndex / LIMIT) + 1); break; default: @@ -41191,9 +41400,9 @@ class Catalog { const javaScript = this.#collectJavaScript(); let actions = collectActions(this.xref, this.#catDict, DocumentActionEventType); if (javaScript) { - actions ??= Object.create(null); + actions ??= new Map(); for (const [key, val] of javaScript) { - (actions[key] ??= []).push(val); + actions.getOrInsertComputed(key, makeArr).push(val); } } return shadow(this, "jsActions", actions); @@ -42378,7 +42587,10 @@ function getColor(data, def = [0, 0, 0]) { b }; } - const color = data.split(",", 3).map(c => MathClamp(parseInt(c.trim(), 10), 0, 255)).map(c => isNaN(c) ? 0 : c); + const color = data.split(",", 3).map(c => { + c = parseInt(c.trim(), 10); + return isNaN(c) ? 0 : MathClamp(c, 0, 255); + }); if (color.length < 3) { return { r, @@ -42554,10 +42766,7 @@ class FontFinder { } function selectFont(xfaFont, typeface) { if (xfaFont.posture === "italic") { - if (xfaFont.weight === "bold") { - return typeface.bolditalic; - } - return typeface.italic; + return xfaFont.weight === "bold" ? typeface.bolditalic : typeface.italic; } else if (xfaFont.weight === "bold") { return typeface.bold; } @@ -43186,10 +43395,7 @@ class XFAObject { return ""; } [$text]() { - if (this[_children].length === 0) { - return this[$content]; - } - return this[_children].map(c => c[$text]()).join(""); + return this[_children].length === 0 ? this[$content] : this[_children].map(c => c[$text]()).join(""); } get [_attributeNames]() { const proto = Object.getPrototypeOf(this); @@ -43220,12 +43426,6 @@ class XFAObject { [$getSubformParent]() { return this[$getParent](); } - [$getChildren](name = null) { - if (!name) { - return this[_children]; - } - return this[name]; - } [$dump]() { const dumped = Object.create(null); if (this[$content]) { @@ -43484,10 +43684,7 @@ class XFAObject { return clone; } [$getChildren](name = null) { - if (!name) { - return this[_children]; - } - return this[_children].filter(c => c[$nodeName] === name); + return !name ? this[_children] : this[_children].filter(c => c[$nodeName] === name); } [$getChildrenByClass](name) { return this[name]; @@ -43674,12 +43871,6 @@ class XmlObject extends XFAObject { } return HTMLResult.EMPTY; } - [$getChildren](name = null) { - if (!name) { - return this[_children]; - } - return this[_children].filter(c => c[$nodeName] === name); - } [$getAttributes]() { return this[_attributes]; } @@ -43834,6 +44025,7 @@ class Option10 extends IntegerObject { + function measureToString(m) { if (typeof m === "string") { return "0px"; @@ -44301,14 +44493,14 @@ function setFontFamily(xfaFont, node, fontFinder, style) { return; } const name = stripQuotes(xfaFont.typeface); - style.fontFamily = `"${name}"`; + style.fontFamily = serializeFontFamily(name); const typeface = fontFinder.find(name); if (typeface) { const { fontFamily } = typeface.regular.cssFontInfo; if (fontFamily !== name) { - style.fontFamily = `"${fontFamily}"`; + style.fontFamily = serializeFontFamily(fontFamily); } const para = getCurrentPara(node); if (para && para.lineHeight !== "") { @@ -48767,7 +48959,7 @@ class Text extends ContentObject { } [$getExtra]() { if (typeof this[$content] === "string") { - return this[$content].split(/[\u2029\u2028\n]/).filter(line => !!line).join("\n"); + return this[$content].split(/[\u2029\u2028\n]/).filter(Boolean).join("\n"); } return this[$content][$text](); } @@ -49052,10 +49244,7 @@ class Value extends XFAObject { } [$text]() { if (this.exData) { - if (typeof this.exData[$content] === "string") { - return this.exData[$content].trim(); - } - return this.exData[$content][$text]().trim(); + return typeof this.exData[$content] === "string" ? this.exData[$content].trim() : this.exData[$content][$text]().trim(); } for (const name of Object.getOwnPropertyNames(this)) { if (name === "image") { @@ -50225,7 +50414,7 @@ class EquateRange extends XFAObject { const ranges = []; const unicodeRegex = /U\+([0-9a-fA-F]+)/; const unicodeRange = this._unicodeRange; - for (let range of unicodeRange.split(",").map(x => x.trim()).filter(x => !!x)) { + for (let range of unicodeRange.split(",").map(x => x.trim()).filter(Boolean)) { range = range.split("-", 2).map(x => { const found = x.match(unicodeRegex); if (!found) { @@ -51999,7 +52188,7 @@ class XhtmlObject extends XmlObject { xfaFont.letterSpacing = getMeasurement(value); break; case "margin": - const values = value.split(/ \t/).map(x => getMeasurement(x)); + const values = value.split(/ \t/).map(getMeasurement); switch (values.length) { case 1: margin.top = margin.bottom = margin.left = margin.right = values[0]; @@ -52459,13 +52648,11 @@ class Builder { if (hasNamespace) { this._currentNamespace = this._namespaceStack.pop(); } - if (prefixes) { - prefixes.forEach(({ - prefix - }) => { - this._namespacePrefixes.get(prefix).pop(); - }); - } + prefixes?.forEach(({ + prefix + }) => { + this._namespacePrefixes.get(prefix).pop(); + }); if (nsAgnostic) { this._nsAgnosticLevel--; } @@ -52755,6 +52942,7 @@ class XFAFactory { + class AnnotationFactory { static createGlobals(pdfManager) { return Promise.all([pdfManager.ensureCatalog("acroForm"), pdfManager.ensureDoc("xfaDatasets"), pdfManager.ensureCatalog("structTreeRoot"), pdfManager.ensureCatalog("baseUrl"), pdfManager.ensureCatalog("attachments"), pdfManager.ensureCatalog("globalColorSpaceCache")]).then(([acroForm, xfaDatasets, structTreeRoot, baseUrl, attachments, globalColorSpaceCache]) => ({ @@ -53124,6 +53312,20 @@ function getTransformMatrix(rect, bbox, matrix) { const yRatio = (rect[3] - rect[1]) / (maxY - minY); return [xRatio, 0, 0, yRatio, rect[0] - minX * xRatio, rect[1] - minY * yRatio]; } +function writeLineToCurveToAppearance(data, buffer, maybeClose = false) { + buffer.push(`${numberToString(data[4])} ${numberToString(data[5])} m`); + for (let i = 6, ii = data.length; i < ii; i += 6) { + if (isNaN(data[i])) { + buffer.push(`${numberToString(data[i + 4])} ${numberToString(data[i + 5])} l`); + } else { + const curve = data.slice(i, i + 6); + buffer.push(`${curve.map(numberToString).join(" ")} c`); + } + } + if (maybeClose && data.length === 6) { + buffer.push(`${numberToString(data[4])} ${numberToString(data[5])} l`); + } +} class Annotation { appearance = null; _oc = undefined; @@ -53183,7 +53385,7 @@ class Annotation { if (annotationGlobals.structTreeRoot) { let structParent = dict.get("StructParent"); this.data.structParent = structParent = Number.isInteger(structParent) && structParent >= 0 ? structParent : -1; - annotationGlobals.structTreeRoot.addAnnotationIdToPage(params.pageRef, structParent); + annotationGlobals.structTreeRoot.addAnnotationIdToPage(params.pageRef, structParent, this.ref); } if (params.collectFields) { const kids = dict.get("Kids"); @@ -54301,13 +54503,24 @@ class WidgetAnnotation extends Annotation { } const defaultVPadding = Math.min(Math.floor((totalHeight - fontSize) / 2), defaultPadding); const alignment = this.data.textAlignment; + let { + ascent: fontAscent, + descent: fontDescent + } = font; + if (isNaN(fontAscent) || isNaN(fontDescent) || !fontAscent && !fontDescent) { + fontAscent = (/* inlined export .LINE_FACTOR */1.35) - (/* inlined export .LINE_DESCENT_FACTOR */0.35); + fontDescent = (/* inlined export .LINE_DESCENT_FACTOR */0.35); + } else { + fontDescent = Math.abs(fontDescent); + } + const vShift = (totalHeight - (fontAscent + fontDescent) * fontSize) / 2 + fontDescent * fontSize; if (this.data.multiLine) { return this._getMultilineAppearance(defaultAppearance, encodedLines, font, fontSize, totalWidth, totalHeight, alignment, defaultHPadding, defaultVPadding, descent, lineHeight, annotationStorage); } if (this.data.comb) { - return this._getCombAppearance(defaultAppearance, font, encodedLines[0], fontSize, totalWidth, totalHeight, alignment, bidi(lines[0]).dir === "rtl", annotationStorage); + return this._getCombAppearance(defaultAppearance, font, encodedLines[0], fontSize, totalWidth, vShift, alignment, bidi(lines[0]).dir === "rtl", annotationStorage); } - const bottomPadding = defaultVPadding + descent; + const bottomPadding = vShift; if (alignment === 0 || alignment > 2) { return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 ${numberToString(defaultHPadding)} ${numberToString(bottomPadding)} Tm (${escapeString(encodedLines[0])}) Tj` + " ET Q EMC"; } @@ -54484,28 +54697,28 @@ class TextWidgetAnnotation extends WidgetAnnotation { this.data.comb = this.hasFieldFlag(AnnotationFieldFlag.COMB) && !this.data.multiLine && !this.data.password && !this.hasFieldFlag(AnnotationFieldFlag.FILESELECT) && this.data.maxLen !== 0; this.data.doNotScroll = this.hasFieldFlag(AnnotationFieldFlag.DONOTSCROLL); const { - data: { - actions - } - } = this; + actions + } = this.data; if (!actions) { return; } const AFDateTime = /^AF(Date|Time)_(?:Keystroke|Format)(?:Ex)?\(['"]?([^'"]+)['"]?\);$/; let canUseHTMLDateTime = false; - if (actions.Format?.length === 1 && actions.Keystroke?.length === 1 && AFDateTime.test(actions.Format[0]) && AFDateTime.test(actions.Keystroke[0]) || actions.Format?.length === 0 && actions.Keystroke?.length === 1 && AFDateTime.test(actions.Keystroke[0]) || actions.Keystroke?.length === 0 && actions.Format?.length === 1 && AFDateTime.test(actions.Format[0])) { + const aFormat = actions.get("Format"), + aKeystroke = actions.get("Keystroke"); + if (aFormat?.length === 1 && aKeystroke?.length === 1 && AFDateTime.test(aFormat[0]) && AFDateTime.test(aKeystroke[0]) || aFormat?.length === 0 && aKeystroke?.length === 1 && AFDateTime.test(aKeystroke[0]) || aKeystroke?.length === 0 && aFormat?.length === 1 && AFDateTime.test(aFormat[0])) { canUseHTMLDateTime = true; } const actionsToVisit = []; - if (actions.Format) { - actionsToVisit.push(...actions.Format); + if (aFormat) { + actionsToVisit.push(...aFormat); } - if (actions.Keystroke) { - actionsToVisit.push(...actions.Keystroke); + if (aKeystroke) { + actionsToVisit.push(...aKeystroke); } if (canUseHTMLDateTime) { - delete actions.Keystroke; - actions.Format = actionsToVisit; + actions.delete("Keystroke"); + actions.set("Format", actionsToVisit); } for (const formatAction of actionsToVisit) { const m = formatAction.match(AFDateTime); @@ -54539,7 +54752,7 @@ class TextWidgetAnnotation extends WidgetAnnotation { get hasTextContent() { return !!this.appearance && !this._needAppearances; } - _getCombAppearance(defaultAppearance, font, text, fontSize, width, height, alignment, isRTL, annotationStorage) { + _getCombAppearance(defaultAppearance, font, text, fontSize, width, vShift, alignment, isRTL, annotationStorage) { const combWidth = width / this.data.maxLen; const colors = this.getBorderAndBackgroundAppearances(annotationStorage); const cells = font.getCharPositions(text).map(([start, end]) => { @@ -54571,7 +54784,6 @@ class TextWidgetAnnotation extends WidgetAnnotation { previousWidth = glyphWidth; } const renderedComb = buf.join(" "); - const vShift = (height - (font.capHeight || font.ascent || 1) * fontSize) / 2; return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 ${numberToString(hShift)} ${numberToString(vShift)} Tm ${renderedComb}` + " ET Q EMC"; } _getMultilineAppearance(defaultAppearance, lines, font, fontSize, width, height, alignment, hPadding, vPadding, descent, lineHeight, annotationStorage) { @@ -55314,10 +55526,7 @@ class ChoiceWidgetAnnotation extends WidgetAnnotation { if (valueIndices.length > 0) { const minIndex = Math.min(...valueIndices); const maxIndex = Math.max(...valueIndices); - firstIndex = Math.max(0, maxIndex - numberOfVisibleLines + 1); - if (firstIndex > minIndex) { - firstIndex = minIndex; - } + firstIndex = MathClamp(maxIndex - numberOfVisibleLines + 1, 0, minIndex); } const end = Math.min(firstIndex + numberOfVisibleLines + 1, lineCount); const buf = ["/Tx BMC q", `1 1 ${totalWidth} ${totalHeight} re W n`]; @@ -55983,18 +56192,7 @@ class InkAnnotation extends MarkupAnnotation { appearanceBuffer.push("/R0 gs"); } for (const outline of paths.lines) { - appearanceBuffer.push(`${numberToString(outline[4])} ${numberToString(outline[5])} m`); - for (let i = 6, ii = outline.length; i < ii; i += 6) { - if (isNaN(outline[i])) { - appearanceBuffer.push(`${numberToString(outline[i + 4])} ${numberToString(outline[i + 5])} l`); - } else { - const [c1x, c1y, c2x, c2y, x, y] = outline.slice(i, i + 6); - appearanceBuffer.push([c1x, c1y, c2x, c2y, x, y].map(numberToString).join(" ") + " c"); - } - } - if (outline.length === 6) { - appearanceBuffer.push(`${numberToString(outline[4])} ${numberToString(outline[5])} l`); - } + writeLineToCurveToAppearance(outline, appearanceBuffer, true); } appearanceBuffer.push("S"); const appearance = appearanceBuffer.join("\n"); @@ -56029,15 +56227,7 @@ class InkAnnotation extends MarkupAnnotation { return null; } const appearanceBuffer = [`${getPdfColor(color, true)}`, "/R0 gs"]; - appearanceBuffer.push(`${numberToString(outline[4])} ${numberToString(outline[5])} m`); - for (let i = 6, ii = outline.length; i < ii; i += 6) { - if (isNaN(outline[i])) { - appearanceBuffer.push(`${numberToString(outline[i + 4])} ${numberToString(outline[i + 5])} l`); - } else { - const [c1x, c1y, c2x, c2y, x, y] = outline.slice(i, i + 6); - appearanceBuffer.push([c1x, c1y, c2x, c2y, x, y].map(numberToString).join(" ") + " c"); - } - } + writeLineToCurveToAppearance(outline, appearanceBuffer); appearanceBuffer.push("h f"); const appearance = appearanceBuffer.join("\n"); const appearanceStreamDict = new Dict(xref); @@ -56336,18 +56526,7 @@ class StampAnnotation extends MarkupAnnotation { } const appearanceBuffer = [`${thickness} w 1 J 1 j`, `${getPdfColor(color, areContours)}`]; for (const line of lines) { - appearanceBuffer.push(`${numberToString(line[4])} ${numberToString(line[5])} m`); - for (let i = 6, ii = line.length; i < ii; i += 6) { - if (isNaN(line[i])) { - appearanceBuffer.push(`${numberToString(line[i + 4])} ${numberToString(line[i + 5])} l`); - } else { - const [c1x, c1y, c2x, c2y, x, y] = line.slice(i, i + 6); - appearanceBuffer.push([c1x, c1y, c2x, c2y, x, y].map(numberToString).join(" ") + " c"); - } - } - if (line.length === 6) { - appearanceBuffer.push(`${numberToString(line[4])} ${numberToString(line[5])} l`); - } + writeLineToCurveToAppearance(line, appearanceBuffer, true); } appearanceBuffer.push(areContours ? "F" : "S"); const appearance = appearanceBuffer.join("\n"); @@ -56980,13 +57159,8 @@ class Word64 { this.low ^= word.low; } shiftRight(places) { - if (places >= 32) { - this.low = this.high >>> places - 32 | 0; - this.high = 0; - } else { - this.low = this.low >>> places | this.high << 32 - places; - this.high = this.high >>> places | 0; - } + this.low = this.low >>> places | this.high << 32 - places; + this.high = this.high >>> places | 0; } rotateRight(places) { let low, high; @@ -57344,12 +57518,12 @@ class DecryptStream extends DecodeStream { } readBlock() { let chunk = this.#nextChunk ?? this.stream.getBytes(chunkSize); - if (!chunk?.length) { + if (!chunk.length) { this.eof = true; return; } this.#nextChunk = this.stream.getBytes(chunkSize); - const hasMoreData = this.#nextChunk?.length > 0; + const hasMoreData = this.#nextChunk.length > 0; const decrypt = this.decrypt; chunk = decrypt(chunk, !hasMoreData); const bufferLength = this.bufferLength, @@ -57442,7 +57616,9 @@ class AESBaseCipher { _s = new Uint8Array([0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]); _inv_s = new Uint8Array([0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d]); _mix = new Uint32Array([0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]); - _mixCol = new Uint8Array(256).map((_, i) => i < 128 ? i << 1 : i << 1 ^ 0x1b); + _mixCol = Uint8Array.from({ + length: 256 + }, (_, i) => i < 128 ? i << 1 : i << 1 ^ 0x1b); constructor() { this.buffer = new Uint8Array(16); this.bufferPosition = 0; @@ -58357,7 +58533,9 @@ class XRef { tableState.parserBuf2 = parser.buf2; const entry = { offset: parser.getObj(), - gen: parser.getObj() + gen: parser.getObj(), + free: false, + uncompressed: false }; const type = parser.getObj(); if (type instanceof Cmd) { @@ -58454,7 +58632,9 @@ class XRef { } const entry = { offset, - gen: generation + gen: generation, + free: false, + uncompressed: false }; switch (type) { case 0: @@ -58576,6 +58756,7 @@ class XRef { this.#entries[num] = { offset: position - stream.start, gen, + free: false, uncompressed: true }; } @@ -59018,7 +59199,7 @@ class Page { } }; } - #createPartialEvaluator(handler, pageIndex = this.pageIndex) { + _createPartialEvaluator(handler, pageIndex = this.pageIndex) { return new PartialEvaluator({ xref: this.xref, handler, @@ -59033,9 +59214,6 @@ class Page { options: this.evaluatorOptions }); } - createAnnotationEvaluator(handler) { - return this.#createPartialEvaluator(handler); - } #getInheritableProperty(key, getArray = false) { const value = getInheritableProperty({ dict: this.pageDict, @@ -59154,39 +59332,40 @@ class Page { async #replaceIdByRef(annotations, deletedAnnotations, existingAnnotations) { const promises = []; for (const annotation of annotations) { - if (annotation.id) { - const ref = Ref.fromString(annotation.id); - if (!ref) { - warn(`A non-linked annotation cannot be modified: ${annotation.id}`); - continue; - } - if (annotation.deleted) { - deletedAnnotations.put(ref, ref); - if (annotation.popupRef) { - const popupRef = Ref.fromString(annotation.popupRef); - if (popupRef) { - deletedAnnotations.put(popupRef, popupRef); - } - } - continue; - } - if (annotation.popup?.deleted) { + if (!annotation.id) { + continue; + } + const ref = Ref.fromString(annotation.id); + if (!ref) { + warn(`A non-linked annotation cannot be modified: ${annotation.id}`); + continue; + } + if (annotation.deleted) { + deletedAnnotations.put(ref); + if (annotation.popupRef) { const popupRef = Ref.fromString(annotation.popupRef); if (popupRef) { - deletedAnnotations.put(popupRef, popupRef); + deletedAnnotations.put(popupRef); } } - existingAnnotations?.put(ref); - annotation.ref = ref; - promises.push(this.xref.fetchAsync(ref).then(obj => { - if (obj instanceof Dict) { - annotation.oldAnnotation = obj.clone(); - } - }, () => { - warn(`Cannot fetch \`oldAnnotation\` for: ${ref}.`); - })); - delete annotation.id; + continue; } + if (annotation.popup?.deleted) { + const popupRef = Ref.fromString(annotation.popupRef); + if (popupRef) { + deletedAnnotations.put(popupRef); + } + } + existingAnnotations?.put(ref); + annotation.ref = ref; + promises.push(this.xref.fetchAsync(ref).then(obj => { + if (obj instanceof Dict) { + annotation.oldAnnotation = obj.clone(); + } + }, () => { + warn(`Cannot fetch \`oldAnnotation\` for: ${ref}.`); + })); + delete annotation.id; } await Promise.all(promises); } @@ -59194,8 +59373,8 @@ class Page { if (this.xfaFactory) { throw new Error("XFA: Cannot save new annotations."); } - const partialEvaluator = this.#createPartialEvaluator(handler); - const deletedAnnotations = new RefSetCache(); + const partialEvaluator = this._createPartialEvaluator(handler); + const deletedAnnotations = new RefSet(); const existingAnnotations = new RefSet(); await this.#replaceIdByRef(annotations, deletedAnnotations, existingAnnotations); const pageDict = this.pageDict; @@ -59220,7 +59399,7 @@ class Page { } } async save(handler, task, annotationStorage, changes) { - const partialEvaluator = this.#createPartialEvaluator(handler); + const partialEvaluator = this._createPartialEvaluator(handler); const annotations = await this._parsedAnnotations; const promises = []; for (const annotation of annotations) { @@ -59259,7 +59438,7 @@ class Page { }) { const contentStreamPromise = this.getContentStream(); const resourcesPromise = this.loadResources(RESOURCES_KEYS_OPERATOR_LIST); - const partialEvaluator = this.#createPartialEvaluator(handler, pageIndex); + const partialEvaluator = this._createPartialEvaluator(handler, pageIndex); const newAnnotsByPage = !this.xfaFactory ? getNewAnnotationsMap(annotationStorage) : null; const newAnnots = newAnnotsByPage?.get(this.pageIndex); let newAnnotationsPromise = Promise.resolve(null); @@ -59390,7 +59569,7 @@ class Page { const langPromise = this.pdfManager.ensureCatalog("lang"); const [contentStream,, lang] = await Promise.all([contentStreamPromise, resourcesPromise, langPromise]); const resources = await this.#getMergedResources(contentStream.dict, RESOURCES_KEYS_TEXT_CONTENT); - const partialEvaluator = this.#createPartialEvaluator(handler); + const partialEvaluator = this._createPartialEvaluator(handler); return partialEvaluator.getTextContent({ stream: contentStream, task, @@ -59440,7 +59619,7 @@ class Page { annotationsData.push(annotation.data); } if (annotation.hasTextContent && isVisible) { - partialEvaluator ??= this.#createPartialEvaluator(handler); + partialEvaluator ??= this._createPartialEvaluator(handler); textContentPromises.push(annotation.extractTextContent(partialEvaluator, task, [-Infinity, -Infinity, Infinity, Infinity]).catch(function (reason) { warn(`getAnnotationsData - ignoring textContent during "${task.name}" task: "${reason}".`); })); @@ -59540,7 +59719,7 @@ class Page { } annotation.data.pageIndex = pageIndex; if (annotation.hasTextContent && annotation.viewable) { - partialEvaluator ??= this.#createPartialEvaluator(handler); + partialEvaluator ??= this._createPartialEvaluator(handler); await annotation.extractTextContent(partialEvaluator, task, [-Infinity, -Infinity, Infinity, Infinity]); } return annotation.data; @@ -59896,8 +60075,7 @@ class PDFDocument { if (!(descriptor instanceof Dict)) { continue; } - let fontFamily = descriptor.get("FontFamily"); - fontFamily = fontFamily.replaceAll(/ +(\d)/g, "$1"); + const fontFamily = normalizeCSSFontFamily(descriptor.get("FontFamily")); const fontWeight = descriptor.get("FontWeight"); const italicAngle = -descriptor.get("ItalicAngle"); const cssFontInfo = { @@ -60062,15 +60240,12 @@ class PDFDocument { default: if (value instanceof Name) { customValue = value; + break; } - break; - } - if (customValue === undefined) { - warn(`Bad value, for custom key "${key}", in Info: ${value}.`); - continue; + warn(`Bad value, for custom key "${key}", in Info: ${value}.`); + continue; } - docInfo.Custom ??= Object.create(null); - docInfo.Custom[key] = customValue; + (docInfo.Custom ??= new Map()).set(key, customValue); continue; } warn(`Bad value, for key "${key}", in Info: ${value}.`); @@ -60331,24 +60506,24 @@ class PDFDocument { acroForm } = annotationGlobals; const visitedRefs = new RefSet(); - const allFields = Object.create(null); + const allFields = new Map(); const fieldPromises = new Map(); - const orphanFields = new RefSetCache(); + const orphanFields = new RefMap(); for (const fieldRef of acroForm.get("Fields")) { await this.#collectFieldObjects("", null, fieldRef, fieldPromises, annotationGlobals, visitedRefs, orphanFields); } const allPromises = []; for (const [name, promises] of fieldPromises) { allPromises.push(Promise.all(promises).then(fields => { - fields = fields.filter(field => !!field); + fields = fields.filter(Boolean); if (fields.length > 0) { - allFields[name] = fields; + allFields.set(name, fields); } })); } await Promise.all(allPromises); return { - allFields: Object.keys(allFields).length ? allFields : null, + allFields: allFields.size ? allFields : null, orphanFields }; }); @@ -60515,19 +60690,17 @@ class PDFDocument { }; } get hasJSActions() { - const promise = this.pdfManager.ensureDoc("_parseHasJSActions"); + const promise = Promise.all([this.pdfManager.ensureCatalog("jsActions"), this.pdfManager.ensureDoc("fieldObjects")]).then(([catalogJsActions, fieldObjects]) => { + if (catalogJsActions) { + return true; + } + if (fieldObjects?.allFields) { + return fieldObjects.allFields.values().some(fieldObj => fieldObj.some(obj => obj.actions !== null)); + } + return false; + }); return shadow(this, "hasJSActions", promise); } - async _parseHasJSActions() { - const [catalogJsActions, fieldObjects] = await Promise.all([this.pdfManager.ensureCatalog("jsActions"), this.pdfManager.ensureDoc("fieldObjects")]); - if (catalogJsActions) { - return true; - } - if (fieldObjects?.allFields) { - return Object.values(fieldObjects.allFields).some(fieldObject => fieldObject.some(object => object.actions !== null)); - } - return false; - } get calculationOrderIds() { const calculationOrder = this.catalog.acroForm?.get("CO"); if (!Array.isArray(calculationOrder) || calculationOrder.length === 0) { @@ -60613,9 +60786,6 @@ class BasePdfManager { ensureDoc(prop, args) { return this.ensure(this.pdfDocument, prop, args); } - ensureXRef(prop, args) { - return this.ensure(this.pdfDocument.xref, prop, args); - } ensureCatalog(prop, args) { return this.ensure(this.pdfDocument.catalog, prop, args); } @@ -60669,9 +60839,6 @@ class LocalPdfManager extends BasePdfManager { } return value; } - requestRange(begin, end) { - return Promise.resolve(); - } requestLoadedStream(noFetch = false) { return this._loadedStreamPromise; } @@ -61207,6 +61374,20 @@ async function writeArray(array, buffer, transform) { } buffer.push("]"); } +function numberToPDFString(value) { + if (Number.isInteger(value) && Math.abs(value) >= 1e21) { + return BigInt(value).toString(); + } + const str = value.toFixed(10); + let end = str.length; + while (str[end - 1] === "0") { + end--; + } + if (str[end - 1] === ".") { + end--; + } + return str.slice(0, end); +} async function writeValue(value, buffer, transform) { if (value instanceof Name) { buffer.push(`/${escapePDFName(value.name)}`); @@ -61220,7 +61401,7 @@ async function writeValue(value, buffer, transform) { } buffer.push(`(${escapeString(value)})`); } else if (typeof value === "number") { - buffer.push(value.toFixed(10).replace(/\.?0+$/, "")); + buffer.push(numberToPDFString(value)); } else if (typeof value === "boolean") { buffer.push(value.toString()); } else if (value instanceof Dict) { @@ -61554,6 +61735,7 @@ class PageData { this.documentData = documentData; this.annotations = null; this.pointingNamedDestinations = null; + this.copyLevel = 0; documentData.pagesMap.put(page.ref, this); } } @@ -61562,11 +61744,11 @@ class DocumentData { this.document = document; this.destinations = null; this.pageLabels = null; - this.pagesMap = new RefSetCache(); - this.oldRefMapping = new RefSetCache(); + this.pagesMap = new RefMap(); + this.oldRefMapping = new RefMap(); this.dedupNamedDestinations = new Map(); this.usedNamedDestinations = new Set(); - this.postponedRefCopies = new RefSetCache(); + this.postponedRefCopies = new RefMap(); this.resourceStreamPromises = new Map(); this.usedStructParents = new Set(); this.oldStructParentMapping = new Map(); @@ -61583,7 +61765,7 @@ class DocumentData { this.acroFormDefaultResources = null; this.acroFormQ = 0; this.hasSignatureAnnotations = false; - this.fieldToParent = new RefSetCache(); + this.fieldToParent = new RefMap(); this.outline = null; this.embeddedFiles = null; } @@ -61682,6 +61864,7 @@ class PDFEditor { if (obj instanceof Ref) { const { currentDocument: { + fieldToParent, oldRefMapping } } = this; @@ -61691,6 +61874,10 @@ class PDFEditor { } const oldRef = obj; obj = await xref.fetchAsync(oldRef); + const mappedRef = oldRefMapping.get(oldRef); + if (mappedRef) { + return mappedRef; + } if (typeof obj === "number") { return obj; } @@ -61699,7 +61886,13 @@ class PDFEditor { } const newRef = this.newRef; oldRefMapping.put(oldRef, newRef); - this.xref[newRef.num] = await this.#collectDependencies(obj, true, xref, resourceStreamPath); + let cloneSource = true; + if (fieldToParent.has(oldRef) && obj instanceof Dict) { + obj = this.cloneDict(obj); + obj.delete("Parent"); + cloneSource = false; + } + this.xref[newRef.num] = await this.#collectDependencies(obj, cloneSource, xref, resourceStreamPath); return newRef; } const promises = []; @@ -62183,8 +62376,6 @@ class PDFEditor { } this.oldPages[newPageIndex] = null; }; - const docPageInfos = pageInfos.filter(info => !!info.document); - this.isSingleFile = docPageInfos.length === 1 || docPageInfos.length > 0 && docPageInfos.every(info => info.document === docPageInfos[0].document); const allDocumentData = []; if (annotationStorage) { this.#newAnnotationsParams = { @@ -62262,11 +62453,27 @@ class PDFEditor { } } await Promise.all(promises); + if (this.oldPages.length === 0) { + throw new Error("extractPages: nothing to extract."); + } + const copyCounts = new Map(); + const documents = new Set(); for (let i = 0, ii = this.oldPages.length; i < ii; i++) { - if (this.oldPages[i] === undefined) { + const pageData = this.oldPages[i]; + if (pageData === undefined) { throw new Error("extractPages: sparse pageIndices."); } + if (pageData) { + const { + page + } = pageData; + const copyLevel = copyCounts.get(page) ?? 0; + copyCounts.set(page, copyLevel + 1); + pageData.copyLevel = copyLevel; + documents.add(pageData.documentData.document); + } } + this.isSingleFile = documents.size === 1; promises.length = 0; this.#collectValidDestinations(allDocumentData); this.#collectOutlineDestinations(allDocumentData); @@ -62363,7 +62570,6 @@ class PDFEditor { key: "FT" }), "Sig"); const parentRef = annotationDict.getRaw("Parent") || null; - annotationDict.delete("Parent"); fieldToParent.put(annotationRef, parentRef); } newAnnotations[newAnnotationIndex] = annotationRef; @@ -62387,7 +62593,7 @@ class PDFEditor { })); } await Promise.all(promises); - newAnnotations = newAnnotations.filter(annot => !!annot); + newAnnotations = newAnnotations.filter(Boolean); pageData.annotations = newAnnotations.length > 0 ? newAnnotations : null; pageData.documentData.hasSignatureAnnotations ||= hasSignatureAnnotations; } @@ -63092,8 +63298,19 @@ class PDFEditor { } let parent = parentRef; let lastNonNullParent = parentRef; + const visited = new RefSet(); while (true) { - parent = xref.fetchIfRef(parent)?.getRaw("Parent") || null; + if (parent instanceof Ref) { + if (visited.has(parent)) { + break; + } + visited.put(parent); + } + const parentDict = xref.fetchIfRef(parent); + if (!(parentDict instanceof Dict)) { + break; + } + parent = parentDict.getRaw("Parent") || null; if (!parent) { break; } @@ -63163,6 +63380,9 @@ class PDFEditor { } processed.put(oldKidRef); const kid = xref.fetchIfRef(oldKidRef); + if (!(kid instanceof Dict)) { + continue; + } if (kid.has("Kids")) { const kidsArray = kid.get("Kids"); if (!Array.isArray(kidsArray)) { @@ -63276,7 +63496,7 @@ class PDFEditor { } const numPages = document.numPages; const labelsByPageIndex = new Map(); - const oldPageIndices = new Set(this.oldPages.filter(p => !!p).map(({ + const oldPageIndices = new Set(this.oldPages.filter(Boolean).map(({ page: { pageIndex } @@ -63323,7 +63543,8 @@ class PDFEditor { page, documentData, annotations, - pointingNamedDestinations + pointingNamedDestinations, + copyLevel } = this.oldPages[pageIndex]; this.currentDocument = documentData; const { @@ -63373,15 +63594,17 @@ class PDFEditor { newAnnots = newAnnotations; } } - const newAnnotations = documentData.document === this.#primaryDocument ? this.#newAnnotationsParams?.newAnnotationsByPage?.get(page.pageIndex) : null; - if (newAnnotations) { + const newAnnotations = documentData.document === this.#primaryDocument ? this.#newAnnotationsParams?.newAnnotationsByPage?.get(page.pageIndex)?.filter(({ + copyLevel: level + }) => (level ?? 0) === copyLevel) : null; + if (newAnnotations?.length) { const { handler, task, imagesPromises } = this.#newAnnotationsParams; - const changes = new RefSetCache(); - const newData = await AnnotationFactory.saveNewAnnotations(page.createAnnotationEvaluator(handler), this.xrefWrapper, task, newAnnotations, imagesPromises, changes); + const changes = new RefMap(); + const newData = await AnnotationFactory.saveNewAnnotations(page._createPartialEvaluator(handler), this.xrefWrapper, task, newAnnotations, imagesPromises, changes); for (const [ref, { data }] of changes.items()) { @@ -63722,7 +63945,11 @@ class PDFEditor { const parentTree = this.xref[parentTreeRef.num]; parentTree.setIfName("Type", "ParentTree"); structTree.set("ParentTree", parentTreeRef); - structTree.set("ParentTreeNextKey", this.parentTree.size); + let nextKey = 0; + for (const key of this.parentTree.keys()) { + nextKey = Math.max(nextKey, key + 1); + } + structTree.set("ParentTreeNextKey", nextKey); } if (this.idTree.size > 0) { const idTreeRef = this.#makeNameNumTree(Array.from(this.idTree.entries()), true); @@ -63857,7 +64084,7 @@ class PDFEditor { return result; } async #createChanges() { - const changes = new RefSetCache(); + const changes = new RefMap(); changes.put(Ref.get(0, 0xffff), { data: null }); @@ -64108,16 +64335,16 @@ class PDFWorkerStreamRangeReader extends BasePDFStreamRangeReader { class WorkerTask { + #capability = Promise.withResolvers(); + terminated = false; constructor(name) { this.name = name; - this.terminated = false; - this._capability = Promise.withResolvers(); } get finished() { - return this._capability.promise; + return this.#capability.promise; } finish() { - this._capability.resolve(); + this.#capability.resolve(); } terminate() { this.terminated = true; @@ -64158,7 +64385,7 @@ class WorkerMessageHandler { docId, apiVersion } = docParams; - const workerVersion = "6.2.108"; + const workerVersion = "6.3.289"; if (apiVersion !== workerVersion) { throw new Error(`The API version "${apiVersion}" does not match ` + `the Worker version "${workerVersion}".`); } @@ -64451,7 +64678,7 @@ class WorkerMessageHandler { } await Promise.all(pagePromises); const annotations = await Promise.all(annotationPromises); - return annotations.filter(a => !!a); + return annotations.filter(Boolean); } finally { if (task) { finishWorkerTask(task); @@ -64601,7 +64828,7 @@ class WorkerMessageHandler { filename }) { const globalPromises = [pdfManager.requestLoadedStream(), pdfManager.ensureCatalog("acroForm"), pdfManager.ensureCatalog("acroFormRef"), pdfManager.ensureDoc("startXRef"), pdfManager.ensureDoc("xref"), pdfManager.ensureCatalog("structTreeRoot")]; - const changes = new RefSetCache(); + const changes = new RefMap(); const promises = []; const newAnnotationsByPage = !isPureXfa ? getNewAnnotationsMap(annotationStorage) : null; const [stream, acroForm, acroFormRef, startXRef, xref, _structTreeRoot] = await Promise.all(globalPromises); diff --git a/apps/api/internal/webassets/dist/_app/immutable/chunks/BB6meo0l.js b/apps/api/internal/webassets/dist/_app/immutable/chunks/BB6meo0l.js deleted file mode 100644 index c6cc2869c..000000000 --- a/apps/api/internal/webassets/dist/_app/immutable/chunks/BB6meo0l.js +++ /dev/null @@ -1,54 +0,0 @@ -import{t as e}from"./HclGiUj8.js";var t=typeof process==`object`&&process+``==`[object process]`&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!==`browser`),n=[1/0,1/0,-1/0,-1/0],r=new Float32Array(n),i=[.001,0,0,.001,0,0],a=`http://www.w3.org/2000/svg`,o={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},s={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},c=`pdfjs_internal_id_`,l=`pdfjs_internal_editor_`,u={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},d={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},p={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},m={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},h={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26,RICHMEDIA:27},g={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},_={ERRORS:0,WARNINGS:1,INFOS:5},v={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},y={moveTo:0,lineTo:1,curveTo:2,quadraticCurveTo:3,closePath:4},b={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},x=_.WARNINGS;function S(e){Number.isInteger(e)&&(x=e)}function C(){return x}function w(e){x>=_.INFOS&&console.info(`Info: ${e}`)}function T(e){x>=_.WARNINGS&&console.warn(`Warning: ${e}`)}function E(e){throw Error(e)}function D(e,t){e||E(t)}function O(e){switch(e?.protocol){case`http:`:case`https:`:case`ftp:`:case`mailto:`:case`tel:`:return!0;default:return!1}}function k(e,t=null,n=null){if(!e)return null;if(n&&typeof e==`string`&&(n.addDefaultProtocol&&e.startsWith(`www.`)&&e.match(/\./g)?.length>=2&&(e=`http://${e}`),n.tryConvertEncoding))try{e=se(e)}catch{}let r=t?URL.parse(e,t):URL.parse(e);return O(r)?r:null}function A(e,t,n=!1){let r=URL.parse(e);return r?(r.hash=t,r.href):n&&k(e,`http://example.com`)?e.split(`#`,1)[0]+`${t?`#${t}`:``}`:``}function j(e){return e.substring(e.lastIndexOf(`/`)+1)}function M(e,t,n,r=!1){return Object.defineProperty(e,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}var N=function(){function e(e,t){this.message=e,this.name=t}return e.prototype=Error(),e.constructor=e,e}(),ee=class extends N{constructor(e,t){super(e,`PasswordException`),this.code=t}},te=class extends N{constructor(e,t){super(e,`UnknownErrorException`),this.details=t}},ne=class extends N{constructor(e){super(e,`InvalidPDFException`)}},re=class extends N{constructor(e,t,n){super(e,`ResponseException`),this.status=t,this.missing=n}},ie=class extends N{constructor(e){super(e,`FormatError`)}},P=class extends N{constructor(e){super(e,`AbortException`)}};function ae(e){(typeof e!=`object`||e?.length===void 0)&&E(`Invalid argument for bytesToString`);let t=e.length,n=8192;if(t`u`)return M(this,`isAlphaColorInputSupported`,!1);let e=document.createElement(`input`);return e.type=`color`,e.setAttribute(`alpha`,``),e.value=`#ff000080`,M(this,`isAlphaColorInputSupported`,e.value!==`#ff0000`)}static get isBackdropFilterSupported(){return M(this,`isBackdropFilterSupported`,typeof CSS<`u`&&CSS.supports(`backdrop-filter`,`blur(1px)`))}},I=class{static get hexNums(){return M(this,`hexNums`,Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,`0`)))}static makeHexColor(e,t,n){return`#${this.hexNums[e]}${this.hexNums[t]}${this.hexNums[n]}`}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static multiplyByDOMMatrix(e,t){return[e[0]*t.a+e[2]*t.b,e[1]*t.a+e[3]*t.b,e[0]*t.c+e[2]*t.d,e[1]*t.c+e[3]*t.d,e[0]*t.e+e[2]*t.f+e[4],e[1]*t.e+e[3]*t.f+e[5]]}static applyTransform(e,t,n=0){let r=e[n],i=e[n+1];e[n]=r*t[0]+i*t[2]+t[4],e[n+1]=r*t[1]+i*t[3]+t[5]}static applyTransformToBezier(e,t,n=0){let r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5];for(let t=0;t<6;t+=2){let l=e[n+t],u=e[n+t+1];e[n+t]=l*r+u*a+s,e[n+t+1]=l*i+u*o+c}}static applyInverseTransform(e,t){let n=e[0],r=e[1],i=t[0]*t[3]-t[1]*t[2];e[0]=(n*t[3]-r*t[2]+t[2]*t[5]-t[4]*t[3])/i,e[1]=(-n*t[1]+r*t[0]+t[4]*t[1]-t[5]*t[0])/i}static axialAlignedBoundingBox(e,t,n){let r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=e[0],u=e[1],d=e[2],f=e[3],p=r*l+s,m=p,h=r*d+s,g=h,_=o*u+c,v=_,y=o*f+c,b=y;if(i!==0||a!==0){let e=i*l,t=i*d,n=a*u,r=a*f;p+=n,g+=n,h+=r,m+=r,_+=e,b+=e,y+=t,v+=t}n[0]=Math.min(n[0],p,h,m,g),n[1]=Math.min(n[1],_,y,v,b),n[2]=Math.max(n[2],p,h,m,g),n[3]=Math.max(n[3],_,y,v,b)}static inverseTransform(e){let t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e,t){let n=e[0],r=e[1],i=e[2],a=e[3],o=n**2+r**2,s=n*i+r*a,c=i**2+a**2,l=(o+c)/2,u=Math.sqrt(l**2-(o*c-s**2));t[0]=Math.sqrt(l+u||1),t[1]=Math.sqrt(l-u||1)}static normalizeRect(e){let t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){let n=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(n>r)return null;let i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>a?null:[n,i,r,a]}static pointBoundingBox(e,t,n){n[0]=Math.min(n[0],e),n[1]=Math.min(n[1],t),n[2]=Math.max(n[2],e),n[3]=Math.max(n[3],t)}static rectBoundingBox(e,t,n,r,i){i[0]=Math.min(i[0],e,n),i[1]=Math.min(i[1],t,r),i[2]=Math.max(i[2],e,n),i[3]=Math.max(i[3],t,r)}static#e(e,t,n,r,i,a,o,s,c,l){if(c<=0||c>=1)return;let u=1-c,d=c*c,f=d*c,p=u*(u*(u*e+3*c*t)+3*d*n)+f*r,m=u*(u*(u*i+3*c*a)+3*d*o)+f*s;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],m),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],m)}static#t(e,t,n,r,i,a,o,s,c,l,u,d){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,n,r,i,a,o,s,-u/l,d);return}let f=l**2-4*u*c;if(f<0)return;let p=Math.sqrt(f),m=2*c;this.#e(e,t,n,r,i,a,o,s,(-l+p)/m,d),this.#e(e,t,n,r,i,a,o,s,(-l-p)/m,d)}static bezierBoundingBox(e,t,n,r,i,a,o,s,c){c[0]=Math.min(c[0],e,o),c[1]=Math.min(c[1],t,s),c[2]=Math.max(c[2],e,o),c[3]=Math.max(c[3],t,s),this.#t(e,n,i,o,t,r,a,s,3*(-e+3*(n-i)+o),6*(e-2*n+i),3*(n-e),c),this.#t(e,n,i,o,t,r,a,s,3*(-t+3*(r-a)+s),6*(t-2*r+a),3*(r-t),c)}};function se(e){return decodeURIComponent(escape(e))}var ce=null,le=null;function ue(e){return ce||(ce=/([\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,le=new Map([[`ſt`,`ſt`]])),e.replaceAll(ce,(e,t,n)=>t?t.normalize(`NFKC`):le.get(n))}function de(){if(typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=new Uint8Array(32);return crypto.getRandomValues(e),ae(e)}function fe(e,t,n){if(!Array.isArray(n)||n.length<2)return!1;let[r,i,...a]=n;if(!e(r)&&!Number.isInteger(r)||!t(i))return!1;let o=a.length,s=!0;switch(i.name){case`XYZ`:if(o<2||o>3)return!1;break;case`Fit`:case`FitB`:return o===0;case`FitH`:case`FitBH`:case`FitV`:case`FitBV`:if(o>1)return!1;break;case`FitR`:if(o!==4)return!1;s=!1;break;default:return!1}for(let e of a)if(!(typeof e==`number`||s&&e===null))return!1;return!0}var pe=()=>[],me=()=>new Map,he=()=>Object.create(null),ge=()=>new Set;typeof Iterator.prototype.join!=`function`&&(Iterator.prototype.join=function(e){return[...this].join(e)});function L(e,t,n){return Math.min(Math.max(e,t),n)}var _e=class e{constructor({viewBox:e,userUnit:t,scale:n,rotation:r,offsetX:i=0,offsetY:a=0,dontFlip:o=!1}){this.viewBox=e,this.userUnit=t,this.scale=n,this.rotation=r,this.offsetX=i,this.offsetY=a,n*=t;let s=(e[2]+e[0])/2,c=(e[3]+e[1])/2,l,u,d,f;switch(r%=360,r<0&&(r+=360),r){case 180:l=-1,u=0,d=0,f=1;break;case 90:l=0,u=1,d=1,f=0;break;case 270:l=0,u=-1,d=-1,f=0;break;case 0:l=1,u=0,d=0,f=-1;break;default:throw Error(`PageViewport: Invalid rotation, must be a multiple of 90 degrees.`)}o&&(d=-d,f=-f);let p,m,h,g;l===0?(p=Math.abs(c-e[1])*n+i,m=Math.abs(s-e[0])*n+a,h=(e[3]-e[1])*n,g=(e[2]-e[0])*n):(p=Math.abs(s-e[0])*n+i,m=Math.abs(c-e[1])*n+a,h=(e[2]-e[0])*n,g=(e[3]-e[1])*n),this.transform=[l*n,u*n,d*n,f*n,p-l*n*s-d*n*c,m-u*n*s-f*n*c],this.width=h,this.height=g}get rawDims(){let e=this.viewBox;return M(this,`rawDims`,{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:t=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:a=!1}={}){return new e({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:n,offsetX:r,offsetY:i,dontFlip:a})}convertToViewportPoint(e,t){let n=[e,t];return I.applyTransform(n,this.transform),n}convertToPdfPoint(e,t){let n=[e,t];return I.applyInverseTransform(n,this.transform),n}},ve=class e{static textContent(t){let n=[],r={items:n,styles:Object.create(null)};function i(t){if(!t)return;let r=null,a=t.name;if(a===`#text`)r=t.value;else if(e.shouldBuildText(a))t?.attributes?.textContent?r=t.attributes.textContent:t.value&&(r=t.value);else return;if(r!==null&&n.push({str:r}),t.children)for(let e of t.children)i(e)}return i(t),r}static shouldBuildText(e){return e!==`textarea`&&e!==`input`&&e!==`option`&&e!==`select`}},ye=/url\(|image-set\(/i,be=/^on/i,xe=class{static get _allowedHtmlElements(){return M(this,`_allowedHtmlElements`,new Set([`a`,`b`,`br`,`button`,`div`,`i`,`img`,`input`,`label`,`li`,`ol`,`option`,`p`,`select`,`span`,`sub`,`sup`,`textarea`,`ul`]))}static get _allowedSvgElements(){return M(this,`_allowedSvgElements`,new Set([`ellipse`,`line`,`path`,`rect`,`svg`]))}static get _allowedRichTextElements(){return M(this,`_allowedRichTextElements`,new Set([`a`,`b`,`br`,`div`,`i`,`li`,`ol`,`p`,`span`,`sub`,`sup`,`ul`]))}static get _allowedRichTextAttributes(){return M(this,`_allowedRichTextAttributes`,new Set([`class`,`dir`,`style`]))}static get _allowedRichTextStyles(){return M(this,`_allowedRichTextStyles`,new Set(`color.font.fontFamily.fontSize.fontStretch.fontStyle.fontWeight.kerningMode.letterSpacing.lineHeight.margin.marginBottom.marginLeft.marginRight.marginTop.orphans.paddingLeft.paddingRight.breakAfter.breakBefore.breakInside.tabInterval.tabStop.textAlign.textDecoration.textIndent.transform.verticalAlign.widows`.split(`.`)))}static setupStorage(e,t,n,r,i){let a=r.getValue(t,{value:null});switch(n.name){case`textarea`:if(a.value!==null&&(e.textContent=a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})});break;case`input`:if(n.attributes.type===`radio`||n.attributes.type===`checkbox`){if(a.value===n.attributes.xfaOn?e.setAttribute(`checked`,!0):a.value===n.attributes.xfaOff&&e.removeAttribute(`checked`),i===`print`)break;e.addEventListener(`change`,e=>{r.setValue(t,{value:e.target.checked?e.target.getAttribute(`xfaOn`):e.target.getAttribute(`xfaOff`)})})}else{if(a.value!==null&&e.setAttribute(`value`,a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})})}break;case`select`:if(a.value!==null){e.setAttribute(`value`,a.value);for(let e of n.children)e.attributes.value===a.value?e.attributes.selected=!0:Object.hasOwn(e.attributes,`selected`)&&delete e.attributes.selected}e.addEventListener(`input`,e=>{let n=e.target.options,i=n.selectedIndex===-1?``:n[n.selectedIndex].value;r.setValue(t,{value:i})})}}static setAttributes({html:e,element:t,storage:n=null,intent:r,linkService:i}){let{attributes:a}=t,o=e instanceof HTMLAnchorElement;a.type===`radio`&&(a.name=`${a.name}-${r}`);for(let[t,n]of Object.entries(a))if(n!=null&&!be.test(t)&&!(r===`richText`&&!this._allowedRichTextAttributes.has(t)))switch(t){case`class`:n.length&&e.setAttribute(t,n.join(` `));break;case`dataId`:break;case`id`:e.setAttribute(`data-element-id`,n);break;case`style`:if(r===`richText`){let t=this._allowedRichTextStyles;for(let[r,i]of Object.entries(n))t.has(r)&&!ye.test(i)&&(e.style[r]=i)}else Object.assign(e.style,n);break;case`textContent`:e.textContent=n;break;default:(!o||t!==`href`&&t!==`newWindow`)&&e.setAttribute(t,n)}o&&i?.addLinkAttributes(e,a.href,a.newWindow),n&&a.dataId&&this.setupStorage(e,a.dataId,t,n)}static#e(e,t,n){return n===`richText`?!t&&this._allowedRichTextElements.has(e)?document.createElement(e):null:t?t===a&&this._allowedSvgElements.has(e)?document.createElementNS(a,e):null:this._allowedHtmlElements.has(e)?document.createElement(e):null}static render(e){let t=e.annotationStorage,n=e.linkService,r=e.xfaHtml,i=e.intent||`display`,a=this.#e(r.name,r.attributes?.xmlns,i)??document.createElement(`div`);r.attributes&&this.setAttributes({html:a,element:r,intent:i,linkService:n});let o=i!==`richText`,s=e.div;if(s.append(a),e.viewport){let t=`matrix(${e.viewport.transform.join(`,`)})`;s.style.transform=t}o&&s.setAttribute(`class`,`xfaLayer xfaFont`);let c=[];if(r.children.length===0){if(r.value){let e=document.createTextNode(r.value);a.append(e),o&&ve.shouldBuildText(r.name)&&c.push(e)}return{textDivs:c}}let l=[[r,-1,a]];for(;l.length>0;){let[e,r,a]=l.at(-1);if(r+1===e.children.length){l.pop();continue}let s=e.children[++l.at(-1)[1]];if(s===null)continue;let{name:u}=s;if(u===`#text`){let e=document.createTextNode(s.value);c.push(e),a.append(e);continue}let d=this.#e(u,s.attributes?.xmlns,i);if(d){if(a.append(d),s.attributes&&this.setAttributes({html:d,element:s,storage:t,intent:i,linkService:n}),s.children?.length>0)l.push([s,-1,d]);else if(s.value){let e=document.createTextNode(s.value);o&&ve.shouldBuildText(u)&&c.push(e),d.append(e)}}}for(let e of s.querySelectorAll(`.xfaNonInteractive input, .xfaNonInteractive textarea`))e.setAttribute(`readOnly`,!0);return{textDivs:c}}static update(e){let t=`matrix(${e.viewport.transform.join(`,`)})`;e.div.style.transform=t,e.div.hidden=!1}static getPageViewport(e,{scale:t=1,rotation:n=0}){let{width:r,height:i}=e.attributes.style;return new _e({viewBox:[0,0,parseInt(r,10),parseInt(i,10)],userUnit:1,scale:t,rotation:n})}},Se=class{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF};async function Ce(e,t=`text`){if(Ae(e,document.baseURI)){let n=await fetch(e);if(!n.ok)throw Error(n.statusText);switch(t){case`blob`:return n.blob();case`bytes`:return n.bytes();case`json`:return n.json()}return n.text()}return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open(`GET`,e,!0),i.responseType=t===`bytes`?`arraybuffer`:t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case`bytes`:n(new Uint8Array(i.response));return;case`blob`:case`json`:n(i.response);return}n(i.responseText);return}r(Error(i.statusText))}},i.send(null)})}var we=class extends N{constructor(e,t=0){super(e,`RenderingCancelledException`),this.extraDelay=t}};function Te(e){let t=e.length,n=0;for(;n{try{return new URL(e)}catch{}try{return new URL(decodeURIComponent(e))}catch{}try{return new URL(e,`https://foo.bar`)}catch{}try{return new URL(decodeURIComponent(e),`https://foo.bar`)}catch{}return null})(e);if(!n)return t;let r=e=>{try{let t=decodeURIComponent(e);return t.includes(`/`)&&(t=j(t),t.length===4&&i.test(t))?e:t}catch{return e}},i=/\.pdf$/i,a=j(n.pathname);if(i.test(a))return r(a);if(n.searchParams.size>0){let e=e=>[...e].findLast(e=>i.test(e)),t=e(n.searchParams.values())??e(n.searchParams.keys());if(t)return r(t)}if(n.hash){let e=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(n.hash);if(e)return r(e[0])}return t}var ke=class{#e=new Map;times=[];time(e){this.#e.has(e)&&T(`Timer is already running for ${e}`),this.#e.set(e,Date.now())}timeEnd(e){this.#e.has(e)||T(`Timer has not been started for ${e}`),this.times.push({name:e,start:this.#e.get(e),end:Date.now()}),this.#e.delete(e)}toString(){let e=Math.max(...this.times.map(e=>e.name.length));return this.times.map(t=>`${t.name.padEnd(e)} ${t.end-t.start}ms\n`).join(``)}};function Ae(e,t){let n=t?URL.parse(e,t):URL.parse(e);return/https?:/.test(n?.protocol??``)}function R(e){e.preventDefault()}function z(e){e.preventDefault(),e.stopPropagation()}var je=class{static#e;static toDateObject(e){if(e instanceof Date)return e;if(!e||typeof e!=`string`)return null;this.#e||=RegExp(`^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?`);let t=this.#e.exec(e);if(!t)return null;let n=parseInt(t[1],10),r=parseInt(t[2],10);r=r>=1&&r<=12?r-1:0;let i=parseInt(t[3],10);i=i>=1&&i<=31?i:1;let a=parseInt(t[4],10);a=a>=0&&a<=23?a:0;let o=parseInt(t[5],10);o=o>=0&&o<=59?o:0;let s=parseInt(t[6],10);s=s>=0&&s<=59?s:0;let c=t[7]||`Z`,l=parseInt(t[8],10);l=l>=0&&l<=23?l:0;let u=parseInt(t[9],10)||0;return u=u>=0&&u<=59?u:0,c===`-`?(a+=l,o+=u):c===`+`&&(a-=l,o-=u),new Date(Date.UTC(n,r,i,a,o,s))}};function Me(e){if(e.startsWith(`#`)){let t=e.slice(1);return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16),t.length>=8?parseInt(t.slice(6,8),16)/255:1]}if(e.startsWith(`rgb(`)){let[t,n,r]=e.slice(4,-1).split(`,`).map(e=>parseInt(e,10));return[t,n,r,1]}if(e.startsWith(`rgba(`)){let t=e.slice(5,-1).split(`,`);return[parseInt(t[0],10),parseInt(t[1],10),parseInt(t[2],10),parseFloat(t[3])]}let t=e.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return t?[Math.round(parseFloat(t[1])*255),Math.round(parseFloat(t[2])*255),Math.round(parseFloat(t[3])*255),t[4]!==void 0&&t[4]!==`none`?parseFloat(t[4]):1]:null}function Ne(e){let t=Me(e);return t?t.slice(0,3):(T(`Not a valid color format: "${e}"`),[0,0,0])}function Pe(e){let t=document.createElement(`span`);t.style.visibility=`hidden`,t.style.colorScheme=`only light`,document.body.append(t);for(let n of e.keys()){t.style.color=n;let r=window.getComputedStyle(t).color;e.set(n,Ne(r))}t.remove()}function B(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform();return[t,n,r,i,a,o]}function V(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform().invertSelf();return[t,n,r,i,a,o]}function Fe(e,t,n=!1,r=!0){if(t instanceof _e){let{pageWidth:r,pageHeight:i}=t.rawDims,{style:a}=e,o=`round(down, var(--total-scale-factor) * ${r}px, var(--scale-round-x))`,s=`round(down, var(--total-scale-factor) * ${i}px, var(--scale-round-y))`;!n||t.rotation%180==0?(a.width=o,a.height=s):(a.width=s,a.height=o)}r&&e.setAttribute(`data-main-rotation`,t.rotation)}var Ie=class e{constructor(){let{pixelRatio:t}=e;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(t,n,r,i,a=-1){let o=1/0,s=1/0,c=1/0;r=e.capPixels(r,a),r>0&&(o=Math.sqrt(r/(t*n))),i!==-1&&(s=i/t,c=i/n);let l=Math.min(o,s,c);return this.sx>l||this.sy>l?(this.sx=l,this.sy=l,!0):!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(e,t){if(t>=0){let n=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+t/100));return e>0?Math.min(e,n):n}return e}},Le=[`image/apng`,`image/avif`,`image/bmp`,`image/gif`,`image/jpeg`,`image/png`,`image/svg+xml`,`image/webp`,`image/x-icon`],Re=class{static get isDarkMode(){return M(this,`isDarkMode`,!!window?.matchMedia?.(`(prefers-color-scheme: dark)`).matches)}},ze=class{static get commentForegroundColor(){let e=document.createElement(`span`);e.classList.add(`comment`,`sidebar`);let{style:t}=e;t.width=t.height=`0`,t.display=`none`,t.color=`var(--comment-fg-color)`,document.body.append(e);let{color:n}=window.getComputedStyle(e);return e.remove(),M(this,`commentForegroundColor`,Ne(n))}};function Be(e,t){t=L(t??1,0,1);let n=255*(1-t);return e.map(e=>Math.round(e*t+n))}function Ve(e,t){let n=e[0]/255,r=e[1]/255,i=e[2]/255,a=Math.max(n,r,i),o=Math.min(n,r,i),s=(a+o)/2;if(a===o)t[0]=t[1]=0;else{let e=a-o;switch(t[1]=s<.5?e/(a+o):e/(2-a-o),a){case n:t[0]=((r-i)/e+(ri?(r+.05)/(i+.05):(i+.05)/(r+.05)}var Ge=new Map;function Ke(e,t){let n=e[0]+e[1]*256+e[2]*65536+t[0]*16777216+t[1]*4294967296+t[2]*1099511627776,r=Ge.get(n);if(r)return r;let i=new Float32Array(9),a=i.subarray(0,3),o=i.subarray(3,6);Ve(e,o);let s=i.subarray(6,9);Ve(t,s);let c=s[2]<.5,l=c?12:4.5;if(o[2]=c?Math.sqrt(o[2]):1-Math.sqrt(1-o[2]),We(o,s,a).005;){let n=o[2]=(e+t)/2;c===We(o,s,a){n.delete()},{signal:n._signal}),this.#r.append(r)}get#p(){let e=document.createElement(`div`);return e.className=`divider`,e}async addAltText(e){let t=await e.render();this.#f(t),this.#r.append(t,this.#p),this.#i=e}addComment(e,t=null){if(this.#a)return;let n=e.renderForToolbar();if(!n)return;this.#f(n);let r=this.#o=this.#p;t?(this.#r.insertBefore(n,t),this.#r.insertBefore(r,t)):this.#r.append(n,r),this.#a=e,e.toolbar=this}addColorPicker(e){if(this.#t)return;this.#t=e;let t=e.renderButton();this.#f(t),this.#r.append(t,this.#p)}async addEditSignatureButton(e){let t=this.#s=await e.renderEditButton(this.#n);this.#f(t),this.#r.append(t,this.#p)}removeButton(e){e===`comment`&&(this.#a?.removeToolbarCommentButton(),this.#a=null,this.#o?.remove(),this.#o=null)}async addButton(e,t){switch(e){case`colorPicker`:t&&this.addColorPicker(t);break;case`altText`:t&&await this.addAltText(t);break;case`editSignature`:t&&await this.addEditSignatureButton(t);break;case`delete`:this.addDeleteButton();break;case`comment`:t&&this.addComment(t)}}async addButtonBefore(e,t,n){if(!t&&e===`comment`)return;let r=this.#r.querySelector(n);r&&e===`comment`&&this.addComment(t,r)}updateEditSignatureButton(e){this.#s&&(this.#s.title=e)}remove(){this.#e.remove(),this.#t?.destroy(),this.#t=null}},Xe=class{#e=null;#t=null;#n;constructor(e){this.#n=e}#r(){let e=this.#t=document.createElement(`div`);e.className=`editToolbar`,e.setAttribute(`role`,`toolbar`);let t=this.#n._signal;t instanceof AbortSignal&&!t.aborted&&e.addEventListener(`contextmenu`,R,{signal:t});let n=this.#e=document.createElement(`div`);return n.className=`buttons`,e.append(n),this.#n.hasCommentManager()&&this.#a(`commentButton`,`pdfjs-comment-floating-button`,`pdfjs-comment-floating-button-label`,()=>{this.#n.commentSelection(`floating_button`)}),this.#a(`highlightButton`,`pdfjs-highlight-floating-button1`,`pdfjs-highlight-floating-button-label`,()=>{this.#n.highlightSelection(`floating_button`)}),e}#i(e,t){let n=0,r=0;for(let i of e){let e=i.y+i.height;if(en){r=a,n=e;continue}t?a>r&&(r=a):a=1}static clearPointerType(){e.#r=null}static clearPointerIds(){e.#e=NaN,e.#t=null}static clearTimeStamp(){e.#n=NaN}},$e=class{#e=0;get id(){return`${l}${this.#e++}`}},et=class e{#e=de();#t=0;#n=null;static get _isSVGFittingCanvas(){let e=`data:image/svg+xml;charset=UTF-8,`,t=new OffscreenCanvas(1,3).getContext(`2d`,{willReadFrequently:!0}),n=new Image;n.src=e;let r=n.decode().then(()=>(t.drawImage(n,0,0,1,1,0,0,1,3),new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]===0));return M(this,`_isSVGFittingCanvas`,r)}async#r(t,n){this.#n||=new Map;let r=this.#n.get(t);if(r===null)return null;if(r?.bitmap)return r.refCounter+=1,r;try{r||={bitmap:null,id:`image_${this.#e}_${this.#t++}`,refCounter:0,isSvg:!1};let t;if(typeof n==`string`?(r.url=n,t=await Ce(n,`blob`)):n instanceof File?t=r.file=n:n instanceof Blob&&(t=n),t.type===`image/svg+xml`){let n=e._isSVGFittingCanvas,i=new FileReader,a=new Image,o=new Promise((e,t)=>{a.onload=()=>{r.bitmap=a,r.isSvg=!0,e()},i.onload=async()=>{let e=r.svgUrl=i.result;a.src=await n?`${e}#svgView(preserveAspectRatio(none))`:e},a.onerror=i.onerror=t});i.readAsDataURL(t),await o}else r.bitmap=await createImageBitmap(t);r.refCounter=1}catch(e){T(e),r=null}return this.#n.set(t,r),r&&this.#n.set(r.id,r),r}async getFromFile(e){let{lastModified:t,name:n,size:r,type:i}=e;return this.#r(`${t}_${n}_${r}_${i}`,e)}async getFromUrl(e){return this.#r(e,e)}async getFromBlob(e,t){let n=await t;return this.#r(e,n)}async getFromId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){let{blobPromise:e}=t;return delete t.blobPromise,this.getFromBlob(t.id,e)}return this.getFromUrl(t.url)}getFromCanvas(e,t){this.#n||=new Map;let n=this.#n.get(e);if(n?.bitmap)return n.refCounter+=1,n;let r=new OffscreenCanvas(t.width,t.height);return r.getContext(`2d`).drawImage(t,0,0),n={bitmap:r.transferToImageBitmap(),id:`image_${this.#e}_${this.#t++}`,refCounter:1,isSvg:!1},this.#n.set(e,n),this.#n.set(n.id,n),n}getSvgUrl(e){let t=this.#n.get(e);return t?.isSvg?t.svgUrl:null}deleteId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t||(--t.refCounter,t.refCounter!==0))return;let{bitmap:n}=t;if(!t.url&&!t.file){let e=new OffscreenCanvas(n.width,n.height);e.getContext(`bitmaprenderer`).transferFromImageBitmap(n),t.blobPromise=e.convertToBlob()}n.close?.(),t.bitmap=null}isValidId(e){return e.startsWith(`image_${this.#e}_`)}},tt=class{#e=[];#t=!1;#n;#r=-1;constructor(e=128){this.#n=e}add({cmd:e,undo:t,post:n,mustExec:r,type:i=NaN,overwriteIfSameType:a=!1,keepUndo:o=!1}){if(r&&e(),this.#t)return;let s={cmd:e,undo:t,post:n,type:i};if(this.#r===-1){this.#e.length>0&&(this.#e.length=0),this.#r=0,this.#e.push(s);return}if(a&&this.#e[this.#r].type===i){o&&(s.undo=this.#e[this.#r].undo),this.#e[this.#r]=s;return}let c=this.#r+1;c===this.#n?this.#e.splice(0,1):(this.#r=c,c=0;t--)if(this.#e[t].type!==e){this.#e.splice(t+1,this.#r-t),this.#r=t;return}this.#e.length=0,this.#r=-1}}destroy(){this.#e=null}},nt=class e{static ALT=1;static CTRL=2;static META=4;static SHIFT=8;constructor(t){this.callbacks=new Map;let{isMac:n}=F.platform;for(let[r,i,a={}]of t){let t=r.some(e=>e.startsWith(`mac+`));for(let o of r){let r=o;if(t){let e=o.startsWith(`mac+`);if(n!==e)continue;e&&(r=o.slice(4))}let[s,c]=e.#e(r);s!==null&&this.callbacks.getOrInsertComputed(s,pe).push({callback:i,options:a,modifiers:c})}}}static#e(t){let n=null,r=0;for(let i of t.split(`+`)){if(i=i.trim(),!i)continue;let a=i.toUpperCase(),o=e[a];if(o){r|=o;continue}if(n!==null){T(`KeyboardManager: multiple keys in shortcut "${t}"`);break}n=a===`SPACE`?` `:i}return n===null&&T(`KeyboardManager: no key found in shortcut "${t}"`),[n,r]}static#t(e){let t=/^(?:Key([A-Z])|(?:Digit|Numpad)(\d))$/.exec(e);return t?t[1]?.toLowerCase()??t[2]:null}exec(t,n){let r=this.callbacks.get(n.key);if(!r){if(/^[a-z]$/i.test(n.key))return;let t=e.#t(n.code);if(t===null||t===n.key||(r=this.callbacks.get(t),!r))return}let i=(n.altKey?e.ALT:0)|(n.ctrlKey?e.CTRL:0)|(n.metaKey?e.META:0)|(n.shiftKey?e.SHIFT:0),a=r.find(e=>e.modifiers===i);if(!a)return;let{callback:o,options:{bubbles:s=!1,args:c=[],checker:l=null}}=a;l&&!l(t,n)||(o.bind(t,...c,n)(),s||z(n))}},rt=class e{static _colorsMapping=new Map([[`CanvasText`,[0,0,0]],[`Canvas`,[255,255,255]]]);get _colors(){let e=new Map([[`CanvasText`,null],[`Canvas`,null]]);return Pe(e),M(this,`_colors`,e)}convert(t){let n=Ne(t);if(!window.matchMedia(`(forced-colors: active)`).matches)return n;for(let[t,r]of this._colors)if(r.every((e,t)=>e===n[t]))return e._colorsMapping.get(t);return n}getHexCode(e){let t=this._colors.get(e);return t?I.makeHexColor(...t):e}},it=class e{#e=new AbortController;#t=null;#n=null;#r=new Map;#i=new Map;#a=null;#o=null;#s=null;#c=null;#l=new tt;#u=null;#d=null;#f=null;#p=0;#m=new Set;#h=null;#g=null;#_=new Set;_editorUndoBar=null;#v=!1;#y=!1;#b=!1;#x=null;#S=null;#C=null;#w=null;#T=!1;#E=null;#D=new $e;#O=!1;#k=!1;#A=!1;#j=null;#M=null;#N=null;#P=null;#F=null;#I=u.NONE;#L=new Set;#R=null;#z=null;#B=null;#V=null;#H=null;#U={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#W=[0,0];#G=null;#K=null;#q=null;#J=null;#Y=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.#K.contains(document.activeElement)&&document.activeElement.tagName!==`BUTTON`&&e.hasSomethingToControl(),r=(e,{target:t})=>{if(t instanceof HTMLInputElement){let{type:e}=t;return e!==`text`&&e!==`number`}return!0},i=this.TRANSLATE_SMALL,a=this.TRANSLATE_BIG;return M(this,`_keyboardManager`,new nt([[[`ctrl+a`,`mac+meta+a`],t.selectAll,{checker:r}],[[`ctrl+z`,`mac+meta+z`],t.undo,{checker:r}],[[`ctrl+y`,`ctrl+shift+z`,`mac+meta+shift+z`,`ctrl+shift+Z`,`mac+meta+shift+Z`],t.redo,{checker:r}],[[`Backspace`,`alt+Backspace`,`ctrl+Backspace`,`shift+Backspace`,`mac+Backspace`,`mac+alt+Backspace`,`mac+ctrl+Backspace`,`Delete`,`ctrl+Delete`,`shift+Delete`,`mac+Delete`],t.delete,{checker:r}],[[`Enter`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#K.contains(t)&&!e.isEnterHandled}],[[`Space`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#K.contains(document.activeElement)}],[[`Escape`],t.unselectAll],[[`ArrowLeft`],t.translateSelectedEditors,{args:[-i,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t.translateSelectedEditors,{args:[-a,0],checker:n}],[[`ArrowRight`],t.translateSelectedEditors,{args:[i,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t.translateSelectedEditors,{args:[a,0],checker:n}],[[`ArrowUp`],t.translateSelectedEditors,{args:[0,-i],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t.translateSelectedEditors,{args:[0,-a],checker:n}],[[`ArrowDown`],t.translateSelectedEditors,{args:[0,i],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t.translateSelectedEditors,{args:[0,a],checker:n}]]))}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this._signal=this.#e.signal;this.#K=e,this.#q=t,this.#J=n,this.#o=r,this.#u=i,this.#z=a,this.#H=s,this._eventBus=o;let _={signal:g,...Ze};o.on(`editingaction`,this.onEditingAction.bind(this),_),o.on(`pagechanging`,this.onPageChanging.bind(this),_),o.on(`scalechanging`,this.onScaleChanging.bind(this),_),o.on(`rotationchanging`,this.onRotationChanging.bind(this),_),o.on(`setpreference`,this.onSetPreference.bind(this),_),o.on(`switchannotationeditorparams`,e=>this.updateParams(e.type,e.value),_),window.addEventListener(`pointerdown`,()=>{this.#k=!0},{capture:!0,signal:g}),window.addEventListener(`pointerup`,()=>{this.#k=!1},{capture:!0,signal:g}),window.addEventListener(`beforeunload`,this.endCurrentEditing.bind(this),{capture:!0,signal:g}),this.#te(),this.#ce(),this.#ie(),this.#s=s.annotationStorage,this.#x=s.filterFactory,this.#B=c,this.#w=l||null,this.#v=u,this.#y=d,this.#b=f,this.#F=p||null,this.viewParameters={realScale:Se.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=m||null,this._supportsPinchToZoom=h!==!1,i?.setSidebarUiManager(this)}destroy(){this.#Y?.resolve(),this.#Y=null,this.#e?.abort(),this.#e=null,this._signal=null;for(let e of this.#i.values())e.destroy();this.#i.clear(),this.#r.clear(),this.#_.clear(),this.#P?.clear(),this.#t=null,this.#L.clear(),this.#l.destroy(),this.#o?.destroy(),this.#u?.destroy(),this.#z?.destroy(),this.#E?.hide(),this.#E=null,this.#N?.destroy(),this.#N=null,this.#n=null,this.#S&&=(clearTimeout(this.#S),null),this.#G&&=(clearTimeout(this.#G),null),this._editorUndoBar?.destroy(),this.#H=null}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return this.#F}get useNewAltTextFlow(){return this.#y}get useNewAltTextWhenAddingImage(){return this.#b}get hcmFilter(){return M(this,`hcmFilter`,this.#B?this.#x.addHCMFilter(this.#B.foreground,this.#B.background):`none`)}get direction(){return M(this,`direction`,getComputedStyle(this.#K).direction)}get _highlightColors(){return M(this,`_highlightColors`,this.#w?new Map(this.#w.split(`,`).map(e=>(e=e.split(`=`).map(e=>e.trim()),e[1]=e[1].toUpperCase(),e))):null)}get highlightColors(){let{_highlightColors:e}=this;if(!e)return M(this,`highlightColors`,null);let t=new Map,n=!!this.#B;for(let[r,i]of e){let e=r.endsWith(`_HCM`);if(n&&e){t.set(r.replace(`_HCM`,``),i);continue}!n&&!e&&t.set(r,i)}return M(this,`highlightColors`,t)}get highlightColorNames(){return M(this,`highlightColorNames`,this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}getNonHCMColor(e){if(!this._highlightColors)return e;let t=this.highlightColorNames.get(e);return this._highlightColors.get(t)||e}getNonHCMColorName(e){return this.highlightColorNames.get(e)||e}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#f=e}setMainHighlightColorPicker(e){this.#N=e}editAltText(e,t=!1){this.#o?.editAltText(this,e,t)}hasCommentManager(){return!!this.#u}editComment(e,t,n,r){this.#u?.showDialog(this,e,t,n,r)}selectComment(e,t){(this.#i.get(e)?.getEditorByUID(t))?.toggleComment(!0,!0)}updateComment(e){this.#u?.updateComment(e.getData())}updatePopupColor(e){this.#u?.updatePopupColor(e)}removeComment(e){this.#u?.removeComments([e.uid])}deleteComment(e,t){let n=()=>{e.comment=t};this.addCommands({cmd:()=>{this._editorUndoBar?.show(n,`comment`),this.toggleComment(null),e.comment=null},undo:n,mustExec:!0})}toggleComment(e,t,n=void 0){this.#u?.toggleCommentPopup(e,t,n)}makeCommentColor(e,t){return e&&this.#u?.makeCommentColor(e,t)||null}getCommentDialogElement(){return this.#u?.dialogElement||null}async waitForEditorsRendered(e){if(this.#i.has(e-1))return;let{resolve:t,promise:n}=Promise.withResolvers(),r=n=>{n.pageNumber===e&&(this._eventBus.off(`editorsrendered`,r),t())};this._eventBus.on(`editorsrendered`,r,Ze),await n}getSignature(e){this.#z?.getSignature({uiManager:this,editor:e})}get signatureManager(){return this.#z}switchToMode(e,t){this._eventBus.on(`annotationeditormodechanged`,t,{once:!0,signal:this._signal,...Ze}),this._eventBus.dispatch(`showannotationeditorui`,{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch(`setpreference`,{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){e===`enableNewAltTextWhenAddingImage`&&(this.#b=t)}onPageChanging({pageNumber:e}){this.#p=e-1}deletePage(e){for(let t of this.getEditors(e))t.remove();this.#i.delete(e),this.#p===e&&(this.#p=0)}focusMainContainer(){this.#K.focus()}findParent(e,t){for(let n of this.#i.values()){let{x:r,y:i,width:a,height:o}=n.div.getBoundingClientRect();if(e>=r&&e<=r+a&&t>=i&&t<=i+o)return n}return null}disableUserSelect(e=!1){this.#q.classList.toggle(`noUserSelect`,e)}addShouldRescale(e){this.#_.add(e)}removeShouldRescale(e){this.#_.delete(e)}onScaleChanging({scale:e}){this.commitOrRemove(),this.viewParameters.realScale=e*Se.PDF_TO_CSS_UNITS;for(let e of this.#_)e.onScaleChanging();this.#f?.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}#X({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e}#Z(e){let{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(let t of this.#i.values())if(t.hasTextLayer(e))return t;return null}highlightSelection(e=``,t=!1){let n=document.getSelection();if(!n||n.isCollapsed)return;let{anchorNode:r,anchorOffset:i,focusNode:a,focusOffset:o}=n,s=n.toString(),c=this.#X(n).closest(`.textLayer`),l=this.getSelectionBoxes(c);if(!l)return;n.empty();let d=this.#Z(c),f=this.#I===u.NONE,p=()=>{let n=d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:l,anchorNode:r,anchorOffset:i,focusNode:a,focusOffset:o,text:s});f&&this.showAllEditors(`highlight`,!0,!0),t&&n?.editComment()};if(f){this.switchToMode(u.HIGHLIGHT,p);return}p()}commentSelection(e=``){this.highlightSelection(e,!0)}endCurrentEditing(){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#Q(){let e=document.getSelection();if(!e||e.isCollapsed)return;let t=this.#X(e).closest(`.textLayer`),n=this.getSelectionBoxes(t);n&&(this.#E||=new Xe(this),this.#E.show(t,n,this.direction===`ltr`))}getAndRemoveDataFromAnnotationStorage(e){if(!this.#s)return null;let t=`${l}${e}`,n=this.#s.getRawValue(t);return n&&this.#s.remove(t),n}addToAnnotationStorage(e){!e.isEmpty()&&this.#s&&!this.#s.has(e.id)&&this.#s.setValue(e.id,e)}a11yAlert(e,t=null){let n=this.#J;n&&(n.setAttribute(`data-l10n-id`,e),t?n.setAttribute(`data-l10n-args`,JSON.stringify(t)):n.removeAttribute(`data-l10n-args`))}#$(){let e=document.getSelection();if(!e||e.isCollapsed){this.#R&&(this.#E?.hide(),this.#R=null,this.#le({hasSelectedText:!1}));return}let{anchorNode:t}=e;if(t===this.#R)return;let n=this.#X(e).closest(`.textLayer`);if(!n){this.#R&&(this.#E?.hide(),this.#R=null,this.#le({hasSelectedText:!1}));return}if(this.#E?.hide(),this.#R=t,this.#le({hasSelectedText:!0}),(this.#I===u.HIGHLIGHT||this.#I===u.NONE)&&(this.#I===u.HIGHLIGHT&&this.showAllEditors(`highlight`,!0,!0),this.#T=this.isShiftKeyDown,!this.isShiftKeyDown)){let e=this.#I===u.HIGHLIGHT?this.#Z(n):null;if(e?.toggleDrawing(),this.#k){let t=new AbortController,n=this.combinedSignal(t),r=n=>{(n.type!==`pointerup`||n.button===0)&&(t.abort(),e?.toggleDrawing(!0),n.type===`pointerup`&&this.#ee(`main_toolbar`))};window.addEventListener(`pointerup`,r,{signal:n}),window.addEventListener(`blur`,r,{signal:n})}else e?.toggleDrawing(!0),this.#ee(`main_toolbar`)}}#ee(e=``){this.#I===u.HIGHLIGHT?this.highlightSelection(e):this.#v&&this.#Q()}#te(){document.addEventListener(`selectionchange`,this.#$.bind(this),{signal:this._signal})}#ne(){if(this.#C)return;this.#C=new AbortController;let e=this.combinedSignal(this.#C);window.addEventListener(`focus`,this.focus.bind(this),{signal:e}),window.addEventListener(`blur`,this.blur.bind(this),{signal:e})}#re(){this.#C?.abort(),this.#C=null}blur(){if(this.isShiftKeyDown=!1,this.#T&&(this.#T=!1,this.#ee(`main_toolbar`)),!this.hasSelection)return;let{activeElement:e}=document;for(let t of this.#L)if(t.div.contains(e)){this.#M=[t,e],t._focusEventsAllowed=!1;break}}focus(){if(!this.#M)return;let[e,t]=this.#M;this.#M=null,t.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}#ie(){if(this.#j)return;this.#j=new AbortController;let e=this.combinedSignal(this.#j);window.addEventListener(`keydown`,this.keydown.bind(this),{signal:e}),window.addEventListener(`keyup`,this.keyup.bind(this),{signal:e})}#ae(){this.#j?.abort(),this.#j=null}#oe(){if(this.#d)return;this.#d=new AbortController;let e=this.combinedSignal(this.#d);document.addEventListener(`copy`,this.copy.bind(this),{signal:e}),document.addEventListener(`cut`,this.cut.bind(this),{signal:e}),document.addEventListener(`paste`,this.paste.bind(this),{signal:e})}#se(){this.#d?.abort(),this.#d=null}#ce(){let e=this._signal;document.addEventListener(`dragover`,this.dragOver.bind(this),{signal:e}),document.addEventListener(`drop`,this.drop.bind(this),{signal:e})}addEditListeners(){this.#ie(),this.setEditingState(!0)}removeEditListeners(){this.#ae(),this.setEditingState(!1)}dragOver(e){for(let{type:t}of e.dataTransfer.items)for(let n of this.#g)if(n.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect=`copy`,e.preventDefault();return}}drop(e){for(let t of e.dataTransfer.items)for(let n of this.#g)if(n.isHandlingMimeForPasting(t.type)){n.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){if(e.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let t=[];for(let e of this.#L){let n=e.serialize(!0);n&&t.push(n)}t.length!==0&&e.clipboardData.setData(`application/pdfjs`,JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();let{clipboardData:t}=e;for(let e of t.items)for(let t of this.#g)if(t.isHandlingMimeForPasting(e.type)){t.paste(e,this.currentLayer);return}let n=t.getData(`application/pdfjs`);if(!n)return;try{n=JSON.parse(n)}catch(e){T(`paste: "${e.message}".`);return}if(!Array.isArray(n))return;this.unselectAll();let r=this.currentLayer;try{let e=[];for(let t of n){let n=await r.deserialize(t);if(!n)return;e.push(n)}this.addCommands({cmd:()=>{for(let t of e)this.#pe(t);this.#ge(e)},undo:()=>{for(let t of e)t.remove()},mustExec:!0})}catch(e){T(`paste: "${e.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key===`Shift`&&(this.isShiftKeyDown=!0),this.#I!==u.NONE&&!this.isEditorHandlingKeyboard&&e._keyboardManager.exec(this,t)}keyup(e){this.isShiftKeyDown&&e.key===`Shift`&&(this.isShiftKeyDown=!1,this.#T&&(this.#T=!1,this.#ee(`main_toolbar`)))}onEditingAction({name:e}){switch(e){case`undo`:case`redo`:case`delete`:case`selectAll`:this[e]();break;case`highlightSelection`:this.highlightSelection(`context_menu`);break;case`commentSelection`:this.commentSelection(`context_menu`)}}updatePageIndex(e,t){for(let n of this.getEditors(e))n.pageIndex=t;let n=this.#a.get(e);n&&(n.pageIndex=t,this.#i.set(t,n),this.#O?n.enable():n.disable())}startUpdatePages(){this.#a=new Map(this.#i),this.#i.clear()}endUpdatePages(){this.#a=null}clonePage(e,t){for(let n of this.getEditors(e)){let e=n.serialize(n.mode!==u.HIGHLIGHT);e&&(e.pageIndex=t,e.id=this.getId(),e.isClone=!0,delete e.popupRef,this.#s.setValue(e.id,e))}}findClonesForPage(e){let t=[],{pageIndex:n}=e;for(let[r,i]of this.#s)i.pageIndex===n&&i.isClone&&(this.#s.remove(r),t.push(e.deserialize(i).then(t=>{t&&(t.isClone=!0,e.addOrRebuild(t))})));return Promise.all(t)}#le(e){Object.entries(e).some(([e,t])=>this.#U[e]!==t)&&(this._eventBus.dispatch(`editingstateschanged`,{source:this,details:Object.assign(this.#U,e)}),this.#I===u.HIGHLIGHT&&e.hasSelectedEditor===!1&&this.#ue([[d.HIGHLIGHT_FREE,!0]]))}#ue(e){this._eventBus.dispatch(`annotationeditorparamschanged`,{source:this,details:e})}setEditingState(e){e?(this.#ne(),this.#oe(),this.#le({isEditing:this.#I!==u.NONE,isEmpty:this.#he(),hasSomethingToUndo:this.#l.hasSomethingToUndo(),hasSomethingToRedo:this.#l.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#re(),this.#se(),this.#le({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!this.#g){this.#g=e;for(let e of this.#g)this.#ue(e.defaultPropertiesToUpdate)}}getId(){return this.#D.id}get currentLayer(){return this.#i.get(this.#p)}getLayer(e){return this.#i.get(e)}get currentPageIndex(){return this.#p}addLayer(e){this.#i.set(e.pageIndex,e),this.#O?e.enable():e.disable()}removeLayer(e){this.#i.delete(e.pageIndex)}async updateMode(e,t=null,n=!1,r=!1,i=!1,a=!1){if(this.#I!==e&&!(this.#Y&&(await this.#Y.promise,!this.#Y))){if(this.#Y=Promise.withResolvers(),this.#f?.commitOrRemove(),this.#I===u.POPUP&&this.#u?.hideSidebar(),this.#u?.destroyPopup(),this.#I=e,e===u.NONE){this.setEditingState(!1),this.#fe();for(let e of this.#r.values())e.hideStandaloneCommentButton();this._editorUndoBar?.hide(),this.toggleComment(null),this.#Y.resolve();return}for(let e of this.#r.values())e.addStandaloneCommentButton();e===u.SIGNATURE&&await this.#z?.loadSignatures(),n&&H.clearPointerType(),this.setEditingState(!0),await this.#de(),this.unselectAll();for(let t of this.#i.values())t.updateMode(e);if(e===u.POPUP){this.#n||=await this.#H.getAnnotationsByType(new Set(this.#g.map(e=>e._editorType)));let e=new Set,t=[];for(let n of this.#r.values()){let{annotationElementId:r,hasComment:i,deleted:a}=n;r&&e.add(r),i&&!a&&t.push(n.getData())}for(let n of this.#n){let{id:r,popupRef:i,contentsObj:a}=n;i&&a?.str&&!e.has(r)&&!this.#m.has(r)&&t.push(n)}this.#u?.showSidebar(t)}if(!t){r&&this.addNewEditorFromKeyboard(),this.#Y.resolve();return}for(let e of this.#r.values())e.uid===t?(this.setSelected(e),a?e.editComment():i?e.enterInEditMode():e.focus()):e.unselect();this.#Y.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e.mode!==this.#I&&this._eventBus.dispatch(`switchannotationeditormode`,{source:this,...e})}updateParams(e,t){if(this.#g){switch(e){case d.CREATE:this.currentLayer.addNewEditor(t);return;case d.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:{type:`highlight`,action:`toggle_visibility`}}}),(this.#V||=new Map).set(e,t),this.showAllEditors(`highlight`,t)}if(this.hasSelection)for(let n of this.#L)n.updateParams(e,t);else for(let n of this.#g)n.updateDefaultParams(e,t)}}showAllEditors(e,t,n=!1){for(let n of this.#r.values())n.editorType===e&&n.show(t);(this.#V?.get(d.HIGHLIGHT_SHOW_ALL)??!0)!==t&&this.#ue([[d.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(this.#A!==e){this.#A=e;for(let t of this.#i.values())e?t.disableClick():t.enableClick(),t.div.classList.toggle(`waiting`,e)}}async#de(){if(!this.#O){this.#O=!0;let e=[];for(let t of this.#i.values())e.push(t.enable());await Promise.all(e);for(let e of this.#r.values())e.enable()}}#fe(){if(this.unselectAll(),this.#O){this.#O=!1;for(let e of this.#i.values())e.disable();for(let e of this.#r.values())e.disable()}}*getEditors(e){for(let t of this.#r.values())t.pageIndex===e&&(yield t)}getEditor(e){return this.#r.get(e)}addEditor(e){this.#r.set(e.id,e)}removeEditor(e){e.div.contains(document.activeElement)&&(this.#S&&clearTimeout(this.#S),this.#S=setTimeout(()=>{this.focusMainContainer(),this.#S=null},0)),this.#r.delete(e.id),e.annotationElementId&&this.#P?.delete(e.annotationElementId),this.unselect(e),(!e.annotationElementId||!this.#m.has(e.annotationElementId))&&this.#s?.remove(e.id)}addDeletedAnnotationElement(e){this.#m.add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return this.#m.has(e)}removeDeletedAnnotationElement(e){this.#m.delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}#pe(e){let t=this.#i.get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))}setActiveEditor(e){this.#t!==e&&(this.#t=e,e&&this.#ue(e.propertiesToUpdate))}get#me(){let e=null;for(e of this.#L);return e}updateUI(e){this.#me===e&&this.#ue(e.propertiesToUpdate)}updateUIForDefaultProperties(e){this.#ue(e.defaultPropertiesToUpdate)}toggleSelected(e){if(this.#L.has(e)){this.#L.delete(e),e.unselect(),this.#le({hasSelectedEditor:this.hasSelection});return}this.#L.add(e),e.select(),this.#ue(e.propertiesToUpdate),this.#le({hasSelectedEditor:!0})}setSelected(e){this.updateToolbar({mode:e.mode,editId:e.uid}),this.#f?.commitOrRemove();for(let t of this.#L)t!==e&&t.unselect();this.#u?.destroyPopup(),this.#L.clear(),this.#L.add(e),e.select(),this.#ue(e.propertiesToUpdate),this.#le({hasSelectedEditor:!0})}get firstSelectedEditor(){return this.#L.values().next().value}unselect(e){e.unselect(),this.#L.delete(e),this.#le({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#L.size!==0}get isEnterHandled(){return this.#L.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#l.undo(),this.#le({hasSomethingToUndo:this.#l.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#he()}),this._editorUndoBar?.hide()}redo(){this.#l.redo(),this.#le({hasSomethingToUndo:!0,hasSomethingToRedo:this.#l.hasSomethingToRedo(),isEmpty:this.#he()})}addCommands(e){this.#l.add(e),this.#le({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#he()})}cleanUndoStack(e){this.#l.cleanType(e)}#he(){if(this.#r.size===0)return!0;if(this.#r.size===1)for(let e of this.#r.values())return e.isEmpty();return!1}delete(){this.commitOrRemove();let e=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!e)return;let t=e?[e]:[...this.#L],n=()=>{this._editorUndoBar?.show(r,t.length===1?t[0].editorType:t.length);for(let e of t)e.remove()},r=()=>{for(let e of t)this.#pe(e)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#ge(e){for(let e of this.#L)e.unselect();this.#L.clear();for(let t of e)t.isEmpty()||(this.#L.add(t),t.select());this.#le({hasSelectedEditor:this.hasSelection})}selectAll(){for(let e of this.#L)e.commit();this.#ge(this.#r.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#I!==u.NONE))&&!this.#f?.commitOrRemove()&&(this.#u?.destroyPopup(),this.hasSelection)){for(let e of this.#L)e.unselect();this.#L.clear(),this.#le({hasSelectedEditor:!1})}}translateSelectedEditors(e,t,n=!1){if(n||this.commitOrRemove(),!this.hasSelection)return;this.#W[0]+=e,this.#W[1]+=t;let[r,i]=this.#W,a=[...this.#L];this.#G&&clearTimeout(this.#G),this.#G=setTimeout(()=>{this.#G=null,this.#W[0]=this.#W[1]=0,this.addCommands({cmd:()=>{for(let e of a)this.#r.has(e.id)&&(e.translateInPage(r,i),e.translationDone())},undo:()=>{for(let e of a)this.#r.has(e.id)&&(e.translateInPage(-r,-i),e.translationDone())},mustExec:!1})},1e3);for(let n of a)n.translateInPage(e,t),n.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#h=new Map;for(let e of this.#L)this.#h.set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#h)return!1;this.disableUserSelect(!1);let e=this.#h;this.#h=null;let t=!1;for(let[{x:n,y:r,pageIndex:i},a]of e)a.newX=n,a.newY=r,a.newPageIndex=i,t||=n!==a.savedX||r!==a.savedY||i!==a.savedPageIndex;if(!t)return!1;let n=(e,t,n,r)=>{if(this.#r.has(e.id)){let i=this.#i.get(r);i?e._setParentAndPosition(i,t,n):(e.pageIndex=r,e.x=t,e.y=n)}};return this.addCommands({cmd:()=>{for(let[t,{newX:r,newY:i,newPageIndex:a}]of e)n(t,r,i,a)},undo:()=>{for(let[t,{savedX:r,savedY:i,savedPageIndex:a}]of e)n(t,r,i,a)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(this.#h)for(let n of this.#h.keys())n.drag(e,t)}rebuild(e){if(e.parent===null){let t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#L.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return this.#t===e}getActive(){return this.#t}getMode(){return this.#I}isEditingMode(){return this.#I!==u.NONE}get imageManager(){return M(this,`imageManager`,new et)}getSelectionBoxes(e){if(!e)return null;let t=document.getSelection();for(let n=0,r=t.rangeCount;n({x:(t-r)/a,y:1-(e+o-n)/i,width:s/a,height:o/i});break;case`180`:o=(e,t,o,s)=>({x:1-(e+o-n)/i,y:1-(t+s-r)/a,width:o/i,height:s/a});break;case`270`:o=(e,t,o,s)=>({x:1-(t+s-r)/a,y:(e-n)/i,width:s/a,height:o/i});break;default:o=(e,t,o,s)=>({x:(e-n)/i,y:(t-r)/a,width:o/i,height:s/a})}let s=[];for(let e=0,n=t.rangeCount;ee.stopPropagation(),{signal:r});let i=e=>{e.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#d&&this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_clicked`,data:{label:this.#p}})};return t.addEventListener(`click`,i,{capture:!0,signal:r}),t.addEventListener(`keydown`,e=>{e.target===t&&e.key===`Enter`&&(this.#o=!0,i(e))},{signal:r}),await this.#m(),t}get#p(){return this.#e&&`added`||this.#e===null&&this.guessedText&&`review`||`missing`}finish(){this.#n&&(this.#n.focus({focusVisible:this.#o}),this.#o=!1)}isEmpty(){return this.#d?this.#e===null:!this.#e&&!this.#t}hasData(){return this.#d?this.#e!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#e===null&&(this.#l=t,this.#u=await e._l10n.get(`pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer`,{generatedAltText:t}),this.#m())}toggleAltTextBadge(e=!1){if(!this.#d||this.#e){this.#s?.remove(),this.#s=null;return}if(!this.#s){let e=this.#s=document.createElement(`div`);e.className=`noAltTextBadge`,this.#c.div.append(e)}this.#s.classList.toggle(`hidden`,!e)}serialize(e){let t=this.#e;return!e&&this.#l===t&&(t=this.#u),{altText:t,decorative:this.#t,guessedText:this.#l,textWithDisclaimer:this.#u}}get data(){return{altText:this.#e,decorative:this.#t}}set data({altText:e,decorative:t,guessedText:n,textWithDisclaimer:r,cancel:i=!1}){n&&(this.#l=n,this.#u=r),(this.#e!==e||this.#t!==t)&&(i||(this.#e=e,this.#t=t),this.#m())}toggle(e=!1){this.#n&&(!e&&this.#a&&(clearTimeout(this.#a),this.#a=null),this.#n.disabled=!e)}shown(){this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_displayed`,data:{label:this.#p}})}destroy(){this.#n?.remove(),this.#n=null,this.#r=null,this.#i=null,this.#s?.remove(),this.#s=null}async#m(){let t=this.#n;if(!t)return;if(this.#d){if(t.classList.toggle(`done`,!!this.#e),t.setAttribute(`data-l10n-id`,e.#f[this.#p]),this.#r?.setAttribute(`data-l10n-id`,e.#f[`${this.#p}-label`]),!this.#e){this.#i?.remove();return}}else{if(!this.#e&&!this.#t){t.classList.remove(`done`),this.#i?.remove();return}t.classList.add(`done`),t.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-edit-button`)}let n=this.#i;if(!n){this.#i=n=document.createElement(`span`),n.className=`tooltip`,n.setAttribute(`role`,`tooltip`),n.id=`alt-text-tooltip-${this.#c.id}`;let e=this.#c._uiManager._signal;e.addEventListener(`abort`,()=>{clearTimeout(this.#a),this.#a=null},{once:!0}),t.addEventListener(`mouseenter`,()=>{this.#a=setTimeout(()=>{this.#a=null,this.#i.classList.add(`show`),this.#c._reportTelemetry({action:`alt_text_tooltip`})},100)},{signal:e}),t.addEventListener(`mouseleave`,()=>{this.#a&&=(clearTimeout(this.#a),null),this.#i?.classList.remove(`show`)},{signal:e})}this.#t?n.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-decorative-tooltip`):(n.removeAttribute(`data-l10n-id`),n.textContent=this.#e),n.parentNode||t.append(n),this.#c.getElementForAltText()?.setAttribute(`aria-describedby`,n.id)}},ot=class{#e=null;#t=null;#n=!1;#r=null;#i=null;#a=null;#o=null;#s=null;#c=!1;#l=null;constructor(e){this.#r=e}renderForToolbar(){let e=this.#t=document.createElement(`button`);return e.className=`comment`,this.#u(e,!1)}renderForStandalone(){let e=this.#e=document.createElement(`button`);e.className=`annotationCommentButton`;let t=this.#r.commentButtonPosition;if(t){let{style:n}=e;n.insetInlineEnd=`calc(${100*(this.#r._uiManager.direction===`ltr`?1-t[0]:t[0])}% - var(--comment-button-dim))`,n.top=`calc(${100*t[1]}% - var(--comment-button-dim))`;let r=this.#r.commentButtonColor;r&&(n.backgroundColor=r)}return this.#u(e,!0)}focusButton(){setTimeout(()=>{(this.#e??this.#t)?.focus()},0)}onUpdatedColor(){if(!this.#e)return;let e=this.#r.commentButtonColor;e&&(this.#e.style.backgroundColor=e),this.#r._uiManager.updatePopupColor(this.#r)}get commentButtonWidth(){return(this.#e?.getBoundingClientRect().width??0)/this.#r.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#l)return this.#l;if(!this.#e)return null;let{x:e,y:t,height:n}=this.#e.getBoundingClientRect(),{x:r,y:i,width:a,height:o}=this.#r.parent.boundingClientRect;return[(e-r)/a,(t+n-i)/o]}set commentPopupPositionInLayer(e){this.#l=e}hasDefaultPopupPosition(){return this.#l===null}removeStandaloneCommentButton(){this.#e?.remove(),this.#e=null}removeToolbarCommentButton(){this.#t?.remove(),this.#t=null}setCommentButtonStates({selected:e,hasPopup:t}){this.#e&&(this.#e.classList.toggle(`selected`,e),this.#e.ariaExpanded=t)}#u(e,t){if(!this.#r._uiManager.hasCommentManager())return null;e.tabIndex=`0`,e.ariaHasPopup=`dialog`,t?(e.ariaControls=`commentPopup`,e.setAttribute(`data-l10n-id`,`pdfjs-show-comment-button`)):(e.ariaControlsElements=[this.#r._uiManager.getCommentDialogElement()],e.setAttribute(`data-l10n-id`,`pdfjs-editor-add-comment-button`));let n=this.#r._uiManager._signal;if(!(n instanceof AbortSignal)||n.aborted)return e;e.addEventListener(`contextmenu`,R,{signal:n}),t&&(e.addEventListener(`focusin`,e=>{this.#r._focusEventsAllowed=!1,z(e)},{capture:!0,signal:n}),e.addEventListener(`focusout`,e=>{this.#r._focusEventsAllowed=!0,z(e)},{capture:!0,signal:n})),e.addEventListener(`pointerdown`,e=>e.stopPropagation(),{signal:n});let r=t=>{t.preventDefault(),e===this.#t?this.edit():this.#r.toggleComment(!0)};return e.addEventListener(`click`,r,{capture:!0,signal:n}),e.addEventListener(`keydown`,t=>{t.target===e&&t.key===`Enter`&&(this.#n=!0,r(t))},{signal:n}),e.addEventListener(`pointerenter`,()=>{this.#r.toggleComment(!1,!0)},{signal:n}),e.addEventListener(`pointerleave`,()=>{this.#r.toggleComment(!1,!1)},{signal:n}),e}edit(e){let t=this.commentPopupPositionInLayer,n,r;if(t)[n,r]=t;else{[n,r]=this.#r.commentButtonPosition;let{width:e,height:t,x:i,y:a}=this.#r;n=i+n*e,r=a+r*t}let i=this.#r.parent.boundingClientRect,{x:a,y:o,width:s,height:c}=i;this.#r._uiManager.editComment(this.#r,a+n*s,o+r*c,{...e,parentDimensions:i})}finish(){this.#t&&(this.#t.focus({focusVisible:this.#n}),this.#n=!1)}isDeleted(){return this.#c||this.#o===``}isEmpty(){return this.#o===null}hasBeenEdited(){return this.isDeleted()||this.#o!==this.#i}serialize(){return this.data}get data(){return{text:this.#o,richText:this.#a,date:this.#s,deleted:this.isDeleted()}}set data(e){if(e!==this.#o&&(this.#a=null),e===null){this.#o=``,this.#c=!0;return}this.#o=e,this.#s=new Date,this.#c=!1}restoreData({text:e,richText:t,date:n}){this.#o=e,this.#a=t,this.#s=n,this.#c=!1}setInitialText(e,t=null){this.#i=e,this.data=e,this.#s=null,this.#a=t}shown(){}destroy(){this.#t?.remove(),this.#t=null,this.#e?.remove(),this.#e=null,this.#o=``,this.#a=null,this.#s=null,this.#r=null,this.#n=!1,this.#c=!1}},st=class e{#e;#t=!1;#n=null;#r;#i;#a;#o;#s=null;#c;#l=null;#u;#d=null;constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:n=null,onPinchStart:r=null,onPinching:i=null,onPinchEnd:a=null,signal:o}){this.#e=e,this.#n=n,this.#r=t,this.#i=r,this.#a=i,this.#o=a,this.#u=new AbortController,this.#c=AbortSignal.any([o,this.#u.signal]),e.addEventListener(`touchstart`,this.#f.bind(this),{passive:!1,signal:this.#c})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Ie.pixelRatio}#f(e){if(this.#r?.())return;if(e.touches.length===1){if(this.#s)return;let e=this.#s=new AbortController,t=AbortSignal.any([this.#c,e.signal]),n=this.#e,r={capture:!0,signal:t,passive:!1},i=e=>{e.pointerType===`touch`&&(this.#s?.abort(),this.#s=null)};n.addEventListener(`pointerdown`,e=>{e.pointerType===`touch`&&(z(e),i(e))},r),n.addEventListener(`pointerup`,i,r),n.addEventListener(`pointercancel`,i,r);return}if(!this.#d){this.#d=new AbortController;let e=AbortSignal.any([this.#c,this.#d.signal]),t=this.#e,n={signal:e,capture:!1,passive:!1};t.addEventListener(`touchmove`,this.#p.bind(this),n);let r=this.#m.bind(this);t.addEventListener(`touchend`,r,n),t.addEventListener(`touchcancel`,r,n),n.capture=!0,t.addEventListener(`pointerdown`,z,n),t.addEventListener(`pointermove`,z,n),t.addEventListener(`pointercancel`,z,n),t.addEventListener(`pointerup`,z,n),this.#i?.()}if(z(e),e.touches.length!==2||this.#n?.()){this.#l=null;return}let[t,n]=e.touches;t.identifier>n.identifier&&([t,n]=[n,t]),this.#l={touch0X:t.screenX,touch0Y:t.screenY,touch1X:n.screenX,touch1Y:n.screenY}}#p(t){if(!this.#l||t.touches.length!==2)return;z(t);let[n,r]=t.touches;n.identifier>r.identifier&&([n,r]=[r,n]);let{screenX:i,screenY:a}=n,{screenX:o,screenY:s}=r,c=this.#l,{touch0X:l,touch0Y:u,touch1X:d,touch1Y:f}=c,p=d-l,m=f-u,h=o-i,g=s-a,_=Math.hypot(h,g)||1,v=Math.hypot(p,m)||1;if(!this.#t&&Math.abs(v-_)<=e.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(c.touch0X=i,c.touch0Y=a,c.touch1X=o,c.touch1Y=s,!this.#t){this.#t=!0;return}let y=[(i+o)/2,(a+s)/2];this.#a?.(y,v,_)}#m(e){e.touches.length>=2||(this.#d&&(this.#d.abort(),this.#d=null,this.#o?.()),this.#l&&(z(e),this.#l=null,this.#t=!1))}destroy(){this.#u?.abort(),this.#u=null,this.#s?.abort(),this.#s=null}},U=class e{#e=null;#t=null;#n=null;#r=null;#i=null;#a=!1;#o=null;#s=``;#c=null;#l=null;#u=null;#d=null;#f=null;#p=``;#m=!1;#h=null;#g=!1;#_=!1;#v=!1;#y=null;#b=0;#x=0;#S=null;#C=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#w=!1;#T=e._zIndex++;static _borderLineWidth=-1;static _colorManager=new rt;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let t=e.prototype._resizeWithKeyboard,n=it.TRANSLATE_SMALL,r=it.TRANSLATE_BIG;return M(this,`_resizerKeyboardManager`,new nt([[[`ArrowLeft`],t,{args:[-n,0]}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t,{args:[-r,0]}],[[`ArrowRight`],t,{args:[n,0]}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t,{args:[r,0]}],[[`ArrowUp`],t,{args:[0,-n]}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t,{args:[0,-r]}],[[`ArrowDown`],t,{args:[0,n]}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t,{args:[0,r]}],[[`Escape`],e.prototype._stopResizingWithKeyboard]]))}constructor(e){this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null,this.annotationElementId=e.annotationElementId||null,this.creationDate=e.creationDate||new Date,this.modificationDate=e.modificationDate||null,this.canAddComment=!0;let{rotation:t,rawDims:{pageWidth:n,pageHeight:r,pageX:i,pageY:a}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[n,r],this.pageTranslation=[i,a];let[o,s]=this.parentDimensions;this.x=e.x/o,this.y=e.y/s,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(e){this.pageIndex=e}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return M(this,`_defaultLineColor`,this._colorManager.getHexCode(`CanvasText`))}static deleteAnnotationElement(e){let t=new ct({id:e._uiManager.getId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(t,n){if(e._l10n??=t,e._l10nAlert??=Object.freeze({highlight:`pdfjs-editor-highlight-added-alert`,freetext:`pdfjs-editor-freetext-added-alert`,ink:`pdfjs-editor-ink-added-alert`,stamp:`pdfjs-editor-stamp-added-alert`,signature:`pdfjs-editor-signature-added-alert`}),e._l10nResizer??=Object.freeze({topLeft:`pdfjs-editor-resizer-top-left`,topMiddle:`pdfjs-editor-resizer-top-middle`,topRight:`pdfjs-editor-resizer-top-right`,middleRight:`pdfjs-editor-resizer-middle-right`,bottomRight:`pdfjs-editor-resizer-bottom-right`,bottomMiddle:`pdfjs-editor-resizer-bottom-middle`,bottomLeft:`pdfjs-editor-resizer-bottom-left`,middleLeft:`pdfjs-editor-resizer-middle-left`}),e._borderLineWidth!==-1)return;let r=getComputedStyle(document.documentElement);e._borderLineWidth=parseFloat(r.getPropertyValue(`--outline-width`))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){E(`Not implemented`)}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#w}set _isDraggable(e){this.#w=e,this.div?.classList.toggle(`draggable`,e)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){let[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#T}setParent(e){e===null?(this.#W(),this.#d?.remove(),this.#d=null):(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions),this.parent=e}focusin(e){this._focusEventsAllowed&&(this.#m?this.#m=!1:this.parent.setSelected(this))}focusout(e){this._focusEventsAllowed&&this.isAttachedToDOM&&(e.relatedTarget?.closest(`#${this.id}`)||(e.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove()))}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,n,r){let[i,a]=this.parentDimensions;[n,r]=this.screenToPageTranslation(n,r),this.x=(e+n)/i,this.y=(t+r)/a,this.fixAndSetPosition()}_moveAfterPaste(e,t){if(this.isClone){delete this.isClone;return}let[n,r]=this.parentDimensions;this.setAt(e*n,t*r,this.width*n,this.height*r),this._onTranslated()}#E([e,t],n,r){[n,r]=this.screenToPageTranslation(n,r),this.x+=n/e,this.y+=r/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(e,t){this.#E(this.parentDimensions,e,t)}translateInPage(e,t){this.#h||=[this.x,this.y,this.width,this.height],this.#E(this.pageDimensions,e,t),this.div.scrollIntoView({block:`nearest`})}translationDone(){this._onTranslated(this.x,this.y)}drag(e,t){this.#h||=[this.x,this.y,this.width,this.height];let{div:n,parentDimensions:[r,i]}=this;if(this.x+=e/r,this.y+=t/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:e,y:t}=this.div.getBoundingClientRect();this.parent.findNewParent(this,e,t)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:o}=this,[s,c]=this.getBaseTranslation();a+=s,o+=c;let{style:l}=n;l.left=`${(100*a).toFixed(2)}%`,l.top=`${(100*o).toFixed(2)}%`,this._onTranslating(a,o),n.scrollIntoView({block:`nearest`})}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!this.#h&&(this.#h[0]!==this.x||this.#h[1]!==this.y)}get _hasBeenResized(){return!!this.#h&&(this.#h[2]!==this.width||this.#h[3]!==this.height)}getBaseTranslation(){let[t,n]=this.parentDimensions,{_borderLineWidth:r}=e,i=r/t,a=r/n;switch(this.rotation){case 90:return[-i,a];case 180:return[i,a];case 270:return[i,-a];default:return[-i,-a]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){let{div:{style:t},pageDimensions:[n,r]}=this,{x:i,y:a,width:o,height:s}=this;if(o*=n,s*=r,i*=n,a*=r,this._mustFixPosition)switch(e){case 0:i=L(i,0,n-o),a=L(a,0,r-s);break;case 90:i=L(i,0,n-s),a=L(a,o,r);break;case 180:i=L(i,o,n),a=L(a,s,r);break;case 270:i=L(i,s,n),a=L(a,0,r-o)}this.x=i/=n,this.y=a/=r;let[c,l]=this.getBaseTranslation();i+=c,a+=l,t.left=`${(100*i).toFixed(2)}%`,t.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#D(e,t,n){switch(n){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}}screenToPageTranslation(t,n){return e.#D(t,n,this.parentRotation)}pageTranslationToScreen(t,n){return e.#D(t,n,360-this.parentRotation)}#O(e){switch(e){case 90:{let[e,t]=this.pageDimensions;return[0,-e/t,t/e,0]}case 180:return[-1,0,0,-1];case 270:{let[e,t]=this.pageDimensions;return[0,e/t,-t/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:e,pageDimensions:[t,n]}=this;return[t*e,n*e]}setDims(){let{div:{style:e},width:t,height:n}=this;e.width=`${(100*t).toFixed(2)}%`,e.height=`${(100*n).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#k(){if(this.#c)return;this.#c=document.createElement(`div`),this.#c.classList.add(`resizers`);let e=this._willKeepAspectRatio?[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`]:[`topLeft`,`topMiddle`,`topRight`,`middleRight`,`bottomRight`,`bottomMiddle`,`bottomLeft`,`middleLeft`],t=this._uiManager._signal;for(let n of e){let e=document.createElement(`div`);this.#c.append(e),e.classList.add(`resizer`,n),e.setAttribute(`data-resizer-name`,n),e.addEventListener(`pointerdown`,this.#A.bind(this,n),{signal:t}),e.addEventListener(`contextmenu`,R,{signal:t}),e.tabIndex=-1}this.div.prepend(this.#c)}#A(e,t){t.preventDefault();let{isMac:n}=F.platform;if(t.button!==0||t.ctrlKey&&n)return;this.#n?.toggle(!1);let r=this._isDraggable;this._isDraggable=!1,this.#l=[t.screenX,t.screenY];let i=new AbortController,a=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener(`pointermove`,this.#N.bind(this,e),{passive:!0,capture:!0,signal:a}),window.addEventListener(`touchmove`,z,{passive:!1,signal:a}),window.addEventListener(`contextmenu`,R,{signal:a}),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let o=this.parent.div.style.cursor,s=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;let c=()=>{i.abort(),this.parent.togglePointerEvents(!0),this.#n?.toggle(!0),this._isDraggable=r,this.parent.div.style.cursor=o,this.div.style.cursor=s,this.#M()};window.addEventListener(`pointerup`,c,{signal:a}),window.addEventListener(`blur`,c,{signal:a})}#j(e,t,n,r){this.width=n,this.height=r,this.x=e,this.y=t,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#M(){if(!this.#u)return;let{savedX:e,savedY:t,savedWidth:n,savedHeight:r}=this.#u;this.#u=null;let i=this.x,a=this.y,o=this.width,s=this.height;(i!==e||a!==t||o!==n||s!==r)&&this.addCommands({cmd:this.#j.bind(this,i,a,o,s),undo:this.#j.bind(this,e,t,n,r),mustExec:!0})}static _round(e){return Math.round(e*1e4)/1e4}#N(t,n){let[r,i]=this.parentDimensions,a=this.x,o=this.y,s=this.width,c=this.height,l=e.MIN_SIZE/r,u=e.MIN_SIZE/i,d=this.#O(this.rotation),f=(e,t)=>[d[0]*e+d[2]*t,d[1]*e+d[3]*t],p=this.#O(360-this.rotation),m=(e,t)=>[p[0]*e+p[2]*t,p[1]*e+p[3]*t],h,g,_=!1,v=!1;switch(t){case`topLeft`:_=!0,h=(e,t)=>[0,0],g=(e,t)=>[e,t];break;case`topMiddle`:h=(e,t)=>[e/2,0],g=(e,t)=>[e/2,t];break;case`topRight`:_=!0,h=(e,t)=>[e,0],g=(e,t)=>[0,t];break;case`middleRight`:v=!0,h=(e,t)=>[e,t/2],g=(e,t)=>[0,t/2];break;case`bottomRight`:_=!0,h=(e,t)=>[e,t],g=(e,t)=>[0,0];break;case`bottomMiddle`:h=(e,t)=>[e/2,t],g=(e,t)=>[e/2,0];break;case`bottomLeft`:_=!0,h=(e,t)=>[0,t],g=(e,t)=>[e,0];break;case`middleLeft`:v=!0,h=(e,t)=>[0,t/2],g=(e,t)=>[e,t/2]}let y=h(s,c),b=g(s,c),x=f(...b),S=e._round(a+x[0]),C=e._round(o+x[1]),w=1,T=1,E,D;if(n.fromKeyboard)({deltaX:E,deltaY:D}=n);else{let{screenX:e,screenY:t}=n,[r,i]=this.#l;[E,D]=this.screenToPageTranslation(e-r,t-i),this.#l[0]=e,this.#l[1]=t}if([E,D]=m(E/r,D/i),_){let e=Math.hypot(s,c);w=T=Math.max(Math.min(Math.hypot(b[0]-y[0]-E,b[1]-y[1]-D)/e,1/s,1/c),l/s,u/c)}else v?w=L(Math.abs(b[0]-y[0]-E),l,1)/s:T=L(Math.abs(b[1]-y[1]-D),u,1)/c;let O=e._round(s*w),k=e._round(c*T);x=f(...g(O,k));let A=S-x[0],j=C-x[1];this.#h||=[this.x,this.y,this.width,this.height],this.width=O,this.height=k,this.x=A,this.y=j,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#n?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#_)return this._editToolbar;this._editToolbar=new Ye(this),this.div.append(this._editToolbar.render());let{toolbarButtons:e}=this;if(e)for(let[t,n]of e)await this._editToolbar.addButton(t,n);return this.hasComment||this._editToolbar.addButton(`comment`,this.addCommentButton()),this._editToolbar.addButton(`delete`),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore(`comment`,this.addCommentButton(),`.deleteButton`)}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton(`comment`)}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#n?.destroy()}addContainer(e){let t=this._editToolbar?.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#n||(at.initialize(e._l10n),this.#n=new at(this),this.#e&&=(this.#n.data=this.#e,null)),this.#n}get altTextData(){return this.#n?.data}set altTextData(e){this.#n&&(this.#n.data=e)}get guessedAltText(){return this.#n?.guessedText}async setGuessedAltText(e){await this.#n?.setGuessedText(e)}serializeAltText(e){return this.#n?.serialize(e)}hasAltText(){return!!this.#n&&!this.#n.isEmpty()}hasAltTextData(){return this.#n?.hasData()??!1}focusCommentButton(){this.#r?.focusButton()}addCommentButton(){return this.canAddComment?this.#r||=new ot(this):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager()){if(this.#i){this._uiManager.isEditingMode()&&this.#i.classList.remove(`hidden`);return}this.hasComment&&(this.#i=this.#r.renderForStandalone(),this.div.append(this.#i))}}removeStandaloneCommentButton(){this.#r.removeStandaloneCommentButton(),this.#i=null}hideStandaloneCommentButton(){this.#i?.classList.add(`hidden`)}get comment(){if(!this.#r)return null;let{data:{richText:e,text:t,date:n,deleted:r}}=this.#r;return{text:t,richText:e,date:n,deleted:r,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(e){this.#r||=new ot(this),typeof e==`object`&&e?this.#r.restoreData(e):this.#r.data=e,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:e,popupRef:t,richText:n}){if(!t||(this.#r||=new ot(this),this.#r.setInitialText(e,n),!this.annotationElementId))return;let r=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);r&&this.updateFromAnnotationLayer(r)}get hasEditedComment(){return this.#r?.hasBeenEdited()}get hasDeletedComment(){return this.#r?.isDeleted()}get hasComment(){return!!this.#r&&!this.#r.isEmpty()&&!this.#r.isDeleted()}async editComment(e){this.#r||=new ot(this),this.#r.edit(e)}toggleComment(e,t=void 0){this.hasComment&&this._uiManager.toggleComment(this,e,t)}setSelectedCommentButton(e){this.#r.setSelectedButton(e)}addComment(e){if(this.hasEditedComment){let[,,,t]=e.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,i=r+n+1,a=t-100,o=i+180;e.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[i,a,o,t]}}}updateFromAnnotationLayer({popup:{contents:e,deleted:t}}){this.#r.data=t?null:e}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){let e=this.div=document.createElement(`div`);e.setAttribute(`data-editor-rotation`,(360-this.rotation)%360),e.className=this.name,e.setAttribute(`id`,this.id),e.tabIndex=this.#a?-1:0,e.setAttribute(`role`,`application`),this.defaultL10nId&&e.setAttribute(`data-l10n-id`,this.defaultL10nId),this._isVisible||e.classList.add(`hidden`),this.setInForeground(),this.#z();let[t,n]=this.parentDimensions;this.parentRotation%180!=0&&(e.style.maxWidth=`${(100*n/t).toFixed(2)}%`,e.style.maxHeight=`${(100*t/n).toFixed(2)}%`);let[r,i]=this.getInitialTranslation();return this.translate(r,i),Qe(this,e,[`keydown`,`pointerdown`,`dblclick`]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#C||=new st({container:e,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#P.bind(this),onPinching:this.#F.bind(this),onPinchEnd:this.#I.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),e}#P(){this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#n?.toggle(!1),this.parent.togglePointerEvents(!1)}#F(t,n,r){let i=.7,a=r/n*i+1-i;if(a===1)return;let o=this.#O(this.rotation),s=(e,t)=>[o[0]*e+o[2]*t,o[1]*e+o[3]*t],[c,l]=this.parentDimensions,u=this.x,d=this.y,f=this.width,p=this.height,m=e.MIN_SIZE/c,h=e.MIN_SIZE/l;a=Math.max(Math.min(a,1/f,1/p),m/f,h/p);let g=e._round(f*a),_=e._round(p*a);if(g===f&&_===p)return;this.#h||=[u,d,f,p];let v=s(f/2,p/2),y=e._round(u+v[0]),b=e._round(d+v[1]),x=s(g/2,_/2);this.x=y-x[0],this.y=b-x[1],this.width=g,this.height=_,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#I(){this.#n?.toggle(!0),this.parent.togglePointerEvents(!0),this.#M()}pointerdown(e){let{isMac:t}=F.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(this.#m=!0,this._isDraggable){this.#R(e);return}this.#L(e)}#L(e){let{isMac:t}=F.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)}#R(e){let{isSelected:t}=this;this._uiManager.setUpDragSession();let n=!1,r=new AbortController,i=this._uiManager.combinedSignal(r),a={capture:!0,passive:!1,signal:i},o=e=>{r.abort(),this.#o=null,this.#m=!1,this._uiManager.endDragSession()||this.#L(e),n&&this._onStopDragging()};t&&(this.#b=e.clientX,this.#x=e.clientY,this.#o=e.pointerId,this.#s=e.pointerType,window.addEventListener(`pointermove`,e=>{n||(n=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());let{clientX:t,clientY:r,pointerId:i}=e;if(i!==this.#o){z(e);return}let[a,o]=this.screenToPageTranslation(t-this.#b,r-this.#x);this.#b=t,this.#x=r,this._uiManager.dragSelectedEditors(a,o)},a),window.addEventListener(`touchmove`,z,a),window.addEventListener(`pointerdown`,e=>{e.pointerType===this.#s&&(this.#C||e.isPrimary)&&o(e),z(e)},a));let s=e=>{if(!this.#o||this.#o===e.pointerId){o(e);return}z(e)};window.addEventListener(`pointerup`,s,{signal:i}),window.addEventListener(`blur`,s,{signal:i})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#y&&clearTimeout(this.#y),this.#y=setTimeout(()=>{this.#y=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(e,t,n){e.changeParent(this),this.x=t,this.y=n,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,n=this.rotation){let r=this.parentScale,[i,a]=this.pageDimensions,[o,s]=this.pageTranslation,c=e/r,l=t/r,u=this.x*i,d=this.y*a,f=this.width*i,p=this.height*a;switch(n){case 0:return[u+c+o,a-d-l-p+s,u+c+f+o,a-d-l+s];case 90:return[u+l+o,a-d+c+s,u+l+p+o,a-d+c+f+s];case 180:return[u-c-f+o,a-d+l+s,u-c+o,a-d+l+p+s];case 270:return[u-l-p+o,a-d-c-f+s,u-l+o,a-d-c+s];default:throw Error(`Invalid rotation`)}}getRectInCurrentCoords(e,t){let[n,r,i,a]=e,o=i-n,s=a-r;switch(this.rotation){case 0:return[n,t-a,o,s];case 90:return[n,t-r,s,o];case 180:return[i,t-r,o,s];case 270:return[i,t-a,s,o];default:throw Error(`Invalid rotation`)}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&e._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#r?.onUpdatedColor()}getData(){let{comment:{text:e,color:t,date:n,opacity:r,deleted:i,richText:a},uid:o,pageIndex:s,creationDate:c,modificationDate:l}=this;return{id:o,pageIndex:s,rect:this.getPDFRect(),richText:a,contentsObj:{str:e},creationDate:c,modificationDate:n||l,popupRef:!i,color:t,opacity:r}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#_=!0,!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),this.#_=!1,!0):!1}isInEditMode(){return this.#_}shouldGetKeyboardEvents(){return this.#v}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){let{top:e,left:t,bottom:n,right:r}=this.getClientDimensions(),{innerHeight:i,innerWidth:a}=window;return t0&&e0}#z(){if(this.#f||!this.div)return;this.#f=new AbortController;let e=this._uiManager.combinedSignal(this.#f);this.div.addEventListener(`focusin`,this.focusin.bind(this),{signal:e}),this.div.addEventListener(`focusout`,this.focusout.bind(this),{signal:e})}rebuild(){this.#z()}rotate(e){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||``}}serialize(e=!1,t=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||``}}static async deserialize(e,t,n){let r=new this.prototype.constructor({parent:t,id:n.getId(),uiManager:n,annotationElementId:e.annotationElementId,creationDate:e.creationDate,modificationDate:e.modificationDate});r.rotation=e.rotation,r.#e=e.accessibilityData,r._isCopy=e.isCopy||!1;let[i,a]=r.pageDimensions,[o,s,c,l]=r.getRectInCurrentCoords(e.rect,a);return r.x=o/i,r.y=s/a,r.width=c/i,r.height=l/a,r}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#f?.abort(),this.#f=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#y&&=(clearTimeout(this.#y),null),this.#W(),this.removeEditToolbar(),this.#S){for(let e of this.#S.values())clearTimeout(e);this.#S=null}this.parent=null,this.#C?.destroy(),this.#C=null,this.#d?.remove(),this.#d=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#k(),this.#c.classList.remove(`hidden`))}get toolbarPosition(){return null}get commentButtonPosition(){return this._uiManager.direction===`ltr`?[1,0]:[0,0]}get commentButtonPositionInPage(){let{commentButtonPosition:[t,n]}=this,[r,i,a,o]=this.getPDFRect();return[e._round(r+(a-r)*t),e._round(i+(o-i)*(1-n))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#r.commentPopupPositionInLayer}set commentPopupPosition(e){this.#r.commentPopupPositionInLayer=e}hasDefaultPopupPosition(){return this.#r.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#r.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(e){this.#r?.setCommentButtonStates(e)}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!==`Enter`)return;this._uiManager.setSelected(this),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let n=this.#c.children;if(!this.#t){this.#t=Array.from(n);let t=this.#B.bind(this),r=this.#V.bind(this),i=this._uiManager._signal;for(let n of this.#t){let a=n.getAttribute(`data-resizer-name`);n.setAttribute(`role`,`spinbutton`),n.addEventListener(`keydown`,t,{signal:i}),n.addEventListener(`blur`,r,{signal:i}),n.addEventListener(`focus`,this.#H.bind(this,a),{signal:i}),n.setAttribute(`data-l10n-id`,e._l10nResizer[a])}}let r=this.#t[0],i=0;for(let e of n){if(e===r)break;i++}let a=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(a!==i){if(ai)for(let e=0;e{this.div?.classList.contains(`selectedEditor`)&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#n?.toggleAltTextBadge(!1)}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#c?.classList.add(`hidden`),this.div?.classList.remove(`selectedEditor`),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#n?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(e,t){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(e){e.target.nodeName!==`BUTTON`&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#g}set isEditing(e){this.#g=e,this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:`added`}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){this.#S||=new Map;let{action:n}=t,r=this.#S.get(n);r&&clearTimeout(r),r=setTimeout(()=>{this._reportTelemetry(t),this.#S.delete(n),this.#S.size===0&&(this.#S=null)},e._telemetryTimeout),this.#S.set(n,r);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:t}})}show(e=this._isVisible){this.div.classList.toggle(`hidden`,!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),this.#a=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#a=!0}updateFakeAnnotationElement(e){if(!this.#d&&!this.deleted){this.#d=e.addFakeAnnotation(this);return}if(this.deleted){this.#d.remove(),this.#d=null;return}(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#d.updateEdited({rect:this.getPDFRect(),popup:this.comment})}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let t=e.container.querySelector(`.annotationContent`);if(!t)t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.container.prepend(t);else if(t.nodeName===`CANVAS`){let e=t;t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.before(t)}return t}resetAnnotationElement(e){let{firstElementChild:t}=e.container;t?.nodeName===`DIV`&&t.classList.contains(`annotationContent`)&&t.remove()}},ct=class extends U{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}},lt=3285377520,W=4294901760,ut=65535,dt=class{constructor(e){this.h1=e?e&4294967295:lt,this.h2=e?e&4294967295:lt}update(e){let t,n;if(typeof e==`string`){t=new Uint8Array(e.length*2),n=0;for(let r=0,i=e.length;r>>8,t[n++]=i&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),n=t.byteLength;else throw Error(`Invalid data format, must be a string or TypedArray.`);let r=n>>2,i=n-r*4,a=new Uint32Array(t.buffer,0,r),o=0,s=0,c=this.h1,l=this.h2,u=3432918353,d=461845907,f=11601,p=13715;for(let e=0;e>>17,o=o*d&W|o*p&ut,c^=o,c=c<<13|c>>>19,c=c*5+3864292196):(s=a[e],s=s*u&W|s*f&ut,s=s<<15|s>>>17,s=s*d&W|s*p&ut,l^=s,l=l<<13|l>>>19,l=l*5+3864292196);switch(o=0,i){case 3:o^=t[r*4+2]<<16;case 2:o^=t[r*4+1]<<8;case 1:o^=t[r*4],o=o*u&W|o*f&ut,o=o<<15|o>>>17,o=o*d&W|o*p&ut,r&1?c^=o:l^=o}this.h1=c,this.h2=l}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&W|e*36045&ut,t=t*4283543511&W|((t<<16|e>>>16)*2950163797&W)>>>16,e^=t>>>1,e=e*444984403&W|e*60499&ut,t=t*3301882366&W|((t<<16|e>>>16)*3120437893&W)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}},ft=Object.freeze({map:null,hash:``,transfer:void 0}),pt=class{#e=!1;#t=null;#n=null;#r=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(e,t){let n=this.#r.get(e);return n===void 0?t:Object.assign(t,n)}getRawValue(e){return this.#r.get(e)}remove(e){let t=this.#r.get(e);t!==void 0&&(t instanceof U&&this.#n.delete(t.annotationElementId),this.#r.delete(e),this.#r.size===0&&this.resetModified(),!this.#r.values().some(e=>e instanceof U)&&this.onAnnotationEditor?.(null))}setValue(e,t){let n=this.#r.get(e),r=!1;if(n!==void 0)for(let[e,i]of Object.entries(t))n[e]!==i&&(r=!0,n[e]=i);else r=!0,this.#r.set(e,t);r&&this.#i(),t instanceof U&&((this.#n||=new Map).set(t.annotationElementId,t),this.onAnnotationEditor?.(t.constructor._type))}has(e){return this.#r.has(e)}get size(){return this.#r.size}#i(){this.#e||(this.#e=!0,this.onSetModified?.())}resetModified(){this.#e&&(this.#e=!1,this.onResetModified?.())}get print(){return new mt(this)}get serializable(){if(this.#r.size===0)return ft;let e=new Map,t=new dt,n=[],r=Object.create(null),i=!1;for(let[n,a]of this.#r){let o=a instanceof U?a.serialize(!1,r):a;a.page&&(a.pageIndex=a.page._pageIndex,delete a.page),o&&(e.set(n,o),t.update(`${n}:${JSON.stringify(o)}`),i||=!!o.bitmap)}if(i)for(let t of e.values())t.bitmap&&n.push(t.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:n}:ft}get editorStats(){let e=null,t=new Map,n=0,r=0;for(let i of this.#r.values()){if(!(i instanceof U)){i.popup&&(i.popup.deleted?r+=1:n+=1);continue}i.isCommentDeleted?r+=1:i.hasEditedComment&&(n+=1);let a=i.telemetryFinalData;if(!a)continue;let{type:o}=a;t.getOrInsertComputed(o,()=>Object.getPrototypeOf(i).constructor),e||=Object.create(null);let s=e[o]||=new Map;for(let[e,t]of Object.entries(a)){if(e===`type`)continue;let n=s.getOrInsertComputed(e,me);n.set(t,(n.get(t)??0)+1)}}if((r>0||n>0)&&(e||=Object.create(null),e.comments={deleted:r,edited:n}),!e)return null;for(let[n,r]of t)e[n]=r.computeTelemetryFinalData(e[n]);return e}resetModifiedIds(){this.#t=null}updateEditor(e,t){let n=this.#n?.get(e);return n?(n.updateFromAnnotationLayer(t),!0):!1}getEditor(e){return this.#n?.get(e)||null}get modifiedIds(){if(this.#t)return this.#t;let e=[];if(this.#n)for(let t of this.#n.values())t.serialize()&&e.push(t.annotationElementId);let t=``;if(e.length){let n=new dt;n.update(e.join(`,`)),t=n.hexdigest()}return this.#t={ids:new Set(e),hash:t}}[Symbol.iterator](){return this.#r.entries()}},mt=class extends pt{#e=ft;constructor(e){super();let{serializable:t}=e;if(t===ft)return;let{map:n,hash:r,transfer:i}=t,a=structuredClone(n,i?{transfer:i}:null);this.#e={map:a,hash:r,transfer:[]}}get print(){E(`Should not call PrintAnnotationStorage.print`)}get serializable(){return this.#e}get modifiedIds(){return M(this,`modifiedIds`,{ids:new Set,hash:``})}},ht=`__forcedDependency`,{floor:gt,ceil:_t}=Math;function vt(e,t,n,r,i,a){e[t*4+0]=Math.min(e[t*4+0],n),e[t*4+1]=Math.min(e[t*4+1],r),e[t*4+2]=Math.max(e[t*4+2],i),e[t*4+3]=Math.max(e[t*4+3],a)}function yt(e,t,n,r,i){let a;e?(e<0&&(a=i[0],i[0]=i[2],i[2]=a),i[0]*=e,i[2]*=e,t<0&&(a=i[1],i[1]=i[3],i[3]=a),i[1]*=t,i[3]*=t):i.fill(0),i[0]+=n,i[1]+=r,i[2]+=n,i[3]+=r}var bt=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0],xt=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get length(){return this.#e.length}isEmpty(e){return this.#e[e]===bt}minX(e){return this.#t[e*4+0]/256}minY(e){return this.#t[e*4+1]/256}maxX(e){return(this.#t[e*4+2]+1)/256}maxY(e){return(this.#t[e*4+3]+1)/256}},St=(e,t)=>e?.getOrInsertComputed(t,()=>({dependencies:new Set,isRenderingOperation:!1})),Ct=class{#e=[[1,0,0,1,0,0]];#t=[-1/0,-1/0,1/0,1/0];#n=new Float64Array(n);_pendingBBoxIdx=-1;#r;#i;#a;#o;_savesStack=[];_markedContentStack=[];constructor(e,t){this.#r=e.width,this.#i=e.height,this.#s(t)}growOperationsCount(e){e>=this.#o.length&&this.#s(e,this.#o)}#s(e,t){let n=new ArrayBuffer(e*4);this.#a=new Uint8ClampedArray(n),this.#o=new Uint32Array(n),t&&t.length>0?(this.#o.set(t),this.#o.fill(bt,t.length)):this.#o.fill(bt)}get clipBox(){return this.#t}save(e){return this.#t={__proto__:this.#t},this._savesStack.push(e),this}restore(e,t){let n=Object.getPrototypeOf(this.#t);if(n===null)return this;this.#t=n;let r=this._savesStack.pop();return r!==void 0&&(t?.(r,e),this.#o[e]=this.#o[r]),this}recordOpenMarker(e){return this._savesStack.push(e),this}getOpenMarker(){return this._savesStack.length===0?null:this._savesStack.at(-1)}recordCloseMarker(e,t){let n=this._savesStack.pop();return n!==void 0&&(t?.(n,e),this.#o[e]=this.#o[n]),this}beginMarkedContent(e){return this._markedContentStack.push(e),this}endMarkedContent(e,t){let n=this._markedContentStack.pop();return n!==void 0&&(t?.(n,e),this.#o[e]=this.#o[n]),this}pushBaseTransform(e){return this.#e.push(I.multiplyByDOMMatrix(this.#e.at(-1),e.getTransform())),this}popBaseTransform(){return this.#e.length>1&&this.#e.pop(),this}resetBBox(e){return this._pendingBBoxIdx!==e&&(this._pendingBBoxIdx=e,this.#n.set(n,0)),this}recordClipBox(e,t,r,i,a,o){let s=I.multiplyByDOMMatrix(this.#e.at(-1),t.getTransform()),c=n.slice();I.axialAlignedBoundingBox([r,a,i,o],s,c);let l=I.intersect(this.#t,c);return l?(this.#t[0]=l[0],this.#t[1]=l[1],this.#t[2]=l[2],this.#t[3]=l[3]):(this.#t[0]=this.#t[1]=1/0,this.#t[2]=this.#t[3]=-1/0),this}recordBBox(e,t,r,i,a,o){let s=this.#t;if(s[0]===1/0)return this;let c=I.multiplyByDOMMatrix(this.#e.at(-1),t.getTransform());if(s[0]===-1/0)return I.axialAlignedBoundingBox([r,a,i,o],c,this.#n),this;let l=n.slice();return I.axialAlignedBoundingBox([r,a,i,o],c,l),this.#n[0]=L(l[0],s[0],this.#n[0]),this.#n[1]=L(l[1],s[1],this.#n[1]),this.#n[2]=L(l[2],this.#n[2],s[2]),this.#n[3]=L(l[3],this.#n[3],s[3]),this}recordFullPageBBox(e){return this.#n[0]=Math.max(0,this.#t[0]),this.#n[1]=Math.max(0,this.#t[1]),this.#n[2]=Math.min(this.#r,this.#t[2]),this.#n[3]=Math.min(this.#i,this.#t[3]),this}recordOperation(e,t=!1,n){if(this._pendingBBoxIdx!==e)return this;let r=gt(this.#n[0]*256/this.#r),i=gt(this.#n[1]*256/this.#i),a=_t(this.#n[2]*256/this.#r),o=_t(this.#n[3]*256/this.#i);if(vt(this.#a,e,r,i,a,o),n)for(let t of n)for(let n of t)n!==e&&vt(this.#a,n,r,i,a,o);return t||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(e){return this._pendingBBoxIdx===e&&(this._pendingBBoxIdx=-1,this.#t[0]=Math.max(this.#t[0],this.#n[0]),this.#t[1]=Math.max(this.#t[1],this.#n[1]),this.#t[2]=Math.min(this.#t[2],this.#n[2]),this.#t[3]=Math.min(this.#t[3],this.#n[3])),this}take(){return new xt(this.#o,this.#a)}takeDebugMetadata(){throw Error(`Unreachable`)}recordSimpleData(e,t){return this}recordIncrementalData(e,t){return this}resetIncrementalData(e,t){return this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this}recordFutureForcedDependency(e,t){return this}inheritSimpleDataAsFutureForcedDependencies(e){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(e,t,n,r=1,i=0,a=0,o){return this}getSimpleIndex(e){}recordDependencies(e,t){return this}recordNamedDependency(e,t){return this}recordShowTextOperation(e,t=!1){return this}},wt=class{#e={__proto__:null};#t={__proto__:null,transform:[],moveText:[],sameLineText:[],[ht]:[]};#n=new Map;#r=new Set;#i=new Map;#a;#o;#s;constructor(e,t=!1){this.#s=e,t&&(this.#a=new Map,this.#o=(e,t)=>{St(this.#a,t).dependencies.add(e)})}get clipBox(){return this.#s.clipBox}growOperationsCount(e){this.#s.growOperationsCount(e)}save(e){return this.#e={__proto__:this.#e},this.#t={__proto__:this.#t,transform:{__proto__:this.#t.transform},moveText:{__proto__:this.#t.moveText},sameLineText:{__proto__:this.#t.sameLineText},[ht]:{__proto__:this.#t[ht]}},this.#s.save(e),this}restore(e){this.#s.restore(e,this.#o);let t=Object.getPrototypeOf(this.#e);return t===null?this:(this.#e=t,this.#t=Object.getPrototypeOf(this.#t),this)}recordOpenMarker(e){return this.#s.recordOpenMarker(e,this.#o),this}getOpenMarker(){return this.#s.getOpenMarker()}recordCloseMarker(e){return this.#s.recordCloseMarker(e,this.#o),this}beginMarkedContent(e){return this.#s.beginMarkedContent(e),this}endMarkedContent(e){return this.#s.endMarkedContent(e,this.#o),this}pushBaseTransform(e){return this.#s.pushBaseTransform(e),this}popBaseTransform(){return this.#s.popBaseTransform(),this}recordSimpleData(e,t){return this.#e[e]=t,this}recordIncrementalData(e,t){return this.#t[e].push(t),this}resetIncrementalData(e,t){return this.#t[e].length=0,this}recordNamedData(e,t){return this.#n.set(e,t),this}recordSimpleDataFromNamed(e,t,n){this.#e[e]=this.#n.get(t)??n}recordFutureForcedDependency(e,t){return this.recordIncrementalData(ht,t),this}inheritSimpleDataAsFutureForcedDependencies(e){for(let t of e)t in this.#e&&this.recordFutureForcedDependency(t,this.#e[t]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(let e of this.#r)this.recordFutureForcedDependency(ht,e);return this}resetBBox(e){return this.#s.resetBBox(e),this}recordClipBox(e,t,n,r,i,a){return this.#s.recordClipBox(e,t,n,r,i,a),this}recordBBox(e,t,n,r,i,a){return this.#s.recordBBox(e,t,n,r,i,a),this}recordCharacterBBox(e,t,n,r=1,i=0,a=0,o){let s=n.bbox,c,l;if(s&&(c=s[2]!==s[0]&&s[3]!==s[1]&&this.#i.get(n),c!==!1&&(l=[0,0,0,0],I.axialAlignedBoundingBox(s,n.fontMatrix,l),(r!==1||i!==0||a!==0)&&yt(r,-r,i,a,l),c)))return this.recordBBox(e,t,l[0],l[2],l[1],l[3]);if(!o)return this.recordFullPageBBox(e);let u=o();return s&&l&&c===void 0&&(c=l[0]<=i-u.actualBoundingBoxLeft&&l[2]>=i+u.actualBoundingBoxRight&&l[1]<=a-u.actualBoundingBoxAscent&&l[3]>=a+u.actualBoundingBoxDescent,this.#i.set(n,c),c)?this.recordBBox(e,t,l[0],l[2],l[1],l[3]):this.recordBBox(e,t,i-u.actualBoundingBoxLeft,i+u.actualBoundingBoxRight,a-u.actualBoundingBoxAscent,a+u.actualBoundingBoxDescent)}recordFullPageBBox(e){return this.#s.recordFullPageBBox(e),this}getSimpleIndex(e){return this.#e[e]}recordDependencies(e,t){let n=this.#r,r=this.#e,i=this.#t;for(let e of t)e in this.#e?n.add(r[e]):e in i&&i[e].forEach(n.add,n);return this}recordNamedDependency(e,t){return this.#n.has(t)&&this.#r.add(this.#n.get(t)),this}recordOperation(e,t=!1){if(this.recordDependencies(e,[ht]),this.#a){let t=St(this.#a,e),{dependencies:n}=t;this.#r.forEach(n.add,n),this.#s._savesStack.forEach(n.add,n),this.#s._markedContentStack.forEach(n.add,n),n.delete(e),t.isRenderingOperation=!0}let n=!t&&e===this.#s._pendingBBoxIdx;return this.#s.recordOperation(e,t,[this.#r,this.#s._savesStack,this.#s._markedContentStack]),n&&this.#r.clear(),this}recordShowTextOperation(e,t=!1){let n=Array.from(this.#r);this.recordOperation(e,t),this.recordIncrementalData(`sameLineText`,e);for(let e of n)this.recordIncrementalData(`sameLineText`,e);return this}bboxToClipBoxDropOperation(e,t=!1){let n=!t&&e===this.#s._pendingBBoxIdx;return this.#s.bboxToClipBoxDropOperation(e),n&&this.#r.clear(),this}take(){return this.#i.clear(),this.#s.take()}takeDebugMetadata(){return this.#a}},Tt=class e{#e;#t;#n;#r=0;#i=0;constructor(t,n,r){if(t instanceof e&&t.#n===!!r)return t;this.#e=t,this.#t=n,this.#n=!!r}get clipBox(){return this.#e.clipBox}growOperationsCount(){throw Error(`Unreachable`)}save(e){return this.#i++,this.#e.save(this.#t),this}restore(e){return this.#i>0&&(this.#e.restore(this.#t),this.#i--),this}recordOpenMarker(e){return this.#r++,this}getOpenMarker(){return this.#r>0?this.#t:this.#e.getOpenMarker()}recordCloseMarker(e){return this.#r--,this}beginMarkedContent(e){return this}endMarkedContent(e){return this}pushBaseTransform(e){return this.#e.pushBaseTransform(e),this}popBaseTransform(){return this.#e.popBaseTransform(),this}recordSimpleData(e,t){return this.#e.recordSimpleData(e,this.#t),this}recordIncrementalData(e,t){return this.#e.recordIncrementalData(e,this.#t),this}resetIncrementalData(e,t){return this.#e.resetIncrementalData(e,this.#t),this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this.#e.recordSimpleDataFromNamed(e,t,this.#t),this}recordFutureForcedDependency(e,t){return this.#e.recordFutureForcedDependency(e,this.#t),this}inheritSimpleDataAsFutureForcedDependencies(e){return this.#e.inheritSimpleDataAsFutureForcedDependencies(e),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#e.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(e){return this.#n||this.#e.resetBBox(this.#t),this}recordClipBox(e,t,n,r,i,a){return this.#n||this.#e.recordClipBox(this.#t,t,n,r,i,a),this}recordBBox(e,t,n,r,i,a){return this.#n||this.#e.recordBBox(this.#t,t,n,r,i,a),this}recordCharacterBBox(e,t,n,r,i,a,o){return this.#n||this.#e.recordCharacterBBox(this.#t,t,n,r,i,a,o),this}recordFullPageBBox(e){return this.#n||this.#e.recordFullPageBBox(this.#t),this}getSimpleIndex(e){return this.#e.getSimpleIndex(e)}recordDependencies(e,t){return this.#e.recordDependencies(this.#t,t),this}recordNamedDependency(e,t){return this.#e.recordNamedDependency(this.#t,t),this}recordOperation(e){return this.#e.recordOperation(this.#t,!0),this}recordShowTextOperation(e){return this.#e.recordShowTextOperation(this.#t,!0),this}bboxToClipBoxDropOperation(e){return this.#n||this.#e.bboxToClipBoxDropOperation(this.#t,!0),this}take(){throw Error(`Unreachable`)}takeDebugMetadata(){throw Error(`Unreachable`)}},G={stroke:[`path`,`transform`,`filter`,`strokeColor`,`strokeAlpha`,`lineWidth`,`lineCap`,`lineJoin`,`miterLimit`,`dash`],fill:[`path`,`transform`,`filter`,`fillColor`,`fillAlpha`,`globalCompositeOperation`,`SMask`],imageXObject:[`transform`,`SMask`,`filter`,`fillAlpha`,`strokeAlpha`,`globalCompositeOperation`],rawFillPath:[`filter`,`fillColor`,`fillAlpha`],showText:[`transform`,`leading`,`charSpacing`,`wordSpacing`,`hScale`,`textRise`,`moveText`,`textMatrix`,`font`,`fontObj`,`filter`,`fillColor`,`textRenderingMode`,`SMask`,`fillAlpha`,`strokeAlpha`,`globalCompositeOperation`,`sameLineText`],transform:[`transform`],transformAndFill:[`transform`,`fillColor`]},Et=class e{#e;#t;#n=4;#r=0;#i=new e.#a(this.#n*6);static#a=F.isFloat16ArraySupported?Float16Array:Float32Array;constructor(e){this.#e=e.width,this.#t=e.height}record(t,r,i,a){if(this.#r===this.#n){this.#n*=2;let t=new e.#a(this.#n*6);t.set(this.#i),this.#i=t}let o=B(t),s;if(a[0]!==1/0){let e=n.slice();I.axialAlignedBoundingBox([0,-i,r,0],o,e);let t=I.intersect(a,e);if(!t)return;let[c,l,u,d]=t;if(c!==e[0]||l!==e[1]||u!==e[2]||d!==e[3]){let e=Math.atan2(o[1],o[0]),t=Math.abs(Math.sin(e)),n=Math.abs(Math.cos(e));if(t<1e-6||n<1e-6||Math.abs(t-n)<1e-6)s=[c,l,c,d,u,l];else{let e=u-c,r=d-l,i=t*t,a=n*n,o=n*t,f=a-i,p=(r*a-e*o)/f;s=[c+(r*o-e*i)/f,l,c,l+p,u,d-p]}}}s||(s=[0,-i,0,0,r,-i],I.applyTransform(s,o,0),I.applyTransform(s,o,2),I.applyTransform(s,o,4)),s[0]/=this.#e,s[1]/=this.#t,s[2]/=this.#e,s[3]/=this.#t,s[4]/=this.#e,s[5]/=this.#t,this.#i.set(s,this.#r*6),this.#r++}take(){return this.#i.subarray(0,this.#r*6)}},Dt=class{#e=new Set;#t=null;constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){let t=this.#n();t.insertRule(e,t.cssRules.length)}#n(){if(this.#t)return this.#t;let e=this._document.defaultView?.CSSStyleSheet||globalThis.CSSStyleSheet;if(!this.styleElement&&e){let{adoptedStyleSheets:t}=this._document;if(t){let n=new e;return t.push(n),this.#t=n}}return this.styleElement||(this.styleElement=this._document.createElement(`style`),this._document.documentElement.getElementsByTagName(`head`)[0].append(this.styleElement)),this.#t=this.styleElement.sheet}clear(){for(let e of this.nativeFontFaces)this._document.fonts.delete(e);if(this.nativeFontFaces.clear(),this.#e.clear(),this.#t){let{adoptedStyleSheets:e}=this._document;e?.includes(this.#t)&&(this._document.adoptedStyleSheets=e.filter(e=>e!==this.#t)),this.#t=null}this.styleElement&&=(this.styleElement.remove(),null)}async loadSystemFont({systemFontInfo:e,disableFontFace:t,_inspectFont:n}){if(!(!e||this.#e.has(e.loadedName))){if(D(!t,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:t,src:r,style:i}=e,a=new FontFace(t,r,i);this.addNativeFontFace(a);try{await a.load(),this.#e.add(t),n?.(e)}catch{T(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}E(`Not implemented: loadSystemFont without the Font Loading API.`)}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){let t=e.createNativeFontFace();if(t){this.addNativeFontFace(t);try{await t.loaded}catch(n){throw T(`Failed to load font '${t.family}': '${n}'.`),e.disableFontFace=!0,n}}return}let t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(t=>{let n=this._queueLoadingCallback(t);this._prepareFontLoadEvent(e,n)})}}get isFontLoadingAPISupported(){let e=!!this._document?.fonts;return M(this,`isFontLoadingAPISupported`,e)}get isSyncFontLoadingSupported(){return M(this,`isSyncFontLoadingSupported`,t||F.platform.isFirefox)}_queueLoadingCallback(e){function t(){for(D(!r.done,`completeRequest() cannot be called twice.`),r.done=!0;n.length>0&&n[0].done;){let e=n.shift();setTimeout(e.callback,0)}}let{loadingRequests:n}=this,r={done:!1,complete:t,callback:e};return n.push(r),r}get _loadTestFont(){let e=atob(`T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==`);return M(this,`_loadTestFont`,e)}_prepareFontLoadEvent(e,t){function n(e,t){return e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3)&255}function r(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,e&255)}function i(e,t,n,r){let i=e.substring(0,t),a=e.substring(t+n);return i+r+a}let a,o,s=this._document.createElement(`canvas`);s.width=1,s.height=1;let c=s.getContext(`2d`),l=0;function u(e,t){if(++l>30){T(`Load test font never loaded.`),t();return}if(c.font=`30px `+e,c.fillText(`.`,0,20),c.getImageData(0,0,1,1).data[3]>0){t();return}setTimeout(u.bind(null,e,t))}let d=`lt${Date.now()}${this.loadTestFontId++}`,f=this._loadTestFont;f=i(f,976,d.length,d);let p=1482184792,m=n(f,16);for(a=0,o=d.length-3;a{g.remove(),t.complete()})}},Ot=class{compiledGlyphs=Object.create(null);#e;constructor(e,t=null,n,r){this.#e=e,this._inspectFont=t,n&&(this.charProcOperatorList=n),r&&Object.assign(this,r)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{let t={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(t.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,t)}return this._inspectFont?.(this),e}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let e=`url(data:${this.mimetype};base64,${this.data.toBase64()});`,t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let n=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(n+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${n}src:${e}}`}return this._inspectFont?.(this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];let n=this.loadedName+`_path_`+t,r;try{r=e.get(n)}catch(e){T(`getPathGenerator - ignoring character: "${e}".`)}let i=Je(r?.path);return this.fontExtraProperties||e.delete(n),this.compiledGlyphs[t]=i}get black(){return this.#e.black}get bold(){return this.#e.bold}get disableFontFace(){return this.#e.disableFontFace}set disableFontFace(e){M(this,`disableFontFace`,!!e)}get fontExtraProperties(){return this.#e.fontExtraProperties}get isInvalidPDFjsFont(){return this.#e.isInvalidPDFjsFont}get isType3Font(){return this.#e.isType3Font}get italic(){return this.#e.italic}get missingFile(){return this.#e.missingFile}get remeasure(){return this.#e.remeasure}get vertical(){return this.#e.vertical}get ascent(){return this.#e.ascent}get defaultWidth(){return this.#e.defaultWidth}get descent(){return this.#e.descent}get bbox(){return this.#e.bbox}get fontMatrix(){return this.#e.fontMatrix}get fallbackName(){return this.#e.fallbackName}get loadedName(){return this.#e.loadedName}get mimetype(){return this.#e.mimetype}get name(){return this.#e.name}get data(){return this.#e.data}clearData(){this.#e.clearData()}get cssFontInfo(){return this.#e.cssFontInfo}get systemFontInfo(){return this.#e.systemFontInfo}get defaultVMetrics(){return this.#e.defaultVMetrics}},kt=class{static strings=[`fontFamily`,`fontWeight`,`italicAngle`]},At=class{static strings=[`css`,`loadedName`,`baseFontName`,`src`]},K=class{static bools=[`black`,`bold`,`disableFontFace`,`fontExtraProperties`,`isInvalidPDFjsFont`,`isType3Font`,`italic`,`missingFile`,`remeasure`,`vertical`];static numbers=[`ascent`,`defaultWidth`,`descent`];static strings=[`fallbackName`,`loadedName`,`mimetype`,`name`];static OFFSET_NUMBERS=Math.ceil(this.bools.length*2/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+this.numbers.length*8;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6},jt=class{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16},Mt=class{#e;#t=new TextDecoder;#n;constructor(e){this.#e=e,this.#n=new DataView(e)}#r(e){D(e>n&3;return r===0?void 0:r===2}get black(){return this.#r(0)}get bold(){return this.#r(1)}get disableFontFace(){return this.#r(2)}get fontExtraProperties(){return this.#r(3)}get isInvalidPDFjsFont(){return this.#r(4)}get isType3Font(){return this.#r(5)}get italic(){return this.#r(6)}get missingFile(){return this.#r(7)}get remeasure(){return this.#r(8)}get vertical(){return this.#r(9)}#i(e){return D(e0){t=n.slice();for(let e=0,n=l.length;etypeof e==`object`&&Number.isInteger(e?.num)&&e.num>=0&&Number.isInteger(e?.gen)&&e.gen>=0,Vt=fe.bind(null,Bt,e=>typeof e==`object`&&typeof e?.name==`string`),Ht=class{#e=new Map;#t=Promise.resolve();postMessage(e,t){let n={data:structuredClone(e,t?{transfer:t}:null)};this.#t.then(()=>{for(let[e]of this.#e)e.call(this,n)})}addEventListener(e,t,n=null){let r=null;if(n?.signal instanceof AbortSignal){let{signal:i}=n;if(i.aborted){T("LoopbackPort - cannot use an `aborted` signal.");return}let a=()=>this.removeEventListener(e,t);r=()=>i.removeEventListener(`abort`,a),i.addEventListener(`abort`,a)}this.#e.set(t,r)}removeEventListener(e,t){this.#e.get(t)?.(),this.#e.delete(t)}terminate(){for(let[,e]of this.#e)e?.();this.#e.clear()}},Ut={DATA:1,ERROR:2},q={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Wt(){}function J(e){if(e instanceof P||e instanceof ne||e instanceof ee||e instanceof re||e instanceof te)return e;switch(e instanceof Error||typeof e==`object`&&e||E(`wrapReason: Expected "reason" to be a (possibly cloned) Error.`),e.name){case`AbortException`:return new P(e.message);case`InvalidPDFException`:return new ne(e.message);case`PasswordException`:return new ee(e.message,e.code);case`ResponseException`:return new re(e.message,e.status,e.missing);case`UnknownErrorException`:return new te(e.message,e.details)}return new te(e.message,e.toString())}var Gt=class{#e=new AbortController;constructor(e,t,n){this.sourceName=e,this.targetName=t,this.comObj=n,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),n.addEventListener(`message`,this.#t.bind(this),{signal:this.#e.signal})}#t({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#r(e);return}if(e.callback){let t=e.callbackId,n=this.callbackCapabilities[t];if(!n)throw Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],e.callback===Ut.DATA)n.resolve(e.data);else if(e.callback===Ut.ERROR)n.reject(J(e.reason));else throw Error(`Unexpected callback case`);return}let t=this.actionHandler[e.action];if(!t)throw Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){let n=this.sourceName,r=e.sourceName,i=this.comObj;Promise.try(t,e.data).then(function(t){i.postMessage({sourceName:n,targetName:r,callback:Ut.DATA,callbackId:e.callbackId,data:t})},function(t){i.postMessage({sourceName:n,targetName:r,callback:Ut.ERROR,callbackId:e.callbackId,reason:J(t)})});return}if(e.streamId){this.#n(e);return}t(e.data)}on(e,t){let n=this.actionHandler;if(n[e])throw Error(`There is already an actionName called "${e}"`);n[e]=t}send(e,t,n){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},n)}sendWithPromise(e,t,n){let r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},n)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,n,r){let i=this.streamId++,a=this.sourceName,o=this.targetName,s=this.comObj;return new ReadableStream({start:n=>{let c=Promise.withResolvers();return this.streamControllers[i]={controller:n,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},s.postMessage({sourceName:a,targetName:o,action:e,streamId:i,data:t,desiredSize:n.desiredSize},r),c.promise},pull:e=>{let t=Promise.withResolvers();return this.streamControllers[i].pullCall=t,s.postMessage({sourceName:a,targetName:o,stream:q.PULL,streamId:i,desiredSize:e.desiredSize}),t.promise},cancel:e=>{D(e instanceof Error,`cancel must have a valid reason`);let t=Promise.withResolvers();return this.streamControllers[i].cancelCall=t,this.streamControllers[i].isClosed=!0,s.postMessage({sourceName:a,targetName:o,stream:q.CANCEL,streamId:i,reason:J(e)}),t.promise}},n)}#n(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this,o=this.actionHandler[e.action],s={enqueue(e,a=1,o){if(this.isCancelled)return;let s=this.desiredSize;this.desiredSize-=a,s>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),i.postMessage({sourceName:n,targetName:r,stream:q.ENQUEUE,streamId:t,chunk:e},o)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:q.CLOSE,streamId:t}),delete a.streamSinks[t])},error(e){D(e instanceof Error,`error must have a valid reason`),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:q.ERROR,streamId:t,reason:J(e)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};s.sinkCapability.resolve(),s.ready=s.sinkCapability.promise,this.streamSinks[t]=s,Promise.try(o,e.data,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.START_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.START_COMPLETE,streamId:t,reason:J(e)})})}#r(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this.streamControllers[t],o=this.streamSinks[t];switch(e.stream){case q.START_COMPLETE:e.success?a.startCall.resolve():a.startCall.reject(J(e.reason));break;case q.PULL_COMPLETE:e.success?a.pullCall.resolve():a.pullCall.reject(J(e.reason));break;case q.PULL:if(!o){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,success:!0});break}o.desiredSize<=0&&e.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=e.desiredSize,Promise.try(o.onPull||Wt).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,reason:J(e)})});break;case q.ENQUEUE:if(D(a,`enqueue should have stream controller`),a.isClosed)break;a.controller.enqueue(e.chunk);break;case q.CLOSE:if(D(a,`close should have stream controller`),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#i(a,t);break;case q.ERROR:D(a,`error should have stream controller`),a.controller.error(J(e.reason)),this.#i(a,t);break;case q.CANCEL_COMPLETE:e.success?a.cancelCall.resolve():a.cancelCall.reject(J(e.reason)),this.#i(a,t);break;case q.CANCEL:if(!o)break;let s=J(e.reason);Promise.try(o.onCancel||Wt,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.CANCEL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.CANCEL_COMPLETE,streamId:t,reason:J(e)})}),o.sinkCapability.reject(s),o.isCancelled=!0,delete this.streamSinks[t];break;default:throw Error(`Unexpected stream case`)}}async#i(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]),delete this.streamControllers[t]}destroy(){this.#e?.abort(),this.#e=null}},Kt=class{#e=Object.freeze({cMapUrl:`CMap`,standardFontDataUrl:`font`,wasmUrl:`wasm`});constructor({cMapUrl:e=null,standardFontDataUrl:t=null,wasmUrl:n=null}){this.cMapUrl=e,this.standardFontDataUrl=t,this.wasmUrl=n}async fetch({kind:e,filename:t}){switch(e){case`cMapUrl`:case`standardFontDataUrl`:case`wasmUrl`:break;default:E(`Not implemented: ${e}`)}let n=this[e];if(!n)throw Error(`Ensure that the \`${e}\` API parameter is provided.`);let r=`${n}${t}`;return this._fetch(r,e).catch(t=>{throw Error(`Unable to load ${this.#e[e]} data at: ${r}`)})}async _fetch(e,t){E("Abstract method `_fetch` called.")}},qt=class extends Kt{async _fetch(e,t){let n=await Ce(e,t===`cMapUrl`&&!e.endsWith(`.bcmap`)?`text`:`bytes`);return n instanceof Uint8Array?n:oe(n)}},Jt=class{#e=!1;constructor({enableHWA:e=!1}){this.#e=e}create(e,t){if(e<=0||t<=0)throw Error(`Invalid canvas size`);let n=this._createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`,{willReadFrequently:!this.#e})}}reset({canvas:e},t,n){if(!e)throw Error(`Canvas is not specified`);if(t<=0||n<=0)throw Error(`Invalid canvas size`);e.width=t,e.height=n}destroy(e){let{canvas:t}=e;if(!t)throw Error(`Canvas is not specified`);t.width=t.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){E("Abstract method `_createCanvas` called.")}},Yt=class extends Jt{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){let n=this._document.createElement(`canvas`);return n.width=e,n.height=t,n}},Xt=class{addFilter(e){return`none`}addHCMFilter(e,t){return`none`}addAlphaFilter(e){return`none`}addLuminosityFilter(e){return`none`}addKnockoutFilter(e=0){return`none`}addHighlightHCMFilter(e,t,n,r,i){return`none`}addSelectionHCMFilter(e,t){return`none`}addSelectionFilter(){return`none`}createSelectionStyle(e=null){return null}destroy(e=!1){}},Zt=class extends Xt{#e;#t;#n;#r;#i;#a;#o=0;constructor({docId:e,ownerDocument:t=globalThis.document}){super(),this.#r=e,this.#i=t}get#s(){return this.#t||=new Map}get#c(){return this.#a||=new Map}get#l(){if(!this.#n){let e=this.#i.createElement(`div`),{style:t}=e;t.colorScheme=`only light`,t.visibility=`hidden`,t.contain=`strict`,t.width=t.height=0,t.position=`absolute`,t.top=t.left=0,t.zIndex=-1;let n=this.#i.createElementNS(a,`svg`);n.setAttribute(`width`,0),n.setAttribute(`height`,0),this.#n=this.#i.createElementNS(a,`defs`),e.append(n),n.append(this.#n),this.#i.body.append(e)}return this.#n}#u(e){if(e.length===1){let t=e[0],n=Array(256);for(let e=0;e<256;e++)n[e]=t[e]/255;let r=n.join(`,`);return[r,r,r]}let[t,n,r]=e,i=Array(256),a=Array(256),o=Array(256);for(let e=0;e<256;e++)i[e]=t[e]/255,a[e]=n[e]/255,o[e]=r[e]/255;return[i.join(`,`),a.join(`,`),o.join(`,`)]}#d(e){if(this.#e===void 0){this.#e=``;let e=this.#i.URL;e!==this.#i.baseURI&&(Te(e)?T(`#createUrl: ignore "data:"-URL for performance reasons.`):this.#e=A(e,``))}return`url(${this.#e}#${e})`}addFilter(e){if(!e)return`none`;let t=this.#s.get(e);if(t)return t;let[n,r,i]=this.#u(e),a=e.length===1?n:`${n}${r}${i}`;if(t=this.#s.get(a),t)return this.#s.set(e,t),t;let o=`g_${this.#r}_transfer_map_${this.#o++}`,s=this.#d(o);this.#s.set(e,s),this.#s.set(a,s);let c=this.#m(o);return this.#g(n,r,i,c),s}addHCMFilter(e,t){let n=`${e}-${t}`,r=`base`,i=this.#c.get(r);if(i?.key===n||(i?(i.filter?.remove(),i.key=n,i.url=`none`,i.filter=null):(i={key:n,url:`none`,filter:null},this.#c.set(r,i)),!e||!t))return i.url;let a=this.#v(e);e=I.makeHexColor(...a);let o=this.#v(t);if(t=I.makeHexColor(...o),this.#b(),e===`#000000`&&t===`#ffffff`||e===t)return i.url;let s=Array(256);for(let e=0;e<=255;e++){let t=e/255;s[e]=t<=.03928?t/12.92:((t+.055)/1.055)**2.4}let c=s.join(`,`),l=`g_${this.#r}_hcm_filter`,u=i.filter=this.#m(l);this.#g(c,c,c,u),this.#p(u);let d=(e,t)=>{let n=a[e]/255,r=o[e]/255,i=Array(t+1);for(let e=0;e<=t;e++)i[e]=n+e/t*(r-n);return i.join(`,`)};return this.#g(d(0,5),d(1,5),d(2,5),u),i.url=this.#d(l),i.url}addSelectionHCMFilter(e,t){return this.addHighlightHCMFilter(`selection`,e,t,`HighlightText`,`Highlight`)}addSelectionFilter(){return this.addHighlightHCMFilter(`selection_default`,`black`,`white`,`HighlightText`,`Highlight`)}createSelectionStyle(e=null){let t=e?this.addSelectionHCMFilter(e.foreground,e.background):this.addSelectionFilter();return t===`none`||!F.platform.isFirefox?null:{"backdrop-filter":t,"background-color":`transparent`}}addAlphaFilter(e){let t=this.#s.get(e);if(t)return t;let[n]=this.#u([e]),r=`alpha_${n}`;if(t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_alpha_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#_(n,o),a}addLuminosityFilter(e){let t=this.#s.get(e||`luminosity`);if(t)return t;let n,r;if(e?([n]=this.#u([e]),r=`luminosity_${n}`):r=`luminosity`,t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_luminosity_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#f(o),e&&this.#_(n,o),a}addKnockoutFilter(e=0){let t=e>0?Math.min(1/e,1e6):1e6,n=`knockout_${t}`,r=this.#s.get(n);if(r)return r;let i=`g_${this.#r}_knockout_filter_${this.#o++}`,o=this.#d(i);this.#s.set(n,o);let s=this.#m(i),c=this.#i.createElementNS(a,`feComponentTransfer`);s.append(c);let l=this.#i.createElementNS(a,`feFuncA`);return l.setAttribute(`type`,`linear`),l.setAttribute(`slope`,`${t}`),l.setAttribute(`intercept`,`0`),c.append(l),o}addHighlightHCMFilter(e,t,n,r,i){let a=`${t}-${n}-${r}-${i}`,o=this.#c.get(e);if(o?.key===a||(o?(o.filter?.remove(),o.key=a,o.url=`none`,o.filter=null):(o={key:a,url:`none`,filter:null},this.#c.set(e,o)),!t||!n))return o.url;let[s,c]=[t,n].map(this.#v.bind(this)),l=Math.round(.2126*s[0]+.7152*s[1]+.0722*s[2]),u=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),[d,f]=[r,i].map(this.#x.bind(this));u{let r=Array(256),i=(u-l)/n,a=e/255,o=(t-e)/(255*n),s=0;for(let e=0;e<=n;e++){let t=Math.round(l+e*i),n=a+e*o;for(let e=s;e<=t;e++)r[e]=n;s=t+1}for(let e=s;e<256;e++)r[e]=r[s-1];return r.join(`,`)},m=`g_${this.#r}_hcm_${e}_filter`,h=o.filter=this.#m(m);return this.#p(h),this.#g(p(d[0],f[0],5),p(d[1],f[1],5),p(d[2],f[2],5),h),o.url=this.#d(m),o.url}destroy(e=!1){e&&this.#a?.size||(this.#n?.parentNode.parentNode.remove(),this.#n=null,this.#t?.clear(),this.#t=null,this.#a?.clear(),this.#a=null,this.#o=0)}#f(e){let t=this.#i.createElementNS(a,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.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`),e.append(t)}#p(e){let t=this.#i.createElementNS(a,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.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`),e.append(t)}#m(e){let t=this.#i.createElementNS(a,`filter`);return t.setAttribute(`color-interpolation-filters`,`sRGB`),t.setAttribute(`id`,e),this.#l.append(t),t}#h(e,t,n){let r=this.#i.createElementNS(a,t);r.setAttribute(`type`,`discrete`),r.setAttribute(`tableValues`,n),e.append(r)}#g(e,t,n,r){let i=this.#i.createElementNS(a,`feComponentTransfer`);r.append(i),this.#h(i,`feFuncR`,e),this.#h(i,`feFuncG`,t),this.#h(i,`feFuncB`,n)}#_(e,t){let n=this.#i.createElementNS(a,`feComponentTransfer`);t.append(n),this.#h(n,`feFuncA`,e)}#v(e){return this.#l.style.color=`CanvasText`,this.#l.style.backgroundColor=e,Ne(getComputedStyle(this.#l).getPropertyValue(`background-color`))}#y(e){return this.#l.style.color=`CanvasText`,this.#l.style.backgroundColor=e,Me(getComputedStyle(this.#l).getPropertyValue(`background-color`))}#b(){this.#l.style.color=``,this.#l.style.backgroundColor=``}#x(e){let[t,n,r,i]=this.#y(e);if(i===1)return[t,n,r];let[a,o,s]=this.#v(`Canvas`);return[Qt(t,a,i),Qt(n,o,i),Qt(r,s,i)]}};function Qt(e,t,n){return Math.round(n*e+(1-n)*t)}t&&T("Please use the `legacy` build in Node.js environments.");async function $t(e){let t=await process.getBuiltinModule(`fs/promises`).readFile(e);return new Uint8Array(t)}var en=class extends Xt{},tn=class extends Jt{_createCanvas(e,t){return process.getBuiltinModule(`module`).createRequire(import.meta.url)(`@napi-rs/canvas`).createCanvas(e,t)}},nn=class extends Kt{async _fetch(e,t){return $t(e)}};function rn({src:e,srcPos:t=0,dest:n,width:r,height:i,nonBlackColor:a=4294967295,inverseDecode:o=!1}){let s=F.isLittleEndian?4278190080:255,[c,l]=o?[a,s]:[s,a],u=r>>3,d=r&7,f=c^l,p=e.length;n=new Uint32Array(n.buffer);let m=0;for(let r=0;r>7&1)&f,n[m+1]=c^-(r>>6&1)&f,n[m+2]=c^-(r>>5&1)&f,n[m+3]=c^-(r>>4&1)&f,n[m+4]=c^-(r>>3&1)&f,n[m+5]=c^-(r>>2&1)&f,n[m+6]=c^-(r>>1&1)&f,n[m+7]=c^-(r&1)&f}if(d===0)continue;let r=t>7-e&1)&f}return{srcPos:t,destPos:m}}function an({src:e,srcPos:t=0,dest:n,destPos:r=0,width:i,height:a}){let o=0,s=i*a*3,c=s>>2,l=new Uint32Array(e.buffer,t,c),u=F.isLittleEndian?4278190080:255;if(F.isLittleEndian){for(;o>>24|t<<8|u,n[r+2]=t>>>16|i<<16|u,n[r+3]=i>>>8|u}for(let i=o*4,a=t+s;i>>8|u,n[r+2]=t<<16|i>>>16|u,n[r+3]=i<<8|u}for(let i=o*4,a=t+s;i u : Uniforms; - -struct VertexInput { - @location(0) position : vec2, - @location(1) color : vec4, -}; - -struct VertexOutput { - @builtin(position) position : vec4, - @location(0) color : vec3, -}; - -@vertex -fn vs_main(in : VertexInput) -> VertexOutput { - var out : VertexOutput; - let cx = (in.position.x + u.offsetX) * u.scaleX; - let cy = (in.position.y + u.offsetY) * u.scaleY; - out.position = vec4( - ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0, - 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0, - 0.0, - 1.0 - ); - out.color = in.color.rgb; - return out; -} - -@fragment -fn fs_main(in : VertexOutput) -> @location(0) vec4 { - return vec4(in.color, 1.0); -} -`,sn=new class{#e=null;#t=null;#n=null;#r=null;async#i(){if(!globalThis.navigator?.gpu)return!1;try{let e=await navigator.gpu.requestAdapter();return e?(this.#r=navigator.gpu.getPreferredCanvasFormat(),this.#t=await e.requestDevice(),!0):!1}catch{return!1}}init(){return this.#e||=this.#i()}get isReady(){return this.#t!==null}loadMeshShader(){if(!this.#t||this.#n)return;let e=this.#t.createShaderModule({code:on});this.#n=this.#t.createRenderPipeline({layout:`auto`,vertex:{module:e,entryPoint:`vs_main`,buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:`float32x2`}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:`unorm8x4`}]}]},fragment:{module:e,entryPoint:`fs_main`,targets:[{format:this.#r}]},primitive:{topology:`triangle-list`}})}draw(e,t,n,r,i,a,o,s){this.loadMeshShader();let c=this.#t,{offsetX:l,offsetY:u,scaleX:d,scaleY:f}=r,p=c.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&c.queue.writeBuffer(p,0,e);let m=c.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&c.queue.writeBuffer(m,0,t);let h=c.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});c.queue.writeBuffer(h,0,new Float32Array([l,u,d,f,a,o,s,0]));let g=c.createBindGroup({layout:this.#n.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:h}}]}),_=new OffscreenCanvas(a,o),v=_.getContext(`webgpu`);v.configure({device:c,format:this.#r,alphaMode:i?`opaque`:`premultiplied`});let y=i?{r:i[0]/255,g:i[1]/255,b:i[2]/255,a:1}:{r:0,g:0,b:0,a:0},b=c.createCommandEncoder(),x=b.beginRenderPass({colorAttachments:[{view:v.getCurrentTexture().createView(),clearValue:y,loadOp:`clear`,storeOp:`store`}]});return n>0&&(x.setPipeline(this.#n),x.setBindGroup(0,g),x.setVertexBuffer(0,p),x.setVertexBuffer(1,m),x.draw(n)),x.end(),c.queue.submit([b.finish()]),p.destroy(),m.destroy(),h.destroy(),_.transferToImageBitmap()}};function cn(){return sn.init()}function ln(){return sn.isReady}function un(){sn.loadMeshShader()}function dn(e,t,n,r,i,a,o,s){return sn.draw(e,t,n,r,i,a,o,s)}var Y={FILL:`Fill`,STROKE:`Stroke`,SHADING:`Shading`};function fn(e,t){if(!t)return;let n=t[2]-t[0],r=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],n,r),e.clip(i)}var pn=class{matrix=null;isModifyingCurrentTransform(){return!1}getPattern(){E("Abstract method `getPattern` called.")}},mn=class extends pn{constructor(e){super(),this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7]}isOriginBased(){return this._p0[0]===0&&this._p0[1]===0&&(!this.isRadial()||this._p1[0]===0&&this._p1[1]===0)}isRadial(){return this._type===`radial`}areConic(){if(!this.isRadial())return!1;let e=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return e+this._r1>this._r0&&e+this._r0>this._r1}_createGradient(e,t=null){let n,r=this._p0,i=this._p1;if(t&&(r=r.slice(),i=i.slice(),I.applyTransform(r,t),I.applyTransform(i,t)),this._type===`axial`)n=e.createLinearGradient(r[0],r[1],i[0],i[1]);else if(this._type===`radial`){let a=this._r0,o=this._r1;if(t){let e=new Float32Array(2);I.singularValueDecompose2dScale(t,e),a*=e[0],o*=e[0]}n=e.createRadialGradient(r[0],r[1],a,i[0],i[1],o)}for(let e of this._colorStops)n.addColorStop(e[0],e[1]);return n}_createReversedGradient(e,t=null){let n=this._p1,r=this._p0;t&&(n=n.slice(),r=r.slice(),I.applyTransform(n,t),I.applyTransform(r,t));let i=this._r1,a=this._r0;if(t){let e=new Float32Array(2);I.singularValueDecompose2dScale(t,e),i*=e[0],a*=e[0]}let o=e.createRadialGradient(n[0],n[1],i,r[0],r[1],a),s=this._colorStops.map(([e,t])=>[1-e,t]).reverse();for(let[e,t]of s)o.addColorStop(e,t);return o}getPattern(e,t,n,r){let i;if(r===Y.STROKE||r===Y.FILL){if(this.isOriginBased()){let r=I.transform(n,t.baseTransform);this.matrix&&(r=I.transform(r,this.matrix));let i=.001,a=Math.hypot(r[0],r[1]),o=Math.hypot(r[2],r[3]),s=(r[0]*r[2]+r[1]*r[3])/(a*o);if(Math.abs(s)c[r*2+1]&&(f=n,n=r,r=f,f=a,a=o,o=f),c[r*2+1]>c[i*2+1]&&(f=r,r=i,i=f,f=o,o=s,s=f),c[n*2+1]>c[r*2+1]&&(f=n,n=r,r=f,f=a,a=o,o=f);let p=(c[n*2]+t.offsetX)*t.scaleX,m=(c[n*2+1]+t.offsetY)*t.scaleY,h=(c[r*2]+t.offsetX)*t.scaleX,g=(c[r*2+1]+t.offsetY)*t.scaleY,_=(c[i*2]+t.offsetX)*t.scaleX,v=(c[i*2+1]+t.offsetY)*t.scaleY;if(m>=v)return;let y=l[a*4],b=l[a*4+1],x=l[a*4+2],S=l[o*4],C=l[o*4+1],w=l[o*4+2],T=l[s*4],E=l[s*4+1],D=l[s*4+2],O=Math.round(m),k=Math.round(v),A,j,M,N,ee,te,ne,re;for(let e=O;e<=k;e++){if(ev?1:g===v?0:(g-e)/(g-v),A=h-(h-_)*t,j=S-(S-T)*t,M=C-(C-E)*t,N=w-(w-D)*t}let t;t=ev?1:(m-e)/(m-v),ee=p-(p-_)*t,te=y-(y-T)*t,ne=b-(b-E)*t,re=x-(x-D)*t;let n=Math.round(Math.min(A,ee)),r=Math.round(Math.max(A,ee)),i=d*e+n*4;for(let e=n;e<=r;e++)t=(A-e)/(A-ee),t<0?t=0:t>1&&(t=1),u[i++]=j-(j-te)*t|0,u[i++]=M-(M-ne)*t|0,u[i++]=N-(N-re)*t|0,u[i++]=255}}var gn=class extends pn{constructor(e){super(),this._posData=e[2],this._colData=e[3],this._vertexCount=e[4],this._bounds=e[5],this._bbox=e[6],this._background=e[7],un()}_createMeshCanvas(e,t,n){let r=1.1,i=3e3,a=Math.floor(this._bounds[0]),o=Math.floor(this._bounds[1]),s=Math.ceil(this._bounds[2])-a,c=Math.ceil(this._bounds[3])-o,l=Math.min(Math.ceil(Math.abs(s*e[0]*r)),i)||1,u=Math.min(Math.ceil(Math.abs(c*e[1]*r)),i)||1,d=s?s/l:1,f=c?c/u:1,p={coords:this._posData,colors:this._colData,offsetX:-a,offsetY:-o,scaleX:1/d,scaleY:1/f},m=l+4,h=u+4,g=n.create(m,h);if(ln()&&this._vertexCount>48)g.context.drawImage(dn(this._posData,this._colData,this._vertexCount,p,t,m,h,2),0,0);else{let e=g.context.createImageData(l,u);if(t){let n=e.data;for(let e=0,r=n.length;ec+1e-6||t>l+1e-6)return null;let u=Math.floor((n-o)/c)+1,d=Math.ceil((n+e-i)/c)-1,f=Math.floor((r-s)/l)+1,p=Math.ceil((r+t-a)/l)-1;return d<=u&&p<=f?[u,f]:null}updatePatternDims(e,t){let n=I.inverseTransform(this.patternBaseMatrix),r=[e[0],e[1]],i=[e[2],e[3]];I.applyTransform(r,n),I.applyTransform(i,n),t[0]=Math.abs(i[0]-r[0]),t[1]=Math.abs(i[1]-r[1]),t[2]=Math.min(r[0],i[0]),t[3]=Math.min(r[1],i[1])}_renderTileCanvas(e,t,n,r){let[i,a,o,s]=this.bbox,c=e.canvasFactory.create(n.size,r.size),l=c.context,u=this.canvasGraphicsFactory.createCanvasGraphics(l,t);return u.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(u,this.paintType,this.color),l.translate(-n.scale*i,-r.scale*a),u.transform(0,n.scale,0,0,r.scale,0,0),l.save(),u.dependencyTracker?.save(),this.clipBbox(u,i,a,o,s),u.baseTransform=B(u.ctx),u.executeOperatorList(this.operatorList),u.endDrawing(),u.dependencyTracker?.restore(),l.restore(),c}_getCombinedScales(){let e=new Float32Array(2);I.singularValueDecompose2dScale(this.matrix,e);let[t,n]=e;return I.singularValueDecompose2dScale(this.baseTransform,e),[t*e[0],n*e[1]]}drawPattern(e,t,n=!1,[r,i],a){let[o,s,c,l]=this.bbox,u=e.dependencyTracker;if(u&&(e.dependencyTracker=new Tt(u,a)),e.save(),n?e.ctx.clip(t,`evenodd`):e.ctx.clip(t),e.ctx.setTransform(...this.patternBaseMatrix),e.ctx.translate(r*this.xstep,i*this.ystep),this.needsIsolation||e.ctx.globalAlpha!==1||e.ctx.globalCompositeOperation!==`source-over`||e.inSMaskMode){let t=c-o,n=l-s,[r,i]=this._getCombinedScales(),u=this.getSizeAndScale(t,this.ctx.canvas.width,r),d=this.getSizeAndScale(n,this.ctx.canvas.height,i),f=this._renderTileCanvas(e,a,u,d);e.ctx.drawImage(f.canvas,o,s,t,n),e.canvasFactory.destroy(f)}else this.setFillAndStrokeStyleToContext(e,this.paintType,this.color),this.clipBbox(e,o,s,c,l),e.baseTransformStack.push(e.baseTransform),e.baseTransform=B(e.ctx),e.executeOperatorList(this.operatorList),e.baseTransform=e.baseTransformStack.pop();e.restore(),u&&(e.dependencyTracker=u)}createPatternCanvas(e,t){let[n,r,i,a]=this.bbox,o=i-n,s=a-r,{xstep:c,ystep:l}=this;c=Math.abs(c),l=Math.abs(l),w(`TilingType: `+this.tilingType);let[u,d]=this._getCombinedScales(),f=o,p=s,m=!1,h=!1;Math.ceil(c*u)>=Math.ceil(o*u)?f=c:m=!0,Math.ceil(l*d)>=Math.ceil(s*d)?p=l:h=!0;let g=this.getSizeAndScale(f,this.ctx.canvas.width,u),_=this.getSizeAndScale(p,this.ctx.canvas.height,d),v=this._renderTileCanvas(e,t,g,_);if(m||h){let t=v.canvas;m&&(f=c),h&&(p=l);let i=this.getSizeAndScale(f,this.ctx.canvas.width,u),a=this.getSizeAndScale(p,this.ctx.canvas.height,d),g=i.size,_=a.size,y=e.canvasFactory.create(g,_),b=y.context,x=m?Math.floor(o/c):0,S=h?Math.floor(s/l):0;for(let e=0;e<=x;e++)for(let n=0;n<=S;n++)b.drawImage(t,g*e,_*n,g,_,0,0,g,_);return e.canvasFactory.destroy(v),{canvas:y.canvas,canvasEntry:y,scaleX:i.scale,scaleY:a.scale,offsetX:n,offsetY:r}}return{canvas:v.canvas,canvasEntry:v,scaleX:g.scale,scaleY:_.scale,offsetX:n,offsetY:r}}getSizeAndScale(t,n,r){let i=Math.max(e.MAX_PATTERN_SIZE,n),a=Math.ceil(t*r);return a>=i?a=i:r=a/t,{scale:r,size:a}}clipBbox(e,t,n,r,i){let a=r-t,o=i-n,s=new Path2D;s.rect(t,n,a,o),I.axialAlignedBoundingBox([t,n,r,i],B(e.ctx),e.current.minMax),e.ctx.clip(s),e.current.updateClipFromPath()}setFillAndStrokeStyleToContext(e,t,n){let r=e.ctx,i=e.current;switch(i.patternFill=i.patternStroke=!1,t){case yn.COLORED:let{fillStyle:e,strokeStyle:a}=this.ctx;r.fillStyle=i.fillColor=e,r.strokeStyle=i.strokeColor=a;break;case yn.UNCOLORED:r.fillStyle=r.strokeStyle=n,i.fillColor=i.strokeColor=n;break;default:throw new ie(`Unsupported paint type: ${t}`)}}isModifyingCurrentTransform(){return!1}getPattern(e,t,n,r,i){let a=r===Y.SHADING?n:I.transform(n,this.patternBaseMatrix),o=this.createPatternCanvas(t,i),s=new DOMMatrix(a);s=s.translate(o.offsetX,o.offsetY),s=s.scale(1/o.scaleX,1/o.scaleY);let c=e.createPattern(o.canvas,`repeat`);return t.canvasFactory.destroy(o.canvasEntry),c.setTransform(s),c}},xn=16,Sn=100,Cn=15,wn=10,X=16,Tn=new DOMMatrix,Z=new Float32Array(2);function En(e,t){if(e._removeMirroring)throw Error(`Context is already forwarding operations.`);let n=new Map;for(let r of[`save`,`restore`,`rotate`,`scale`,`translate`,`transform`,`setTransform`,`resetTransform`,`clip`,`moveTo`,`lineTo`,`bezierCurveTo`,`quadraticCurveTo`,`arc`,`arcTo`,`ellipse`,`rect`,`roundRect`,`closePath`,`beginPath`]){let i=e[r];typeof i==`function`&&typeof t[r]==`function`&&(n.set(r,i),e[r]=function(...e){return t[r](...e),i.apply(this,e)})}e._removeMirroring=()=>{for(let[t,r]of n)e[t]=r;delete e._removeMirroring}}function Dn(e,t,n,r,i,a,o,s,c,l){let[u,d,f,p,m,h]=B(e);if(d===0&&f===0){let g=o*u+m,_=Math.round(g),v=s*p+h,y=Math.round(v),b=(o+c)*u+m,x=Math.abs(Math.round(b)-_)||1,S=(s+l)*p+h,C=Math.abs(Math.round(S)-y)||1;return e.setTransform(Math.sign(u),0,0,Math.sign(p),_,y),e.drawImage(t,n,r,i,a,0,0,x,C),e.setTransform(u,d,f,p,m,h),[x,C]}if(u===0&&p===0){let g=s*f+m,_=Math.round(g),v=o*d+h,y=Math.round(v),b=(s+l)*f+m,x=Math.abs(Math.round(b)-_)||1,S=(o+c)*d+h,C=Math.abs(Math.round(S)-y)||1;return e.setTransform(0,Math.sign(d),Math.sign(f),0,_,y),e.drawImage(t,n,r,i,a,0,0,C,x),e.setTransform(u,d,f,p,m,h),[C,x]}e.drawImage(t,n,r,i,a,o,s,c,l);let g=Math.hypot(u,d),_=Math.hypot(f,p);return[g*c,_*l]}var On=class{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=i;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=p.FILL;textRise=0;fillColor=`#000000`;strokeColor=`#000000`;tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps=`none`;minMax=r.slice();constructor(e,t){this.clipBox=new Float32Array([0,0,e,t])}clone(){let e=Object.create(this);return e.clipBox=this.clipBox.slice(),e.minMax=this.minMax.slice(),e.tilingPatternDims=this.tilingPatternDims?.slice(),e}getPathBoundingBox(e=Y.FILL,t=null){let n=this.minMax.slice();if(e===Y.STROKE){t||E(`Stroke bounding box must include transform.`),I.singularValueDecompose2dScale(t,Z);let e=Z[0]*this.lineWidth/2,r=Z[1]*this.lineWidth/2;n[0]-=e,n[1]-=r,n[2]+=e,n[3]+=r}return n}updateClipFromPath(){let e=I.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(e){this.clipBox.set(e,0),this.minMax.set(r,0)}getClippedPathBoundingBox(e=Y.FILL,t=null){return I.intersect(this.clipBox,this.getPathBoundingBox(e,t))}};function kn(e,t){let{width:n,height:r,kind:i}=t,a=r%X,o=(r-a)/X,s=a===0?o:o+1,c=e.createImageData(n,X),l=0,u=t.data,d=c.data,f;if(i===m.GRAYSCALE_1BPP)for(f=0;fwn&&typeof n==`function`,u=l?Date.now()+Cn:0,d=0,f=this.commonObjs,p=this.objs,m,h;for(;;){if(r!==void 0){if(s===r.nextBreakPoint)return r.breakIt(s,n),s;if(r.shouldSkip(s)){if(++s===c)return s;continue}}if(!i||i(s)){if(m=o[s],h=a[s]??null,m!==v.dependency)h===null?this[m](s):this[m](s,...h);else for(let e of h){this.dependencyTracker?.recordNamedData(e,s);let t=e.startsWith(`g_`)?f:p;if(!t.has(e))return t.get(e,n),s}}if(s++,s===c)return s;if(l&&++d>wn){if(Date.now()>u)return n(),s;d=0}}}#u(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)}endDrawing(){this.#u();for(let e of this.smaskGroupCanvases)this.canvasFactory.destroy(e);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0;for(let e of this.#l)this.#y(e);this.#l.length=0,this.#n=null,this.#r=null,this.#i=null,this.#a=null,this.#o=1,this.#c=null,this.#t=0,this.#e=0,this.cachedPatterns.clear();for(let e of this._cachedBitmapsMap.values()){for(let t of e.values())typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement&&(t.width=t.height=0);e.clear()}this._cachedBitmapsMap.clear(),this.#d()}#d(){if(this.pageColors){let e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!==`none`){let t=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=t}}}_scaleImage(e,t){let n=e.width??e.displayWidth,r=e.height??e.displayHeight,i=Math.max(Math.hypot(t[0],t[1]),1),a=Math.max(Math.hypot(t[2],t[3]),1),o=[],s=i,c=a,l=n,u=r;for(;s>2&&l>1||c>2&&u>1;){let e=l,t=u;s>2&&l>1&&(e=Math.ceil(l/2),s/=l/e),c>2&&u>1&&(t=Math.ceil(u/2),c/=u/t),o.push({newWidth:e,newHeight:t}),l=e,u=t}if(o.length===0)return{img:e,paintWidth:n,paintHeight:r,tmpCanvas:null};if(o.length===1){let{newWidth:t,newHeight:i}=o[0],a=this.canvasFactory.create(t,i);return a.context.drawImage(e,0,0,n,r,0,0,t,i),{img:a.canvas,paintWidth:t,paintHeight:i,tmpCanvas:a}}let d=this.canvasFactory.create(1,1),f=this.canvasFactory.create(1,1),p=n,m=r,h=e;for(let{newWidth:e,newHeight:t}of o)this.canvasFactory.reset(f,e,t),f.context.drawImage(h,0,0,p,m,0,0,e,t),[d,f]=[f,d],h=d.canvas,p=e,m=t;return this.canvasFactory.destroy(f),{img:d.canvas,paintWidth:p,paintHeight:m,tmpCanvas:d}}_createMaskCanvas(e,t){let n=this.ctx,{width:i,height:a}=t,o=this.current.fillColor,s=this.current.patternFill,c=B(n),l,u,d,f;if((t.bitmap||t.data)&&t.count>1){let n=t.bitmap||t.data.buffer;u=JSON.stringify(s?c:[c.slice(0,4),o]),l=this._cachedBitmapsMap.getOrInsertComputed(n,me);let r=l.get(u);if(r&&!s){let t=Math.round(Math.min(c[0],c[2])+c[4]),n=Math.round(Math.min(c[1],c[3])+c[5]);return this.dependencyTracker?.recordDependencies(e,G.transformAndFill),{canvas:r,offsetX:t,offsetY:n}}d=r}d||(f=this.canvasFactory.create(i,a),An(f.context,t));let p=I.transform(c,[1/i,0,0,-1/a,0,0]);p=I.transform(p,[1,0,0,1,0,-a]);let m=r.slice();I.axialAlignedBoundingBox([0,0,i,a],p,m);let[h,g,_,v]=m,y=Math.round(_-h)||1,b=Math.round(v-g)||1,x=this.canvasFactory.create(y,b),S=x.context,C=h,w=g;S.translate(-C,-w),S.transform(...p);let T=null;if(!d){let e=this._scaleImage(f.canvas,V(S));d=e.img,T=e.tmpCanvas,d!==f.canvas&&(this.canvasFactory.destroy(f),f=null),l&&s&&(l.set(u,d),T=null,f=null)}S.imageSmoothingEnabled=Nn(B(S),t.interpolate),Dn(S,d,0,0,d.width,d.height,0,0,i,a),T&&this.canvasFactory.destroy(T),f&&this.canvasFactory.destroy(f),S.globalCompositeOperation=`source-in`;let E=I.transform(V(S),[1,0,0,1,-C,-w]);return S.fillStyle=s?o.getPattern(n,this,E,Y.FILL,e):o,S.fillRect(0,0,i,a),l&&!s&&l.set(u,x.canvas),this.dependencyTracker?.recordDependencies(e,G.transformAndFill),{canvas:x.canvas,canvasEntry:l&&!s?null:x,offsetX:Math.round(C),offsetY:Math.round(w)}}setLineWidth(e,t){this.dependencyTracker?.recordSimpleData(`lineWidth`,e),t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(e,t){this.dependencyTracker?.recordSimpleData(`lineCap`,e),this.ctx.lineCap=Pn[t]}setLineJoin(e,t){this.dependencyTracker?.recordSimpleData(`lineJoin`,e),this.ctx.lineJoin=Fn[t]}setMiterLimit(e,t){this.dependencyTracker?.recordSimpleData(`miterLimit`,e),this.ctx.miterLimit=t}setDash(e,t,n){this.dependencyTracker?.recordSimpleData(`dash`,e);let r=this.ctx;r.setLineDash!==void 0&&(r.setLineDash(t),r.lineDashOffset=n)}setRenderingIntent(e,t){}setFlatness(e,t){}setGState(e,t){for(let[n,r]of t)switch(n){case`LW`:this.setLineWidth(e,r);break;case`LC`:this.setLineCap(e,r);break;case`LJ`:this.setLineJoin(e,r);break;case`ML`:this.setMiterLimit(e,r);break;case`D`:this.setDash(e,r[0],r[1]);break;case`RI`:this.setRenderingIntent(e,r);break;case`FL`:this.setFlatness(e,r);break;case`Font`:this.setFont(e,r[0],r[1]);break;case`CA`:this.dependencyTracker?.recordSimpleData(`strokeAlpha`,e),this.current.strokeAlpha=r;break;case`ca`:this.dependencyTracker?.recordSimpleData(`fillAlpha`,e),this.ctx.globalAlpha=this.current.fillAlpha=r;break;case`BM`:this.dependencyTracker?.recordSimpleData(`globalCompositeOperation`,e),this.ctx.globalCompositeOperation=r;break;case`SMask`:this.dependencyTracker?.recordSimpleData(`SMask`,e),this.current.activeSMask=r?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(e);break;case`TR`:this.dependencyTracker?.recordSimpleData(`filter`,e),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(r)}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&=(this.canvasFactory.destroy(this.smaskPreparedEntry),null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(e){e!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(e))}checkSMaskState(e){let t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode(e):!this.current.activeSMask&&t?this.endSMaskMode():this.current.activeSMask&&t&&this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(e){let{canvas:t,subtype:n,backdrop:r,transferMap:i}=e,a=n===`Luminosity`||n===`Alpha`&&i;if(!a&&!(n===`Luminosity`&&r)){this.smaskPreparedFor=e;return}let o;if(n===`Luminosity`&&r){let[e,t,n]=Me(r),a=Math.round(.3*e+.59*t+.11*n);o=i?.[a]??a}else o=i?.[0]??0;let{width:s,height:c}=this.ctx.canvas,l=t.width*t.height,u=s*c<4*l,d=a?{url:n===`Alpha`?this.filterFactory.addAlphaFilter(i):this.filterFactory.addLuminosityFilter(i),subtype:n,transferMap:i}:null,f=n===`Luminosity`?r:null,p,m,h;u?(p=this._bakeSMaskCanvas(t,e.offsetX,e.offsetY,s,c,f,d),m=0,h=0):(p=this._bakeSMaskCanvas(t,0,0,t.width,t.height,f,d),m=e.offsetX,h=e.offsetY),this.smaskPreparedEntry=p,this.smaskPreparedFor=e,this.smaskPreparedOffsetX=m,this.smaskPreparedOffsetY=h,this.smaskPreparedOOBAlpha=!u&&o!==0?o:null}_bakeSMaskCanvas(e,t,n,r,i,a,o){!a&&!o&&E(`_bakeSMaskCanvas with neither backdrop nor filter`);let s=this.canvasFactory.create(r,i),c=s.context;if(c.drawImage(e,t,n),a&&(c.globalCompositeOperation=`destination-atop`,c.fillStyle=a,c.fillRect(0,0,r,i)),!o)return s;let l=this.canvasFactory.create(r,i),u=l.context;u.filter=o.url;let d=F.isCanvasFilterSupported&&u.filter!==`none`&&u.filter!==``;if(u.drawImage(s.canvas,0,0),F.isCanvasFilterSupported&&(u.filter=`none`),!d){let e=u.getImageData(0,0,r,i),{data:t}=e,{transferMap:n}=o;if(o.subtype===`Luminosity`)for(let e=0,r=t.length;ethis.filterFactory.addKnockoutFilter(n))),!s||c!==`none`)return t&&(o.save(),o.setTransform(1,0,0,1,0,0),o.clearRect(0,0,r,i),o.restore()),o.filter=c,o.drawImage(e,0,0),o.filter=`none`,a;let l=e.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,r,i),u=o.createImageData(r,i),d=l.data,f=u.data,p=n>0?1/n:1e6;for(let e=3,t=d.length;e0||!this.contentVisible)return!1;this.#t++,this.#o=e;let t=this.#l.at(-1),{canvas:n}=this.ctx,r=this.#p(t,`knockoutTempEntry`,n.width,n.height);this.#n=r;let i=r.context;return i.save(),i.setTransform(this.ctx.getTransform()),jn(this.ctx,i),this.#a=i.globalCompositeOperation,i.globalCompositeOperation=`source-over`,En(i,this.ctx),this.#c=t,this.#r=this.ctx,this.#i=this.suspendedCtx,this.ctx=i,this.inSMaskMode&&(this.suspendedCtx=i),!0}#g(e){if(!e)return;let t=this.#n,n=this.#r,r=this.#i,i=t.context;this.#n=null,this.#r=null,this.#i=null,this.inSMaskMode&&this.suspendedCtx===i&&this.ctx!==i&&this.endSMaskMode(),this.inSMaskMode&&(this.suspendedCtx=r),this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=this.#a,this.#a=null,jn(this.ctx,n),this.ctx=n;let a=this.#c;this.#c=null;let o=this.#o;this.#o=1;try{this.#m(r??n,t.canvas,{backdropCanvas:a?.backdropCtx?.canvas??null,backdropOffset:a?.backdropCtx?[a.offsetX,a.offsetY]:[0,0],reuseMaskEntry:a?.knockoutMaskEntry??null,poolMeta:a,knockoutAlpha:o})}finally{i.restore(),this.#t--,a||this.canvasFactory.destroy(t)}}compose(e){if(!this.current.activeSMask)return;e=e?[Math.floor(e[0]),Math.floor(e[1]),Math.ceil(e[2]),Math.ceil(e[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let t=this.current.activeSMask,n=this.suspendedCtx,r=this.#t>0&&n===this.ctx;this.composeSMask(r?null:n,t,this.ctx,e),!r&&(this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore())}composeSMask(e,t,n,r){let i=r[0],a=r[1],o=r[2]-i,s=r[3]-a;if(o===0||s===0)return;let c=this.smaskPreparedEntry;if(c){let e=i,r=a,l=o,u=s,d=this.smaskPreparedOOBAlpha,f=d!==null;if(f){e=Math.max(i,t.offsetX),r=Math.max(a,t.offsetY);let n=Math.min(i+o,t.offsetX+t.canvas.width),c=Math.min(a+s,t.offsetY+t.canvas.height);l=n-e,u=c-r}if(l>0&&u>0){let t=e-this.smaskPreparedOffsetX,i=r-this.smaskPreparedOffsetY;n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0);let a=new Path2D;a.rect(e,r,l,u),n.clip(a),n.globalCompositeOperation=`destination-in`,n.drawImage(c.canvas,t,i,l,u,e,r,l,u),n.restore()}f&&d<255&&this._applySMaskOOBAlpha(n,i,a,o,s,e,r,e+l,r+u,d)}else this.genericComposeSMask(t,n,o,s,i,a);e&&(e.save(),e.globalAlpha=1,e.globalCompositeOperation=t.blendMode||`source-over`,e.setTransform(1,0,0,1,0,0),e.drawImage(n.canvas,i,a,o,s,i,a,o,s),e.restore())}_applySMaskOOBAlpha(e,t,n,r,i,a,o,s,c,l){let u=ao.measureText(t))),(d===p.STROKE||d===p.FILL_STROKE)&&(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(e,o,c,u,n,r,()=>o.measureText(t)).recordDependencies(e,G.stroke),o.strokeText(t,n,r));f&&((this.pendingTextPaths||=[]).push({transform:B(o),x:n,y:r,fontSize:u,path:g}),this.dependencyTracker?.recordCharacterBBox(e,o,c,u,n,r))}get isFontSubpixelAAEnabled(){let e=this.canvasFactory.create(10,10),t=e.context;t.scale(1.5,1),t.fillText(`I`,0,10);let n=t.getImageData(0,0,10,10).data;this.canvasFactory.destroy(e);let r=!1;for(let e=3;e0&&n[e]<255){r=!0;break}return M(this,`isFontSubpixelAAEnabled`,r)}showText(e,t){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(e,G.showText).resetBBox(e),this.current.textRenderingMode&p.ADD_TO_PATH_FLAG&&this.dependencyTracker.recordFutureForcedDependency(`textClip`,e).inheritPendingDependenciesAsFutureForcedDependencies());let n=this.current,r=n.font;if(r.isType3Font){let r=this.#h(n.fillAlpha);this.showType3Text(e,t),this.dependencyTracker?.recordShowTextOperation(e),this.#g(r);return}let i=n.fontSize;if(i===0){this.dependencyTracker?.recordOperation(e);return}let a=this.#h(n.fillAlpha),o=this.ctx,s=n.fontSizeScale,c=n.charSpacing,l=n.wordSpacing,u=n.fontDirection,d=n.textHScale*u,f=t.length,m=r.vertical,h=m?1:-1,g=r.defaultVMetrics,_=i*n.fontMatrix[0],v=n.textRenderingMode===p.FILL&&!r.disableFontFace&&!n.patternFill;o.save(),n.textMatrix&&o.transform(...n.textMatrix),o.translate(n.x,n.y+n.textRise),u>0?o.scale(d,-1):o.scale(d,1);let y,b,x=n.textRenderingMode&p.FILL_STROKE_MASK,S=x===p.FILL||x===p.FILL_STROKE,C=x===p.STROKE||x===p.FILL_STROKE,w=n.lineWidth,T=n.textMatrixScale;if(T===0||w===0?C&&(w=this.getSinglePixelWidth()):w/=T,s!==1&&(o.scale(s,s),w/=s),o.lineWidth=w,S&&n.patternFill){o.save();let t=n.fillColor.getPattern(o,this,V(o),Y.FILL,e);y=B(o),o.restore(),o.fillStyle=t}if(C&&n.patternStroke){o.save();let t=n.strokeColor.getPattern(o,this,V(o),Y.STROKE,e);b=B(o),o.restore(),o.strokeStyle=t}if(r.isInvalidPDFjsFont){let r=[],i=0;for(let e of t)r.push(e.unicode),i+=e.width;let s=r.join(``);if(o.fillText(s,0,0),this.dependencyTracker!==null){let t=o.measureText(s);this.dependencyTracker.recordBBox(e,this.ctx,-t.actualBoundingBoxLeft,t.actualBoundingBoxRight,-t.actualBoundingBoxAscent,t.actualBoundingBoxDescent).recordShowTextOperation(e)}n.x+=i*_*d,o.restore(),this.compose(),this.#g(a);return}let E=0,D;for(D=0;D0){w=o.measureText(f);let e=w.width*1e3/i*s;if(Cw??o.measureText(f));else if(this.paintChar(e,f,x,S,y,b),p){let t=x+i*p.offset.x/s,n=S-i*p.offset.y/s;this.paintChar(e,p.fontChar,t,n,y,b)}}let T=m?C*_-d*u:C*_+d*u;E+=T,a&&o.restore()}m?n.y-=E:n.x+=E*d,o.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(e),this.#g(a)}showType3Text(e,t){let n=this.ctx,r=this.current,a=r.font,o=r.fontSize,s=r.fontDirection,c=a.vertical?1:-1,l=r.charSpacing,u=r.wordSpacing,d=r.textHScale*s,f=r.fontMatrix||i,m=t.length,h=r.textRenderingMode===p.INVISIBLE,g,_,y,b;if(h||o===0)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,n.save(),r.textMatrix&&n.transform(...r.textMatrix),n.translate(r.x,r.y+r.textRise),n.scale(d,s);let x=this.dependencyTracker;for(this.dependencyTracker=x?new Tt(x,e):null,g=0;gnew e(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new Tt(this.dependencyTracker,n,!0):null)},t)}else r=this._getPattern(t,n[1],n[2]);return r}setStrokeColorN(e,...t){this.dependencyTracker?.recordSimpleData(`strokeColor`,e),this.current.strokeColor=this.getColorN_Pattern(e,t),this.current.patternStroke=!0}setFillColorN(e,...t){this.dependencyTracker?.recordSimpleData(`fillColor`,e);let n=this.current.fillColor=this.getColorN_Pattern(e,t);this.current.patternFill=!0,this.current.tilingPatternDims=n instanceof bn?[0,0,0,0]:null}setStrokeRGBColor(e,t){this.dependencyTracker?.recordSimpleData(`strokeColor`,e),this.ctx.strokeStyle=this.current.strokeColor=t,this.current.patternStroke=!1}setStrokeTransparent(e){this.dependencyTracker?.recordSimpleData(`strokeColor`,e),this.ctx.strokeStyle=this.current.strokeColor=`transparent`,this.current.patternStroke=!1}setFillRGBColor(e,t){this.dependencyTracker?.recordSimpleData(`fillColor`,e),this.ctx.fillStyle=this.current.fillColor=t,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(e){this.dependencyTracker?.recordSimpleData(`fillColor`,e),this.ctx.fillStyle=this.current.fillColor=`transparent`,this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(e,t,n=null){let r=this.cachedPatterns.getOrInsertComputed(t,()=>vn(this.getObject(e,t)));return n&&(r.matrix=n),r}shadingFill(e,t){if(!this.contentVisible)return;let n=this.#h(this.current.fillAlpha),i=this.ctx;this.save(e),i.fillStyle=this._getPattern(e,t).getPattern(i,this,V(i),Y.SHADING,e);let a=V(i);if(a){let{width:e,height:t}=i.canvas,n=r.slice();I.axialAlignedBoundingBox([0,0,e,t],a,n);let[o,s,c,l]=n;this.ctx.fillRect(o,s,c-o,l-s)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(e).recordFullPageBBox(e).recordDependencies(e,G.transform).recordDependencies(e,G.fill).recordOperation(e),this.compose(this.current.getClippedPathBoundingBox()),this.restore(e),this.#g(n)}beginInlineImage(){E(`Should not call beginInlineImage`)}beginImageData(){E(`Should not call beginImageData`)}paintFormXObjectBegin(e,t,n){if(this.contentVisible&&(this.save(e),this.baseTransformStack.push(this.baseTransform),t&&this.transform(e,...t),this.baseTransform=B(this.ctx),n)){I.axialAlignedBoundingBox(n,this.baseTransform,this.current.minMax);let[t,r,i,a]=n,o=new Path2D;o.rect(t,r,i-t,a-r),this.ctx.clip(o),this.dependencyTracker?.recordClipBox(e,this.ctx,t,i,r,a),this.endPath(e)}}paintFormXObjectEnd(e){this.contentVisible&&(this.restore(e),this.baseTransform=this.baseTransformStack.pop())}beginGroup(e,t){if(!this.contentVisible)return;this.save(e);let{inSMaskMode:n}=this;n&&(this.endSMaskMode(),this.current.activeSMask=null);let i=this.ctx;if((!t.needsIsolation||!t.isolated&&!t.hasSoftMask)&&!t.knockout&&!t.isGray&&this.#e===0&&i.globalAlpha===1&&i.globalCompositeOperation===`source-over`&&!n){if(t.bbox){let e=new Path2D,[n,r,a,o]=t.bbox;if(e.rect(n,r,a-n,o-r),t.matrix){let n=new Path2D;n.addPath(e,new DOMMatrix(t.matrix)),e=n}i.clip(e)}this.groupStack.push(null),this.#l.push(null),this.groupLevel++;return}!t.isolated&&!t.knockout&&this.#e===0&&w(`TODO: Fully support non-isolated non-knockout groups.`);let a=B(i);t.matrix&&i.transform(...t.matrix);let o=[0,0,i.canvas.width,i.canvas.height],s;t.bbox?(s=r.slice(),I.axialAlignedBoundingBox(t.bbox,B(i),s),s=I.intersect(s,o)||[0,0,0,0]):s=o;let c=Math.floor(s[0]),l=Math.floor(s[1]),u=Math.max(Math.ceil(s[2])-c,1),d=Math.max(Math.ceil(s[3])-l,1);this.current.startNewPathAndClipBox([0,0,u,d]);let f=this.canvasFactory.create(u,d);t.smask&&this.smaskGroupCanvases.push(f);let p=f.context,m=t.knockout&&!t.isolated?i:null,h=!t.isolated&&!t.knockout&&!t.smask&&t.needsIsolation&&this.#e>0,g=t.knockout?this.canvasFactory.create(u,d):null,_=this.#e;t.knockout?this.#e++:this.#e=0,p.translate(-c,-l),p.transform(...a);let v=!t.isolated&&!t.smask&&t.needsIsolation,y=v&&!n&&_===0&&!t.knockout&&!t.isGray&&t.hasSoftMask&&i.globalAlpha===1&&i.globalCompositeOperation===`source-over`&&this.current.transferMaps===`none`;if(v&&(n||y)&&(p.save(),p.setTransform(1,0,0,1,0,0),p.drawImage(i.canvas,-c,-l),p.restore()),t.bbox){let e=new Path2D,[n,r,i,a]=t.bbox;if(e.rect(n,r,i-n,a-r),t.matrix){let n=new Path2D;n.addPath(e,new DOMMatrix(t.matrix)),e=n}p.clip(e)}t.smask&&this.smaskStack.push({canvas:f.canvas,context:p,offsetX:c,offsetY:l,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null}),(!t.smask||this.dependencyTracker)&&(i.setTransform(1,0,0,1,0,0),i.translate(c,l),i.save()),jn(i,p),this.ctx=p,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies([`fillAlpha`,`strokeAlpha`,`globalCompositeOperation`]).pushBaseTransform(i),this.setGState(e,[[`BM`,`source-over`],[`ca`,1],[`CA`,1],[`TR`,null]]),this.groupStack.push(i),this.#l.push({backdropCtx:m,savedKnockoutLevel:_,offsetX:c,offsetY:l,hasInnerBackdrop:h,replaceBackdrop:y,knockoutMaskEntry:g,knockoutTempEntry:null,knockoutBackdropEntry:null}),this.groupLevel++}endGroup(e,t){if(!this.contentVisible)return;this.groupLevel--;let n=this.ctx,i=this.groupStack.pop(),a=this.#l.pop();if(a&&(this.#e=a.savedKnockoutLevel),i===null){this.restore(e);return}if(t.isGray&&this.#v(n),this.ctx=i,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),t.smask)this.tempSMask=this.smaskStack.pop(),this.restore(e),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())),this.#y(a);else{this.ctx.restore();let t=B(this.ctx);this.restore(e),this.ctx.save(),this.ctx.setTransform(...t);let o=r.slice();I.axialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],t,o);let s=this.#l.at(-1);if(this.#e>0){if(a.hasInnerBackdrop){let{width:e,height:r}=n.canvas,o=this.canvasFactory.create(e,r),s=o.context;s.drawImage(i.canvas,a.offsetX,a.offsetY,e,r,0,0,e,r),s.globalCompositeOperation=`source-over`,s.drawImage(n.canvas,0,0);let c=this.#f(n.canvas);s.globalCompositeOperation=`destination-in`,s.drawImage(c.canvas,0,0);let l=this.ctx.globalCompositeOperation,u=this.ctx.globalAlpha,d=this.ctx.filter;this.ctx.save(),this.ctx.setTransform(...t),this.ctx.globalAlpha=1,F.isCanvasFilterSupported&&(this.ctx.filter=`none`),this.ctx.globalCompositeOperation=`destination-out`,this.ctx.drawImage(c.canvas,0,0),this.ctx.globalCompositeOperation=l,this.ctx.globalAlpha=u,F.isCanvasFilterSupported&&(this.ctx.filter=d??`none`),this.ctx.drawImage(o.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(c),this.canvasFactory.destroy(o)}else{let e=s?.backdropCtx??null;this.#m(this.ctx,n.canvas,{backdropCanvas:e?.canvas??null,destTransform:t,backdropOffset:e?[s.offsetX+a.offsetX,s.offsetY+a.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}}else{if(a.replaceBackdrop){let e=new Path2D;e.rect(0,0,n.canvas.width,n.canvas.height),this.ctx.clip(e),this.ctx.globalCompositeOperation=`copy`}this.ctx.drawImage(n.canvas,0,0)}this.ctx.restore(),this.canvasFactory.destroy({canvas:n.canvas,context:n}),this.#y(a),this.compose(o)}}#v(e){let{canvas:t}=e,{width:n,height:r}=t;if(F.isCanvasFilterSupported){e.save(),e.setTransform(1,0,0,1,0,0),e.filter=`grayscale(1)`,e.globalAlpha=1,e.globalCompositeOperation=`copy`,e.drawImage(t,0,0),e.restore();return}let i=e.getImageData(0,0,n,r),{data:a}=i;for(let e=0,t=a.length;ee.getAttribute(`data-canvas-name`)===o);n===-1?e.push(l):e[n]=l}else this.annotationCanvasMap.set(t,l);this.annotationCanvas.savedCtx=this.ctx,this.ctx=u,this.ctx.save(),this.ctx.setTransform(Z[0],0,0,-Z[1],0,s*Z[1]),Mn(this.ctx)}else{Mn(this.ctx),this.endPath(e);let t=new Path2D;t.rect(n[0],n[1],i,s),this.ctx.clip(t)}}this.current=new On(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(e,...r),this.transform(e,...i),this.baseTransform=B(this.ctx)}endAnnotation(e){this.annotationCanvas&&(this.ctx.restore(),this.#d(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(e,t){if(!this.contentVisible)return;let n=t.count;t=this.getObject(e,t.data,t),t.count=n;let r=this.#h(this.current.fillAlpha),i=this.ctx,a=this._createMaskCanvas(e,t),o=a.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(o,a.offsetX,a.offsetY),this.dependencyTracker?.resetBBox(e).recordBBox(e,this.ctx,a.offsetX,a.offsetX+o.width,a.offsetY,a.offsetY+o.height).recordOperation(e),i.restore(),a.canvasEntry&&this.canvasFactory.destroy(a.canvasEntry),this.compose(),this.#g(r)}paintImageMaskXObjectRepeat(e,t,n,r=0,i=0,a,o){if(!this.contentVisible)return;t=this.getObject(e,t.data,t);let s=this.#h(this.current.fillAlpha),c=this.ctx;c.save();let l=B(c);c.transform(n,r,i,a,0,0);let u=this._createMaskCanvas(e,t);c.setTransform(1,0,0,1,u.offsetX-l[4],u.offsetY-l[5]),this.dependencyTracker?.resetBBox(e);for(let t=0,s=o.length;tt?l/t:1,o=c>t?c/t:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(e,t){let{ctx:n,current:{lineWidth:r}}=this,[i,a]=this.getScaleForStroking();if(i===a){n.lineWidth=(r||1)*i,n.stroke(e);return}let o=n.getLineDash();t&&n.save(),n.scale(i,a),Tn.a=1/i,Tn.d=1/a;let s=new Path2D;if(s.addPath(e,Tn),o.length>0){let e=Math.max(i,a);n.setLineDash(o.map(t=>t/e)),n.lineDashOffset/=e}n.lineWidth=r||1,n.stroke(s),t&&n.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}};for(let e in v)Rn.prototype[e]!==void 0&&(Rn.prototype[v[e]]=Rn.prototype[e]);var zn=class{#e=null;#t=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(e,t,n){this._source=e,this.#e=t,this.#t=n}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){return D(!this._fullReader,`BasePDFStream.getFullReader can only be called once.`),this._fullReader=new this.#e(this)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new this.#t(this,e,t);return this._rangeReaders.add(n),n}cancelAllRequests(e){this._fullReader?.cancel(e);for(let t of new Set(this._rangeReaders))t.cancel(e)}},Bn=class{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(e){this._stream=e}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){E("Abstract method `read` called")}cancel(e){E("Abstract method `cancel` called")}},Vn=class{_stream=null;constructor(e,t,n){this._stream=e}async read(){E("Abstract method `read` called")}cancel(e){E("Abstract method `cancel` called")}};function Hn(e){let t=!0,n=r(`filename\\*`,`i`).exec(e);if(n){n=n[1];let e=s(n);return e=unescape(e),e=c(e),e=l(e),a(e)}if(n=o(e),n)return a(l(n));if(n=r(`filename`,`i`).exec(e),n){n=n[1];let e=s(n);return e=l(e),a(e)}function r(e,t){return RegExp(`(?:^|;)\\s*`+e+`\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)`,t)}function i(e,n){if(e){if(!/^[\x00-\xFF]+$/.test(n))return n;try{let r=new TextDecoder(e,{fatal:!0}),i=oe(n);n=r.decode(i),t=!1}catch{}}return n}function a(e){return t&&/[\x80-\xff]/.test(e)&&(e=i(`utf-8`,e),t&&(e=i(`iso-8859-1`,e))),e}function o(e){let t=[],n,i=r(`filename\\*((?!0\\d)\\d+)(\\*?)`,`ig`);for(;(n=i.exec(e))!==null;){let[,e,r,i]=n;if(e=parseInt(e,10),e in t){if(e===0)break;continue}t[e]=[r,i]}let a=[];for(let e=0;e{e._responseOrigin=Wn(n.url),Xn(n.status,i),this._reader=n.body.getReader();let a=n.headers,{contentLength:o,isRangeSupported:s}=Gn({responseHeaders:a,isHttp:!0,rangeChunkSize:r,disableRange:t});this._contentLength=o,this._isRangeSupported=s,this._filename=Kn(a),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new P(`Streaming is disabled.`)),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,this._callOnProgress(),{value:Zn(e),done:!1})}cancel(e){this._reader?.cancel(e),this._abortController.abort()}},er=class extends Vn{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(e,t,n){super(e,t,n);let{url:r,withCredentials:i}=e._source,a=new Headers(e.headers);a.append(`Range`,`bytes=${t}-${n-1}`),Yn(r,a,i,this._abortController).then(t=>{Jn(Wn(t.url),e._responseOrigin),Xn(t.status,r),this._reader=t.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:{value:Zn(e),done:!1}}cancel(e){this._reader?.cancel(e),this._abortController.abort()}};function tr(e){return e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function nr(){for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}var rr=class extends zn{_progressiveDone=!1;_queuedChunks=[];constructor(e){super(e,ir,ar);let{pdfDataRangeTransport:t}=e,{initialData:n,progressiveDone:r}=t;if(n?.length>0){let e=tr(n);this._queuedChunks.push(e)}this._progressiveDone=r,t.transportReady(e=>{switch(e.type){case`range`:case`progressiveRead`:this.#e(e.begin,e.chunk);break;case`progressiveDone`:this._fullReader?.progressiveDone(),this._progressiveDone=!0}})}#e(e,t){let n=tr(t);if(e===void 0)this._fullReader?this._fullReader._enqueue(n):this._queuedChunks.push(n);else{let t=this._rangeReaders.keys().find(t=>t._begin===e);D(t,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),t._enqueue(n)}}getFullReader(){let e=super.getFullReader();return this._queuedChunks=null,e}getRangeReader(e,t){let n=super.getRangeReader(e,t);return n&&(n.onDone=()=>this._rangeReaders.delete(n),this._source.pdfDataRangeTransport.requestDataRange(e,t)),n}cancelAllRequests(e){super.cancelAllRequests(e),this._source.pdfDataRangeTransport.abort()}},ir=class extends Bn{#e=nr.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(e){super(e);let{pdfDataRangeTransport:t,disableRange:n,disableStream:r}=e._source,{length:i,contentDispositionFilename:a}=t;this._queuedChunks=e._queuedChunks||[];for(let e of this._queuedChunks)this._loaded+=e.byteLength;this._done=e._progressiveDone,this._contentLength=i,this._isStreamingSupported=!r,this._isRangeSupported=!n,Ee(a)&&(this._filename=a),this._headersCapability.resolve();let o=this._loaded;Promise.resolve().then(()=>{o>0&&this._loaded===o&&this._callOnProgress()})}_enqueue(e){this._done||(this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunks.push(e),this._loaded+=e.byteLength,this._callOnProgress())}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this.#e()}progressiveDone(){this._done||=!0,this._queuedChunks.length===0&&this.#e()}},ar=class extends Vn{#e=nr.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(e,t,n){super(e,t,n),this._begin=t}_enqueue(e){this._done||(this._requests.length===0?this._queuedChunk=e:(this._requests.shift().resolve({value:e,done:!1}),this.#e()),this._done=!0,this.onDone?.())}async read(){if(this._queuedChunk){let e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this.#e(),this.onDone?.()}},or=200,sr=206;function cr(e){return typeof e==`string`?oe(e).buffer:e}var lr=class extends zn{#e=new WeakMap;_responseOrigin=null;constructor(e){super(e,ur,dr);let{httpHeaders:t,url:n}=e;this.url=n,this.isHttp=/https?:/.test(n.protocol),this.headers=Un(this.isHttp,t)}_request(e){let t=new XMLHttpRequest,n={validateStatus:null,onHeadersReceived:e.onHeadersReceived,onDone:e.onDone,onError:e.onError,onProgress:e.onProgress};this.#e.set(t,n),t.open(`GET`,this.url),t.withCredentials=this._source.withCredentials;for(let[e,n]of this.headers)t.setRequestHeader(e,n);return this.isHttp&&`begin`in e&&`end`in e?(t.setRequestHeader(`Range`,`bytes=${e.begin}-${e.end-1}`),n.validateStatus=e=>e===sr||e===or):n.validateStatus=e=>e===or,t.responseType=`arraybuffer`,D(e.onError,"Expected `onError` callback to be provided."),t.onerror=()=>e.onError(t.status),t.onreadystatechange=this.#n.bind(this,t),t.onprogress=this.#t.bind(this,t),t.send(null),t}#t(e,t){this.#e.get(e)?.onProgress?.(t)}#n(e,t){let n=this.#e.get(e);if(!n||(e.readyState>=2&&n.onHeadersReceived&&(n.onHeadersReceived(),delete n.onHeadersReceived),e.readyState!==4)||!this.#e.has(e))return;if(this.#e.delete(e),e.status===0&&this.isHttp){n.onError(e.status);return}let r=e.status||or;if(!n.validateStatus(r)){n.onError(e.status);return}let i=cr(e.response);if(r===sr){let t=e.getResponseHeader(`Content-Range`);/bytes \d+-\d+\/\d+/.test(t)?n.onDone(i):(T(`Missing or invalid "Content-Range" header.`),n.onError(0))}else i?n.onDone(i):n.onError(e.status)}_abortRequest(e){this.#e.has(e)&&(this.#e.delete(e),e.abort())}getRangeReader(e,t){let n=super.getRangeReader(e,t);return n&&(n.onClosed=()=>this._rangeReaders.delete(n)),n}},ur=class extends Bn{#e=nr.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(e){super(e),this._fullRequestXhr=e._request({onHeadersReceived:this.#t.bind(this),onDone:this.#n.bind(this),onError:this.#r.bind(this),onProgress:this.#i.bind(this)})}#t(){let e=this._stream,{disableRange:t,rangeChunkSize:n}=e._source,r=this._fullRequestXhr;e._responseOrigin=Wn(r.responseURL);let i=r.getAllResponseHeaders(),a=new Headers(i?i.trimStart().replace(/[^\S ]+$/,``).split(/[\r\n]+/).map(e=>{let[t,...n]=e.split(`: `);return[t,n.join(`: `)]}):[]),{contentLength:o,isRangeSupported:s}=Gn({responseHeaders:a,isHttp:e.isHttp,rangeChunkSize:n,disableRange:t});this._contentLength=o,this._isRangeSupported=s,this._filename=Kn(a),this._isRangeSupported&&e._abortRequest(r),this._headersCapability.resolve()}#n(e){this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._cachedChunks.push(e),this._done=!0,this._cachedChunks.length===0&&this.#e()}#r(e){this._storedError=qn(e,this._stream.url),this._headersCapability.reject(this._storedError);for(let e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}#i(e){this.onProgress?.({loaded:e.loaded,total:e.lengthComputable?e.total:this._contentLength})}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this._headersCapability.reject(e),this.#e(),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}},dr=class extends Vn{#e=nr.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(e,t,n){super(e,t,n),this._requestXhr=e._request({begin:t,end:n,onHeadersReceived:this.#t.bind(this),onDone:this.#n.bind(this),onError:this.#r.bind(this),onProgress:null})}#t(){let e=Wn(this._requestXhr?.responseURL);try{Jn(e,this._stream._responseOrigin)}catch(e){this._storedError=e,this.#r(0)}}#n(e){this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0,this.#e(),this.onClosed?.()}#r(e){this._storedError??=qn(e,this._stream.url);for(let e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this.#e(),this._stream._abortRequest(this._requestXhr),this.onClosed?.()}};function fr(e,t=null){let n=process.getBuiltinModule(`fs`),{Readable:r}=process.getBuiltinModule(`stream`),i=n.createReadStream(e,t);return r.toWeb(i)}var pr=class extends zn{constructor(e){super(e,mr,hr);let{url:t}=e;D(t.protocol===`file:`,`PDFNodeStream only supports file:// URLs.`)}},mr=class extends Bn{_reader=null;constructor(e){super(e);let{disableRange:t,disableStream:n,rangeChunkSize:r,url:i}=e._source;this._isStreamingSupported=!n,process.getBuiltinModule(`fs/promises`).lstat(i).then(e=>{let n=fr(i);this._reader=n.getReader();let{size:a}=e;this._contentLength=a,this._isRangeSupported=!t&&a>2*r,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new P(`Streaming is disabled.`)),this._headersCapability.resolve()}).catch(e=>{e.code===`ENOENT`&&(e=qn(0,i)),this._headersCapability.reject(e)})}async read(){await this._headersCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,this._callOnProgress(),{value:Zn(e),done:!1})}cancel(e){this._reader?.cancel(e)}},hr=class extends Vn{_readCapability=Promise.withResolvers();_reader=null;constructor(e,t,n){super(e,t,n);let{url:r}=e._source;try{let e=fr(r,{start:t,end:n-1});this._reader=e.getReader(),this._readCapability.resolve()}catch(e){this._readCapability.reject(e)}}async read(){await this._readCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:{value:Zn(e),done:!1}}cancel(e){this._reader?.cancel(e)}};function gr(e){return Ae(e)?Qn:t?pr:lr}var _r=class{static#e=null;static#t=``;static get workerPort(){return this.#e}static set workerPort(e){if(!(typeof Worker<`u`&&e instanceof Worker)&&e!==null)throw Error("Invalid `workerPort` type.");this.#e=e}static get workerSrc(){return this.#t}static set workerSrc(e){if(typeof e!=`string`)throw Error("Invalid `workerSrc` type.");this.#t=e}},vr=class{#e;#t;constructor({parsedData:e,rawData:t}){this.#e=e,this.#t=t}getRaw(){return this.#t}get(e){return this.#e.get(e)??null}[Symbol.iterator](){return this.#e.entries()}},yr=Symbol(`INTERNAL`),br=class{#e=!1;#t=!1;#n=!1;#r=!0;constructor(e,{name:t,intent:n,usage:r,rbGroups:i}){this.#e=!!(e&o.DISPLAY),this.#t=!!(e&o.PRINT),this.name=t,this.intent=n,this.usage=r,this.rbGroups=i}get visible(){if(this.#n)return this.#r;if(!this.#r)return!1;let{print:e,view:t}=this.usage;return this.#e?t?.viewState!==`OFF`:!this.#t||e?.printState!==`OFF`}_setVisible(e,t,n=!1){e!==yr&&E("Internal method `_setVisible` called."),this.#n=n,this.#r=t}get serializable(){return{userSet:this.#n,visible:this.#r}}},xr=class e{#e=null;#t=new Map;#n=null;#r=null;#i;creator=null;name=null;constructor(e,t=o.DISPLAY,n=null){if(this.#i=e,this.renderingIntent=t,e!==null){this.name=e.name,this.creator=e.creator,this.#r=e.order;for(let n of e.groups)this.#t.set(n.id,new br(t,n));if(n){n.size!==this.#t.size&&E(`Incorrect serialized groupState.`);for(let[e,t]of n)this.#t.get(e)._setVisible(yr,t.visible,t.userSet)}else{if(e.baseState===`OFF`)for(let e of this.#t.values())e._setVisible(yr,!1);for(let t of e.on)this.#t.get(t)._setVisible(yr,!0);for(let t of e.off)this.#t.get(t)._setVisible(yr,!1)}this.#n=this.getHash()}}#a(e){let t=e.length;if(t<2)return!0;let n=e[0];for(let r=1;re===t+1)&&(this.#e=null)}deletePages(e){this.#a();let t=this.#e,n=this.#o();this.#i={pageNumberToId:t.slice(),pagesNumber:this.#n,prevPageNumbers:this.#t.slice()};let r=this.#n-e.length;this.#n=r;let i=this.#e=new Uint32Array(r);this.#t=new Int32Array(r);let a=0,o=0;for(let n of e){let e=n-1;e!==a&&(i.set(t.subarray(a,e),o),o+=e-a),a=e+1}athis.#e[e-1])}}cancelCopy(){this.#r=null}pastePages(e){this.#a();let t=this.#e,n=this.#o(),{pageNumbers:r,pageIds:i}=this.#r,a=this.#n+r.length;this.#n=a;let o=this.#e=new Uint32Array(a);this.#t=new Int32Array(a),o.set(t.subarray(0,e),0),o.set(i,e),o.set(t.subarray(e),e+r.length),this.#s(n,null,e,r),this.#r=null}#s(e,t=null,n=-1,r=null){let i=this.#t,a=this.#e,o=n+(r?.length??0),s=new Map;for(let c=0,l=this.#n;c=n&&ce[0]-t[0]);for(let n=0,r=e.length;ne-t);let t=new Map;for(let n=0,r=e.length;n({...Promise.withResolvers(),data:Cr}),Tr=class{#e=new Map;get(e,t=null){if(t){let n=this.#e.getOrInsertComputed(e,wr);return n.promise.then(()=>t(n.data)),null}let n=this.#e.get(e);if(!n||n.data===Cr)throw Error(`Requesting object that isn't resolved yet ${e}.`);return n.data}has(e){let t=this.#e.get(e);return!!t&&t.data!==Cr}delete(e){let t=this.#e.get(e);return!t||t.data===Cr?!1:(this.#e.delete(e),!0)}resolve(e,t=null){let n=this.#e.getOrInsertComputed(e,wr);if(n.data!==Cr)throw Error(`Object already resolved ${e}.`);n.data=t,n.resolve()}clear(){for(let{data:e}of this.#e.values())e?.bitmap?.close();this.#e.clear()}*[Symbol.iterator](){for(let[e,{data:t}]of this.#e)t!==Cr&&(yield[e,t])}},Er=1e5,Dr=30,Or=class e{#e=Promise.withResolvers();#t=null;#n=!1;#r=!!globalThis.FontInspector?.enabled;#i=null;#a=null;#o=null;#s=0;#c=0;#l=null;#u=null;#d=0;#f=0;#p=Object.create(null);#m=[];#h=null;#g=[];#_=new WeakMap;#v=null;static#y=new Map;static#b=new Map;static#x=new WeakMap;static#S=null;static#C=new Set;constructor({textContentSource:t,images:n,container:r,viewport:i}){if(t instanceof ReadableStream)this.#h=t;else if(typeof t==`object`)this.#h=new ReadableStream({start(e){e.enqueue(t),e.close()}});else throw Error(`No "textContentSource" parameter specified.`);this.#t=this.#u=r,this.#i=n,this.#f=i.scale*Ie.pixelRatio,this.#d=i.rotation,this.#o={div:null,properties:null,ctx:null};let{pageWidth:a,pageHeight:o,pageX:s,pageY:c}=i.rawDims;this.#v=[1,0,0,-1,-s,c+o],this.#c=a,this.#s=o,e.#k(),r.style.setProperty(`--min-font-size`,e.#S),Fe(r,i),this.#e.promise.finally(()=>{e.#C.delete(this),this.#o=null,this.#p=null}).catch(()=>{})}static get fontFamilyMap(){let{isWindows:e,isFirefox:t}=F.platform;return M(this,`fontFamilyMap`,new Map([[`sans-serif`,`${e&&t?`Calibri, `:``}sans-serif`],[`monospace`,`${e&&t?`Lucida Console, `:``}monospace`]]))}render(){this.#i&&this.#t.append(this.#i.render());let t=()=>{this.#l.read().then(({value:e,done:n})=>{if(n){this.#e.resolve();return}this.#a??=e.lang,Object.assign(this.#p,e.styles),this.#w(e.items),t()},this.#e.reject)};return this.#l=this.#h.getReader(),e.#C.add(this),t(),this.#e.promise}update({viewport:t,onBefore:n=null}){let r=t.scale*Ie.pixelRatio,i=t.rotation;if(i!==this.#d&&(n?.(),this.#d=i,Fe(this.#u,{rotation:i})),r!==this.#f){n?.(),this.#f=r;let t={div:null,properties:null,ctx:e.#D(this.#a)};for(let e of this.#g)t.properties=this.#_.get(e),t.div=e,this.#E(t)}}cancel(){let e=new P(`TextLayer task cancelled.`);this.#l?.cancel(e).catch(()=>{}),this.#l=null,this.#e.reject(e)}get textDivs(){return this.#g}get textContentItemsStr(){return this.#m}#w(t){if(this.#n)return;this.#o.ctx??=e.#D(this.#a);let n=this.#g,r=this.#m;for(let e of t){if(n.length>Er){T(`Ignoring additional textDivs for performance reasons.`),this.#n=!0;return}if(e.str===void 0){if(e.type===`beginMarkedContentProps`||e.type===`beginMarkedContent`){let t=this.#t;this.#t=document.createElement(`span`),this.#t.classList.add(`markedContent`),e.id&&this.#t.setAttribute(`id`,e.id),e.tag===`Artifact`&&(this.#t.ariaHidden=!0),t.append(this.#t)}else e.type===`endMarkedContent`&&(this.#t=this.#t.parentNode);continue}r.push(e.str),this.#T(e)}}#T(t){let n=document.createElement(`span`),r={angle:0,canvasWidth:0,hasText:t.str!==``,hasEOL:t.hasEOL,fontSize:0};this.#g.push(n);let i=I.transform(this.#v,t.transform),a=Math.atan2(i[1],i[0]),o=this.#p[t.fontName];o.vertical&&(a+=Math.PI/2);let s=this.#r&&o.fontSubstitution||o.fontFamily;s=e.fontFamilyMap.get(s)||s;let c=Math.hypot(i[2],i[3]),l=c*e.#A(s,o,this.#a),u,d;a===0?(u=i[4],d=i[5]-l):(u=i[4]+l*Math.sin(a),d=i[5]-l*Math.cos(a));let f=n.style;f.left=`${(100*u/this.#c).toFixed(2)}%`,f.top=`${(100*d/this.#s).toFixed(2)}%`,f.setProperty(`--font-height`,`${c.toFixed(2)}px`),f.fontFamily=s,r.fontSize=c,n.setAttribute(`role`,`presentation`),n.textContent=t.str,n.dir=t.dir,this.#r&&(n.dataset.fontName=o.fontSubstitutionLoadedName||t.fontName),a!==0&&(r.angle=180/Math.PI*a);let p=!1;if(t.str.length>1)p=!0;else if(t.str!==` `&&t.transform[0]!==t.transform[3]){let e=Math.abs(t.transform[0]),n=Math.abs(t.transform[3]);e!==n&&Math.max(e,n)/Math.min(e,n)>1.5&&(p=!0)}if(p&&(r.canvasWidth=o.vertical?t.height:t.width),this.#_.set(n,r),this.#o.div=n,this.#o.properties=r,this.#E(this.#o),r.hasText&&this.#t.append(n),r.hasEOL){let e=document.createElement(`br`);e.setAttribute(`role`,`presentation`),this.#t.append(e)}}#E(t){let{div:n,properties:r,ctx:i}=t,{style:a}=n;if(r.canvasWidth!==0&&r.hasText){let{fontFamily:t}=a,{canvasWidth:o,fontSize:s}=r;e.#O(i,s*this.#f,t);let{width:c}=i.measureText(n.textContent);c>0&&a.setProperty(`--scale-x`,o*this.#f/c)}r.angle!==0&&a.setProperty(`--rotate`,`${r.angle}deg`)}static cleanup(){if(!(this.#C.size>0)){this.#y.clear();for(let{canvas:e}of this.#b.values())e.remove();this.#b.clear()}}static#D(e=null){let t=this.#b.get(e||=``);if(!t){let n=document.createElement(`canvas`);n.style.cssText=`position:absolute;top:0;left:0;width:0;height:0;display:none;letter-spacing:normal;word-spacing:normal`,n.lang=e,document.body.append(n),t=n.getContext(`2d`,{alpha:!1,willReadFrequently:!0}),this.#b.set(e,t),this.#x.set(t,{size:0,family:``})}return t}static#O(e,t,n){let r=this.#x.get(e);(t!==r.size||n!==r.family)&&(e.font=`${t}px ${n}`,r.size=t,r.family=n)}static#k(){if(this.#S!==null)return;let e=document.createElement(`div`);e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize=`1px`,e.style.position=`absolute`,e.textContent=`X`,document.body.append(e),this.#S=e.getBoundingClientRect().height,e.remove()}static#A(e,t,n){let r=this.#y.get(e);if(r)return r;let i=this.#D(n);i.canvas.width=i.canvas.height=Dr,this.#O(i,Dr,e);let a=i.measureText(``),o=a.fontBoundingBoxAscent,s=Math.abs(a.fontBoundingBoxDescent);i.canvas.width=i.canvas.height=0;let c=.8;return o?c=o/(o+s):(F.platform.isFirefox&&T("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),t.ascent?c=t.ascent:t.descent&&(c=1+t.descent)),this.#y.set(e,c),c}},kr=100;function Ar(e={}){let n=new jr,{docId:r}=n,i=e.url?Lt(e.url):null,a=e.data?Rt(e.data):null,o=e.httpHeaders||null,s=e.withCredentials===!0,c=e.password??null,l=e.range instanceof Mr?e.range:null,u=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:2**16,d=e.worker instanceof Fr?e.worker:null,f=e.verbosity,p=typeof e.docBaseUrl==`string`&&!Te(e.docBaseUrl)?e.docBaseUrl:null,m=zt(e.cMapUrl),h=e.cMapPacked!==!1,g=zt(e.iccUrl),_=zt(e.standardFontDataUrl),v=zt(e.wasmUrl),y=e.stopAtErrors!==!0,b=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,x=typeof e.isOffscreenCanvasSupported==`boolean`?e.isOffscreenCanvasSupported:!t,C=typeof e.isImageDecoderSupported==`boolean`?e.isImageDecoderSupported:!t,w=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,T=typeof e.disableFontFace==`boolean`?e.disableFontFace:t,E=e.fontExtraProperties===!0,D=e.enableXfa===!0,O=e.ownerDocument||globalThis.document,k=e.disableRange===!0,A=e.disableStream===!0,j=e.disableAutoFetch===!0,M=e.pdfBug===!0,N=e.CanvasFactory||(t?tn:Yt),ee=e.FilterFactory||(t?en:Zt),te=e.BinaryDataFactory||(t?nn:qt),ne=e.enableHWA===!0,re=e.enableWebGPU===!0?cn():Promise.resolve(!1),ie=e.useWasm!==!1,P=e.pagesMapper||new Sr,ae=typeof e.useSystemFonts==`boolean`?e.useSystemFonts:!t&&!T,oe=typeof e.useWorkerFetch==`boolean`?e.useWorkerFetch:!!(te===qt&&m&&h&&_&&v&&Ae(m,document.baseURI)&&Ae(_,document.baseURI)&&Ae(v,document.baseURI));S(f);let F={canvasFactory:new N({ownerDocument:O,enableHWA:ne}),filterFactory:new ee({docId:r,ownerDocument:O}),binaryDataFactory:oe?null:new te({cMapUrl:m,standardFontDataUrl:_,wasmUrl:v})};d||(d=Fr.create({verbosity:f,port:_r.workerPort}),n._worker=d);let I={docId:r,apiVersion:`6.2.108`,data:a,password:c,disableAutoFetch:j,rangeChunkSize:u,docBaseUrl:p,enableXfa:D,evaluatorOptions:{maxImageSize:b,disableFontFace:T,ignoreErrors:y,isOffscreenCanvasSupported:x,isImageDecoderSupported:C,canvasMaxAreaInBytes:w,fontExtraProperties:E,useSystemFonts:ae,useWasm:ie,useWorkerFetch:oe,cMapUrl:m,cMapPacked:h,iccUrl:g,standardFontDataUrl:_,wasmUrl:v,hasGPU:!1}},se={ownerDocument:O,pdfBug:M,styleElement:null,enableHWA:ne,loadingParams:{disableAutoFetch:j,enableXfa:D}};return Promise.all([d.promise,re]).then(function([,e]){if(d.destroyed)throw Error(`Worker was destroyed`);I.evaluatorOptions.hasGPU=e;let t=d.messageHandler.sendWithPromise(`GetDocRequest`,I,a?[a.buffer]:null),c;if(!a){if(l)c=new rr({pdfDataRangeTransport:l,disableRange:k,disableStream:A});else if(i)c=new(gr(i))({url:i,httpHeaders:o,withCredentials:s,rangeChunkSize:u,disableRange:k,disableStream:A});else throw Error("getDocument - expected either `data`, `range`, or `url` parameter.")}return t.then(e=>{if(d.destroyed)throw Error(`Worker was destroyed`);let t=new Gt(r,e,d.port),i=new Ir(t,n,c,se,F,P);if(n._transport=i,n.destroyed)throw Error(`Loading aborted`);t.send(`Ready`,null)})}).catch(n._capability.reject).finally(n._setupCapability.resolve),n}var jr=class e{static#e=0;_capability=Promise.withResolvers();_setupCapability=Promise.withResolvers();_transport=null;_worker=null;docId=`d${e.#e++}`;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0,this._capability.promise.catch(()=>{});try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._setupCapability.promise,await this._transport?.destroy()}catch(e){throw this._worker?.port&&delete this._worker._pendingDestroy,e}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}},Mr=class{#e=Promise.withResolvers();#t=null;constructor(e,t,n=!1,r=null){this.length=e,this.initialData=t,this.progressiveDone=n,this.contentDispositionFilename=r}onDataRange(e,t){this.#t({type:`range`,begin:e,chunk:t})}onDataProgressiveRead(e){this.#e.promise.then(()=>{this.#t({type:`progressiveRead`,chunk:e})})}onDataProgressiveDone(){this.#e.promise.then(()=>{this.#t({type:`progressiveDone`})})}transportReady(e){this.#t=e,this.#e.resolve()}requestDataRange(e,t){E(`Abstract method PDFDataRangeTransport.requestDataRange`)}abort(){}},Nr=class{constructor(e,t){this._pdfInfo=e,this._transport=t}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return M(this,`isPureXfa`,!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAttachmentContent(e){return this._transport.getAttachmentContent(e)}getAnnotationsByType(e,t){return this._transport.getAnnotationsByType(e,t)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:e=`display`}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(t)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(e){return this._transport.extractPages(e)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}getRawData(e){return this._transport.getRawData(e)}cleanup(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}getSignatures(){return this._transport.getSignatures()}getSignatureData(e){return this._transport.getSignatureData(e)}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}},Pr=class e{#e=!1;#t=null;constructor(e,t,n,r,i=!1){this._pageIndex=e,this._pageInfo=t,this._transport=n,this._stats=i?new ke:null,this._pdfBug=i,this.commonObjs=n.commonObjs,this.objs=new Tr,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,this.#t=r,this.imageCoordinates=null}clone(t){let n=new e(t,this._pageInfo,this._transport,this.#t,this._pdfBug);return n.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(n),n}get pageNumber(){return this._pageIndex+1}set pageNumber(e){this._pageIndex=e-1,this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:e,rotation:t=this.rotate,offsetX:n=0,offsetY:r=0,dontFlip:i=!1}={}){return new _e({viewBox:this.view,userUnit:this.userUnit,scale:e,rotation:t,offsetX:n,offsetY:r,dontFlip:i})}getAnnotations({intent:e=`display`}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,t)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return M(this,`isPureXfa`,!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:e,canvas:t=e.canvas,viewport:n,intent:r=`display`,annotationMode:i=s.ENABLE,transform:a=null,background:c=null,optionalContentConfigPromise:l=null,annotationCanvasMap:u=null,pageColors:d=null,printAnnotationStorage:f=null,isEditing:p=!1,recordImages:m=!1,recordOperations:h=!1,operationsFilter:g=null}){this._stats?.time(`Overall`);let _=this._transport.getRenderingIntent(r,i,f,p),{renderingIntent:v,cacheKey:y}=_;this.#e=!1,l||=this._transport.getOptionalContentConfig(v);let b=this._intentStates.getOrInsertComputed(y,he);b.streamReaderCancelTimeout&&=(clearTimeout(b.streamReaderCancelTimeout),null);let x=!!(v&o.PRINT);b.displayReadyCapability||(b.displayReadyCapability=Promise.withResolvers(),b.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time(`Page Request`),this._pumpOperatorList(_));let S=!!(this._pdfBug&&globalThis.StepperManager?.enabled),C=!!t&&!this.recordedBBoxes&&(h||S),w=!!t&&!this.imageCoordinates&&m,T=e=>{if(b.renderTasks.delete(O),C){let e=O.gfx?.dependencyTracker.take();e&&(O.stepper?.setOperatorBBoxes(e,O.gfx.dependencyTracker.takeDebugMetadata()),h&&(this.recordedBBoxes=e))}w&&!e&&(this.imageCoordinates=O.gfx?.imagesTracker.take()),x&&(this.#e=!0),this.#n(),e?(O.capability.reject(e),this._abortOperatorList({intentState:b,reason:e instanceof Error?e:Error(e)})):O.capability.resolve(),this._stats&&(this._stats.timeEnd(`Rendering`),this._stats.timeEnd(`Overall`),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},E=null,D=null;(C||w)&&(D=new Ct(t,b.operatorList.length)),C&&(E=new wt(D,S));let O=new Rr({callback:T,params:{canvas:t,canvasContext:e,dependencyTracker:E??D,imagesTracker:w?new Et(t):null,viewport:n,transform:a,background:c},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:u,operatorList:b.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!x,pdfBug:this._pdfBug,pageColors:d,enableHWA:this._transport.enableHWA,operationsFilter:g});(b.renderTasks||=new Set).add(O);let k=O.task;return Promise.all([b.displayReadyCapability.promise,l]).then(([e,t])=>{if(this.destroyed){T();return}if(this._stats?.time(`Rendering`),!(t.renderingIntent&v))throw Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");O.initializeGraphics({transparency:e,optionalContentConfig:t}),O.operatorListChanged()}).catch(T),k}getOperatorList({intent:e=`display`,annotationMode:t=s.ENABLE,printAnnotationStorage:n=null,isEditing:r=!1}={}){function i(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(c))}let a=this._transport.getRenderingIntent(e,t,n,r,!0),o=this._intentStates.getOrInsertComputed(a.cacheKey,he),c;return o.opListReadCapability||(c=Object.create(null),c.operatorListChanged=i,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(c),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time(`Page Request`),this._pumpOperatorList(a)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:t=!1}={}){return this._transport.messageHandler.sendWithStream(`GetTextContent`,{pageId:this.#t.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:t===!0},{highWaterMark:100,size(e){return e.items.length}})}async getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then(e=>ve.textContent(e));let t=this.streamTextContent(e),n={items:[],styles:Object.create(null),lang:null};for await(let e of t)n.lang??=e.lang,Object.assign(n.styles,e.styles),n.items.push(...e.items);return n}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let e=[];for(let t of this._intentStates.values())if(this._abortOperatorList({intentState:t,reason:Error(`Page was destroyed.`),force:!0}),!t.opListReadCapability)for(let n of t.renderTasks)e.push(n.completed),n.cancel();return this.objs.clear(),this.#e=!1,Promise.all(e)}cleanup(e=!1){this.#e=!0;let t=this.#n();return e&&t&&(this._stats&&=new ke),t}#n(){if(!this.#e||this.destroyed)return!1;for(let{renderTasks:e,operatorList:t}of this._intentStates.values())if(e.size>0||!t.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}_startRenderPage(e,t){let n=this._intentStates.get(t);n&&(this._stats?.timeEnd(`Page Request`),n.displayReadyCapability?.resolve(e))}_renderPageChunk(e,t){for(let n=0,r=e.length;n{o.read().then(({value:e,done:t})=>{if(t){s.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(e,s),c())},e=>{if(s.streamReader=null,!this._transport.destroyed){if(s.operatorList){s.operatorList.lastChunk=!0;for(let e of s.renderTasks)e.operatorListChanged();this.#n()}if(s.displayReadyCapability)s.displayReadyCapability.reject(e);else if(s.opListReadCapability)s.opListReadCapability.reject(e);else throw e}})};c()}_abortOperatorList({intentState:e,reason:t,force:n=!1}){if(e.streamReader){if(e.streamReaderCancelTimeout&&=(clearTimeout(e.streamReaderCancelTimeout),null),!n){if(e.renderTasks.size>0)return;if(t instanceof we){let n=kr;t.extraDelay>0&&t.extraDelay<1e3&&(n+=t.extraDelay),e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:t,force:!0})},n);return}}if(e.streamReader.cancel(new P(t.message)).catch(()=>{}),e.streamReader=null,!this._transport.destroyed){for(let[t,n]of this._intentStates)if(n===e){this._intentStates.delete(t);break}this.cleanup()}}}get stats(){return this._stats}},Fr=class n{#e=Promise.withResolvers();#t=null;#n=null;#r=null;static#i=0;static#a=!1;static#o=new WeakMap;static{t&&(this.#a=!0,_r.workerSrc||=`./pdf.worker.mjs`),this._isSameOrigin=(e,t)=>{let n=URL.parse(e);if(!n?.origin||n.origin===`null`)return!1;let r=new URL(t,n);return n.origin===r.origin},this._createCDNWrapper=e=>{let t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:`text/javascript`}))}}constructor({name:e=null,port:t=null,verbosity:r=C()}={}){if(this.name=e,this.destroyed=!1,this.verbosity=r,t){if(n.#o.has(t))throw Error(`Cannot use more than one PDFWorker per port.`);n.#o.set(t,this),this.#c(t)}else this.#l()}get promise(){return this.#e.promise}#s(){this.#e.resolve(),this.#t.send(`configure`,{verbosity:this.verbosity})}get port(){return this.#n}get messageHandler(){return this.#t}#c(e){this.#n=e,this.#t=new Gt(`main`,`worker`,e),this.#t.on(`ready`,()=>{}),this.#s()}#l(){if(n.#a||n.#d){this.#u();return}let{workerSrc:e}=n;try{n._isSameOrigin(window.location,e)||(e=n._createCDNWrapper(new URL(e,window.location).href));let t=new Worker(e,{type:`module`}),r=new Gt(`main`,`worker`,t),i=()=>{a.abort(),r.destroy(),t.terminate(),this.destroyed?this.#e.reject(Error(`Worker was destroyed`)):this.#u()},a=new AbortController;t.addEventListener(`error`,()=>{this.#r||i()},{signal:a.signal}),r.on(`test`,e=>{if(a.abort(),this.destroyed||!e){i();return}this.#t=r,this.#n=t,this.#r=t,this.#s()}),r.on(`ready`,e=>{if(a.abort(),this.destroyed){i();return}try{o()}catch{this.#u()}});let o=()=>{let e=new Uint8Array;r.send(`test`,e,[e.buffer])};o();return}catch{w(`The worker has been disabled.`)}this.#u()}#u(){n.#a||=(T(`Setting up fake worker.`),!0),n._setupFakeWorkerGlobal.then(e=>{if(this.destroyed){this.#e.reject(Error(`Worker was destroyed`));return}let t=new Ht;this.#n=t;let r=`fake${n.#i++}`,i=new Gt(r+`_worker`,r,t);e.setup(i,t),this.#t=new Gt(r,r+`_worker`,t),this.#s()}).catch(e=>{this.#e.reject(Error(`Setting up fake worker failed: "${e.message}".`))})}destroy(){this.destroyed=!0,this.#r?.terminate(),this.#r=null,n.#o.delete(this.#n),this.#n=null,this.#t?.destroy(),this.#t=null}static create(e){let t=this.#o.get(e?.port);if(t){if(t._pendingDestroy)throw Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return t}return new n(e)}static get workerSrc(){if(_r.workerSrc)return _r.workerSrc;throw Error(`No "GlobalWorkerOptions.workerSrc" specified.`)}static get#d(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return M(this,`_setupFakeWorkerGlobal`,(async()=>this.#d?this.#d:(await e(()=>import(this.workerSrc),[],import.meta.url)).WorkerMessageHandler)())}},Ir=class{downloadInfoCapability=Promise.withResolvers();#e=null;#t=new Map;#n=null;#r=new Map;#i=new Map;#a=new Map;#o=null;constructor(e,t,n,r,i,a){this.messageHandler=e,this.loadingTask=t,this.#n=n,this.commonObjs=new Tr,this.fontLoader=new Dt({ownerDocument:r.ownerDocument,styleElement:r.styleElement}),this.enableHWA=r.enableHWA,this.loadingParams=r.loadingParams,this._params=r,this.canvasFactory=i.canvasFactory,this.filterFactory=i.filterFactory,this.binaryDataFactory=i.binaryDataFactory,this.pagesMapper=a,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(e){let{_pageIndex:t}=e;this.#r.set(t,e),this.#i.set(t,Promise.resolve(e))}#s(e,t=null){return this.#t.getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,t))}#c({loaded:e,total:t}){this.loadingTask.onProgress?.({loaded:e,total:t,percent:t?L(Math.round(e/t*100),0,100):NaN})}get annotationStorage(){return M(this,`annotationStorage`,new pt)}getRenderingIntent(e,t=s.ENABLE,n=null,r=!1,i=!1){let a=o.DISPLAY,c=ft;switch(e){case`any`:a=o.ANY;break;case`display`:break;case`print`:a=o.PRINT;break;default:T(`getRenderingIntent - invalid intent: ${e}`)}let l=a&o.PRINT&&n instanceof mt?n:this.annotationStorage;switch(t){case s.DISABLE:a+=o.ANNOTATIONS_DISABLE;break;case s.ENABLE:break;case s.ENABLE_FORMS:a+=o.ANNOTATIONS_FORMS;break;case s.ENABLE_STORAGE:a+=o.ANNOTATIONS_STORAGE,c=l.serializable;break;default:T(`getRenderingIntent - invalid annotationMode: ${t}`)}r&&(a+=o.IS_EDITING),i&&(a+=o.OPLIST);let{ids:u,hash:d}=l.modifiedIds,f=[a,c.hash,d];return{renderingIntent:a,cacheKey:f.join(`_`),annotationStorageSerializable:c,modifiedIds:u}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#o?.reject(Error(`Worker was destroyed during onPassword callback`));let e=[];for(let t of this.#r.values())e.push(t._destroy());this.#r.clear(),this.#i.clear(),this.#a.clear(),Object.hasOwn(this,`annotationStorage`)&&this.annotationStorage.resetModified();let t=this.messageHandler.sendWithPromise(`Terminate`,null);return e.push(t),Promise.all(e).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),Or.cleanup(),this.#n?.cancelAllRequests(new P(`Worker was terminated.`)),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:e,loadingTask:t}=this;e.on(`GetReader`,(e,t)=>{D(this.#n,"GetReader - no `BasePDFStream` instance available."),this.#e=this.#n.getFullReader(),this.#e.onProgress=e=>this.#c(e),t.onPull=()=>{this.#e.read().then(function({value:e,done:n}){if(n){t.close();return}D(e instanceof ArrayBuffer,`GetReader - expected an ArrayBuffer.`),t.enqueue(new Uint8Array(e),1,[e])}).catch(e=>{t.error(e)})},t.onCancel=e=>{this.#e.cancel(e),t.ready.catch(e=>{if(!this.destroyed)throw e})}}),e.on(`ReaderHeadersReady`,async e=>{await this.#e.headersReady;let{isStreamingSupported:t,isRangeSupported:n,contentLength:r}=this.#e;return t&&n&&(this.#e.onProgress=null),{isStreamingSupported:t,isRangeSupported:n,contentLength:r}}),e.on(`GetRangeReader`,(e,t)=>{D(this.#n,"GetRangeReader - no `BasePDFStream` instance available.");let n=this.#n.getRangeReader(e.begin,e.end);if(!n){t.close();return}t.onPull=()=>{n.read().then(function({value:e,done:n}){if(n){t.close();return}D(e instanceof ArrayBuffer,`GetRangeReader - expected an ArrayBuffer.`),t.enqueue(new Uint8Array(e),1,[e])}).catch(e=>{t.error(e)})},t.onCancel=e=>{n.cancel(e),t.ready.catch(e=>{if(!this.destroyed)throw e})}}),e.on(`GetDoc`,({pdfInfo:e})=>{this.pagesMapper.pagesNumber=e.numPages,this._numPages=e.numPages,this._htmlForXfa=e.htmlForXfa,delete e.htmlForXfa,t._capability.resolve(new Nr(e,this))}),e.on(`DocException`,e=>{t._capability.reject(J(e))}),e.on(`PasswordRequest`,e=>{this.#o=Promise.withResolvers();try{if(!t.onPassword)throw J(e);t.onPassword(e=>{e instanceof Error?this.#o.reject(e):this.#o.resolve({password:e})},e.code)}catch(e){this.#o.reject(e)}return this.#o.promise}),e.on(`DataLoaded`,e=>{this.#c({loaded:e.length,total:e.length}),this.downloadInfoCapability.resolve(e)}),e.on(`StartRenderPage`,e=>{this.destroyed||this.#r.get(e.pageIndex)._startRenderPage(e.transparency,e.cacheKey)}),e.on(`commonobj`,([t,n,r])=>{if(this.destroyed||this.commonObjs.has(t))return null;switch(n){case`Font`:if(`error`in r){let e=r.error;T(`Error during font loading: ${e}`),this.commonObjs.resolve(t,e);break}let i=new Ot(new Pt(r),this._params.pdfBug&&globalThis.FontInspector?.enabled?(e,t)=>globalThis.FontInspector.fontAdded(e,t):null,r.charProcOperatorList,r.extra);this.fontLoader.bind(i).catch(()=>e.sendWithPromise(`FontFallback`,{id:t})).finally(()=>{i.fontExtraProperties||i.clearData(),this.commonObjs.resolve(t,i)});break;case`CopyLocalImage`:let{imageRef:a}=r;D(a,`The imageRef must be defined.`);for(let e of this.#r.values())for(let[,n]of e.objs){if(n?.ref!==a)continue;if(!n.dataLen)return null;let e=structuredClone(n);return this.commonObjs.resolve(t,e),n.dataLen}break;case`FontPath`:this.commonObjs.resolve(t,new It(r));break;case`Image`:this.commonObjs.resolve(t,r);break;case`Pattern`:let o=new Ft(r);this.commonObjs.resolve(t,o.getIR());break;default:throw Error(`Got unknown common object type ${n}`)}return null}),e.on(`obj`,([e,t,n,r])=>{if(this.destroyed)return;let i=this.#r.get(t);if(!i.objs.has(e)){if(i._intentStates.size===0){r?.bitmap?.close();return}switch(n){case`Image`:case`Pattern`:i.objs.resolve(e,r);break;default:throw Error(`Got unknown object type ${n}`)}}}),e.on(`DocProgress`,e=>{this.destroyed||this.#c(e)}),e.on(`FetchBinaryData`,async e=>{if(this.destroyed)throw Error(`Worker was destroyed.`);if(!this.binaryDataFactory)throw Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(e)})}getData(){return this.messageHandler.sendWithPromise(`GetData`,null)}saveDocument(){this.annotationStorage.size<=0&&T("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:e,transfer:t}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise(`SaveDocument`,{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:this.#e?.filename??null},t).finally(()=>{this.annotationStorage.resetModified()})}extractPages(e){let t={pageInfos:e},n,r=globalThis.ImageBitmap;if(typeof r==`function`){let t=Array.isArray(e)?e:[e];for(let e of t)e?.image instanceof r&&(n||=[]).push(e.image)}if(this.annotationStorage.size>0){let e=this.annotationStorage.serializable,{map:r}=e;e.transfer?.length&&(n?n.push(...e.transfer):n=e.transfer);let i=this.pagesMapper.getMapping();if(i){let e=new Map;for(let[t,n]of r){if(n?.pageIndex!==void 0&&n.pageIndex>=0&&n.pageIndex{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this.pagesMapper.pagesNumber)return Promise.reject(Error(`Invalid page request.`));let t=e-1,n=this.pagesMapper.getPageId(e)-1,r=this.#i.get(t);if(r)return r;let i=this.messageHandler.sendWithPromise(`GetPage`,{pageIndex:n}).then(e=>{if(this.destroyed)throw Error(`Transport destroyed`);e.refStr&&this.#a.set(e.refStr,n);let r=new Pr(t,e,this,this.pagesMapper,this._params.pdfBug);return this.#r.set(t,r),r});return this.#i.set(t,i),i}async getPageIndex(e){if(!Bt(e))throw Error(`Invalid pageIndex request.`);let t=await this.messageHandler.sendWithPromise(`GetPageIndex`,{num:e.num,gen:e.gen}),n=this.pagesMapper.getPageNumber(t+1);if(n===0)throw Error(`GetPageIndex: page has been removed.`);return n-1}getAnnotations(e,t){return this.messageHandler.sendWithPromise(`GetAnnotations`,{pageIndex:this.pagesMapper.getPageId(e+1)-1,intent:t})}getFieldObjects(){return this.#s(`GetFieldObjects`)}getSignatures(){return this.#s(`GetSignatures`)}getSignatureData(e){return this.messageHandler.sendWithPromise(`GetSignatureData`,e)}hasJSActions(){return this.#s(`HasJSActions`)}getCalculationOrderIds(){return this.messageHandler.sendWithPromise(`GetCalculationOrderIds`,null)}getDestinations(){return this.messageHandler.sendWithPromise(`GetDestinations`,null)}getDestination(e){return typeof e==`string`?this.messageHandler.sendWithPromise(`GetDestination`,{id:e}):Promise.reject(Error(`Invalid destination request.`))}getPageLabels(){return this.messageHandler.sendWithPromise(`GetPageLabels`,null)}getPageLayout(){return this.messageHandler.sendWithPromise(`GetPageLayout`,null)}getPageMode(){return this.messageHandler.sendWithPromise(`GetPageMode`,null)}getViewerPreferences(){return this.messageHandler.sendWithPromise(`GetViewerPreferences`,null)}getOpenAction(){return this.messageHandler.sendWithPromise(`GetOpenAction`,null)}getAttachments(){return this.messageHandler.sendWithPromise(`GetAttachments`,null)}getAttachmentContent(e){return this.messageHandler.sendWithPromise(`GetAttachmentContent`,e)}getAnnotationsByType(e,t){return this.messageHandler.sendWithPromise(`GetAnnotationsByType`,{types:e,pageIndexesToSkip:t})}getDocJSActions(){return this.#s(`GetDocJSActions`)}getPageJSActions(e){return this.messageHandler.sendWithPromise(`GetPageJSActions`,{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getStructTree(e){return this.messageHandler.sendWithPromise(`GetStructTree`,{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getOutline(){return this.messageHandler.sendWithPromise(`GetOutline`,null)}getOptionalContentConfig(e){return this.#s(`GetOptionalContentConfig`).then(t=>new xr(t,e))}getPermissions(){return this.messageHandler.sendWithPromise(`GetPermissions`,null)}getMetadata(){let e=`GetMetadata`;return this.#t.getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,null).then(e=>({info:e[0],metadata:e[1]?new vr(e[1]):null,contentDispositionFilename:this.#e?.filename??null,contentLength:this.#e?.contentLength??null,hasStructTree:e[2]})))}getMarkInfo(){return this.messageHandler.sendWithPromise(`GetMarkInfo`,null)}getRawData(e){return this.messageHandler.sendWithPromise(`GetRawData`,e)}async startCleanup(e=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise(`Cleanup`,null);for(let e of this.#r.values())if(!e.cleanup())throw Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),Or.cleanup()}}cachedPageNumber(e){if(!Bt(e))return null;let t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`,n=this.#a.get(t);if(n>=0){let e=this.pagesMapper.getPageNumber(n+1);if(e!==0)return e}return null}},Lr=class{_internalRenderTask=null;onContinue=null;onError=null;constructor(e){this._internalRenderTask=e}get promise(){return this._internalRenderTask.capability.promise}cancel(e=0){this._internalRenderTask.cancel(null,e)}get separateAnnots(){let{separateAnnots:e}=this._internalRenderTask.operatorList;if(!e)return!1;let{annotationCanvasMap:t}=this._internalRenderTask;return e.form||e.canvas&&t?.size>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}},Rr=class e{#e=null;static#t=new WeakSet;constructor({callback:e,params:t,objs:n,commonObjs:r,annotationCanvasMap:i,operatorList:a,pageIndex:o,canvasFactory:s,filterFactory:c,useRequestAnimationFrame:l=!1,pdfBug:u=!1,pageColors:d=null,enableHWA:f=!1,operationsFilter:p=null}){this.callback=e,this.params=t,this.objs=n,this.commonObjs=r,this.annotationCanvasMap=i,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=o,this.canvasFactory=s,this.filterFactory=c,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=l===!0&&typeof window<`u`,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new Lr(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=t.canvas,this._canvasContext=t.canvas?null:t.canvasContext,this._enableHWA=f,this._dependencyTracker=t.dependencyTracker,this._imagesTracker=t.imagesTracker,this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:n}){if(this.cancelled)return;if(this._canvas){if(e.#t.has(this._canvas))throw Error(`Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.`);e.#t.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{viewport:r,transform:i,background:a,dependencyTracker:o,imagesTracker:s}=this.params,c=this._canvasContext||this._canvas.getContext(`2d`,{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new Rn(c,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:n},this.annotationCanvasMap,this.pageColors,o,s),this.gfx.beginDrawing({transform:i,viewport:r,transparency:t,background:a}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,n=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#e&&=(window.cancelAnimationFrame(this.#e),null),e.#t.delete(this._canvas),t||=new we(`Rendering cancelled, page ${this._pageIndex+1}`,n),this.callback(t),this.task.onError?.(t)}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#e=window.requestAnimationFrame(()=>{this.#e=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),e.#t.delete(this._canvas),this.callback())))}},zr=`6.2.108`,Br=`0365cbde0`,Vr=class e{#e=null;#t=null;#n;#r=null;#i=!1;#a=!1;#o=null;#s;#c=null;#l=null;static#u=null;static get _keyboardManager(){return M(this,`_keyboardManager`,new nt([[[`Escape`],e.prototype._hideDropdownFromKeyboard],[[`Space`],e.prototype._colorSelectFromKeyboard],[[`ArrowDown`,`ArrowRight`],e.prototype._moveToNext],[[`ArrowUp`,`ArrowLeft`],e.prototype._moveToPrevious],[[`Home`],e.prototype._moveToBeginning],[[`End`],e.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:n=null}){t?(this.#a=!1,this.#o=t):this.#a=!0,this.#l=t?._uiManager||n,this.#s=this.#l._eventBus,this.#n=t?.color?.toUpperCase()||this.#l?.highlightColors.values().next().value||`#FFFF98`,e.#u||=Object.freeze({blue:`pdfjs-editor-colorpicker-blue`,green:`pdfjs-editor-colorpicker-green`,pink:`pdfjs-editor-colorpicker-pink`,red:`pdfjs-editor-colorpicker-red`,yellow:`pdfjs-editor-colorpicker-yellow`})}renderButton(){let e=this.#e=document.createElement(`button`);e.className=`colorPicker`,e.tabIndex=`0`,e.setAttribute(`data-l10n-id`,`pdfjs-editor-colorpicker-button`),e.ariaHasPopup=`true`,this.#o&&(e.ariaControls=`${this.#o.id}_colorpicker_dropdown`);let t=this.#l._signal;e.addEventListener(`click`,this.#m.bind(this),{signal:t}),e.addEventListener(`keydown`,this.#p.bind(this),{signal:t});let n=this.#t=document.createElement(`span`);return n.className=`swatch`,n.ariaHidden=`true`,n.style.backgroundColor=this.#n,e.append(n),e}renderMainDropdown(){let e=this.#r=this.#d();return e.ariaOrientation=`horizontal`,e.ariaLabelledBy=`highlightColorPickerLabel`,e}#d(){let t=document.createElement(`div`),n=this.#l._signal;t.addEventListener(`contextmenu`,R,{signal:n}),t.className=`dropdown`,t.role=`listbox`,t.ariaMultiSelectable=`false`,t.ariaOrientation=`vertical`,t.setAttribute(`data-l10n-id`,`pdfjs-editor-colorpicker-dropdown`),this.#o&&(t.id=`${this.#o.id}_colorpicker_dropdown`);for(let[r,i]of this.#l.highlightColors){let a=document.createElement(`button`);a.tabIndex=`0`,a.role=`option`,a.setAttribute(`data-color`,i),a.title=r,a.setAttribute(`data-l10n-id`,e.#u[r]);let o=document.createElement(`span`);a.append(o),o.className=`swatch`,o.style.backgroundColor=i,a.ariaSelected=i===this.#n,a.addEventListener(`click`,this.#f.bind(this,i),{signal:n}),t.append(a)}return t.addEventListener(`keydown`,this.#p.bind(this),{signal:n}),t}#f(e,t){t.stopPropagation(),this.#s.dispatch(`switchannotationeditorparams`,{source:this,type:d.HIGHLIGHT_COLOR,value:e}),this.updateColor(e)}_colorSelectFromKeyboard(e){if(e.target===this.#e){this.#m(e);return}let t=e.target.getAttribute(`data-color`);t&&this.#f(t,e)}_moveToNext(e){if(!this.#g){this.#m(e);return}if(e.target===this.#e){this.#r.firstElementChild?.focus();return}e.target.nextSibling?.focus()}_moveToPrevious(e){if(e.target===this.#r?.firstElementChild||e.target===this.#e){this.#g&&this._hideDropdownFromKeyboard();return}this.#g||this.#m(e),e.target.previousSibling?.focus()}_moveToBeginning(e){if(!this.#g){this.#m(e);return}this.#r.firstElementChild?.focus()}_moveToEnd(e){if(!this.#g){this.#m(e);return}this.#r.lastElementChild?.focus()}#p(t){e._keyboardManager.exec(this,t)}#m(e){if(this.#g){this.hideDropdown();return}if(this.#i=e.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener(`pointerdown`,this.#h.bind(this),{signal:this.#l.combinedSignal(this.#c)})),this.#e.ariaExpanded=`true`,this.#r){this.#r.classList.remove(`hidden`);return}let t=this.#r=this.#d();this.#e.append(t)}#h(e){this.#r?.contains(e.target)||this.hideDropdown()}hideDropdown(){this.#r?.classList.add(`hidden`),this.#e.ariaExpanded=`false`,this.#c?.abort(),this.#c=null}get#g(){return this.#r&&!this.#r.classList.contains(`hidden`)}_hideDropdownFromKeyboard(){if(!this.#a){if(!this.#g){this.#o?.unselect();return}this.hideDropdown(),this.#e.focus({preventScroll:!0,focusVisible:this.#i})}}updateColor(e){if(this.#t&&(this.#t.style.backgroundColor=e),!this.#r)return;let t=this.#l.highlightColors.values();for(let n of this.#r.children)n.ariaSelected=t.next().value===e.toUpperCase()}destroy(){this.#e?.remove(),this.#e=null,this.#t=null,this.#r?.remove(),this.#r=null}},Hr=class e{#e=null;#t=!1;#n=null;#r=null;static#i=null;constructor(t){this.#n=t,this.#r=t._uiManager,e.#i||=Object.freeze({freetext:`pdfjs-editor-color-picker-free-text-input`,ink:`pdfjs-editor-color-picker-ink-input`})}renderButton(){if(this.#e)return this.#e;let{editorType:t,colorType:n,colorAndOpacityType:r,opacityType:i,color:a,opacity:o}=this.#n,s=this.#t=F.isAlphaColorInputSupported&&i!==void 0,c=this.#e=document.createElement(`input`);if(c.type=`color`,s){c.setAttribute(`alpha`,``);let e=I.hexNums[Math.round((o??1)*255)];c.value=(a||`#000000`)+e}else c.value=a||`#000000`;return c.className=`basicColorPicker`,c.tabIndex=0,c.setAttribute(`data-l10n-id`,e.#i[t]),c.addEventListener(`input`,()=>{if(s){let e=Me(c.value);if(!e)return;let[t,a,o,s]=e,l=I.makeHexColor(t,a,o);r===void 0?(this.#r.updateParams(n,l),this.#r.updateParams(i,s)):this.#r.updateParams(r,{color:l,opacity:s})}else this.#r.updateParams(n,c.value)},{signal:this.#r._signal}),c}update(e){if(this.#e){if(this.#t){let t=I.hexNums[Math.round(this.#n.opacity*255)];this.#e.value=e+t}else this.#e.value=e}}updateOpacity(e){if(!this.#e||!this.#t)return;let t=I.hexNums[Math.round(e*255)];this.#e.value=this.#n.color+t}destroy(){this.#e?.remove(),this.#e=null}hideDropdown(){}};function Ur(e){return Math.floor(L(e,0,1)*255).toString(16).padStart(2,`0`)}function Wr(e){return L(e,0,1)*255}var Gr=class{static CMYK_G([e,t,n,r]){return[`G`,1-Math.min(1,.3*e+.59*n+.11*t+r)]}static G_CMYK([e]){return[`CMYK`,0,0,0,1-e]}static G_RGB([e]){return[`RGB`,e,e,e]}static G_rgb([e]){return e=Wr(e),[e,e,e]}static G_HTML([e]){let t=Ur(e);return`#${t}${t}${t}`}static RGB_G([e,t,n]){return[`G`,.3*e+.59*t+.11*n]}static RGB_rgb(e){return e.map(Wr)}static RGB_HTML(e){return`#${e.map(Ur).join(``)}`}static T_HTML(){return`#00000000`}static T_rgb(){return[null]}static CMYK_RGB([e,t,n,r]){return[`RGB`,1-Math.min(1,e+r),1-Math.min(1,n+r),1-Math.min(1,t+r)]}static CMYK_rgb([e,t,n,r]){return[Wr(1-Math.min(1,e+r)),Wr(1-Math.min(1,n+r)),Wr(1-Math.min(1,t+r))]}static CMYK_HTML(e){let t=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(t)}static RGB_CMYK([e,t,n]){let r=1-e,i=1-t,a=1-n;return[`CMYK`,r,i,a,Math.min(r,i,a)]}},Kr=class{create(e,t,n=!1){if(e<=0||t<=0)throw Error(`Invalid SVG dimensions`);let r=this._createSVG(`svg:svg`);return r.setAttribute(`version`,`1.1`),n||(r.setAttribute(`width`,`${e}px`),r.setAttribute(`height`,`${t}px`)),r.setAttribute(`preserveAspectRatio`,`none`),r.setAttribute(`viewBox`,`0 0 ${e} ${t}`),r}createElement(e){if(typeof e!=`string`)throw Error(`Invalid SVG element type`);return this._createSVG(e)}_createSVG(e){E("Abstract method `_createSVG` called.")}},qr=class extends Kr{_createSVG(e){return document.createElementNS(a,e)}},Jr=9,Yr=new WeakSet,Xr=new Date().getTimezoneOffset()*60*1e3,Zr=class{static create(e){switch(e.data.annotationType){case h.LINK:return new $r(e);case h.TEXT:return new ei(e);case h.WIDGET:switch(e.data.fieldType){case`Tx`:return new ni(e);case`Btn`:return e.data.radioButton?new ai(e):e.data.checkBox?new ii(e):new oi(e);case`Ch`:return new si(e);case`Sig`:return new ri(e)}return new ti(e);case h.POPUP:return new ci(e);case h.FREETEXT:return new ui(e);case h.LINE:return new di(e);case h.SQUARE:return new fi(e);case h.CIRCLE:return new pi(e);case h.POLYLINE:return new mi(e);case h.CARET:return new gi(e);case h.INK:return new _i(e);case h.POLYGON:return new hi(e);case h.HIGHLIGHT:return new vi(e);case h.UNDERLINE:return new yi(e);case h.SQUIGGLY:return new bi(e);case h.STRIKEOUT:return new xi(e);case h.STAMP:return new Si(e);case h.FILEATTACHMENT:return new Ci(e);case h.RICHMEDIA:case h.SCREEN:case h.SOUND:return new wi(e);default:return new Q(e)}}},Q=class e{#e=null;#t=!1;#n=null;constructor(e,{isRenderable:t=!1,ignoreBorder:n=!1,createQuadrilaterals:r=!1}={}){this.isRenderable=t,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableComment=e.enableComment,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,this.hasOwnCommentButton=!1,t&&(this.contentElement=this.container=this._createContainer(n)),r&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:e,richText:t}){return!!(e?.str||t?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return e._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){let{data:e}=this,t=this.annotationStorage?.getEditor(e.id);return t?t.getData():e}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){let e=this.annotationStorage?.getEditor(this.data.id);if(e)return e.commentButtonPositionInPage;let{quadPoints:t,inkLists:n,rect:r}=this.data,i=-1/0,a=-1/0;if(t?.length>=8){for(let e=0;ea?(a=t[e+1],i=t[e+2]):t[e+1]===a&&(i=Math.max(i,t[e+2]));return[i,a]}if(n?.length>=1){for(let e of n)for(let t=0,n=e.length;ta?(a=e[t+1],i=e[t]):e[t+1]===a&&(i=Math.max(i,e[t]));if(i!==1/0)return[i,a]}return r?[r[2],r[3]]:null}_normalizePoint(e){let{page:{view:t},viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:i,pageY:a}}}=this.parent;return e[1]=t[3]-e[1]+t[1],e[0]=100*(e[0]-i)/n,e[1]=100*(e[1]-a)/r,e}get commentText(){let{data:e}=this;return this.annotationStorage.getRawValue(`${l}${e.id}`)?.popup?.contents||e.contentsObj?.str||``}set commentText(e){let{data:t}=this,n={deleted:!e,contents:e||``};this.annotationStorage.updateEditor(t.id,{popup:n})||this.annotationStorage.setValue(`${l}${t.id}`,{id:t.id,annotationType:t.annotationType,page:this.parent.page,popup:n,popupRef:t.popupRef,modificationDate:new Date}),e||this.removePopup()}removePopup(){(this.#n?.popup||this.popup)?.remove(),this.#n=this.popup=null}updateEdited(e){if(!this.container)return;e.rect&&(this.#e||={rect:this.data.rect.slice(0)});let{rect:t,popup:n}=e;t&&this.#r(t);let r=this.#n?.popup||this.popup;!r&&n?.text&&(this._createPopup(n),r=this.#n.popup),r&&(r.updateEdited(e),n?.deleted&&(r.remove(),this.#n=null,this.popup=null))}resetEdited(){this.#e&&=(this.#r(this.#e.rect),this.#n?.popup.resetEdited(),null)}#r(e){let{container:{style:t},data:{rect:n,rotation:r},parent:{viewport:{rawDims:{pageWidth:i,pageHeight:a,pageX:o,pageY:s}}}}=this;n?.splice(0,4,...e),t.left=`${100*(e[0]-o)/i}%`,t.top=`${100*(a-e[3]+s)/a}%`,r===0?(t.width=`${100*(e[2]-e[0])/i}%`,t.height=`${100*(e[3]-e[1])/a}%`):this.setRotation(r)}_createContainer(e){let{data:t,parent:{page:n,viewport:r}}=this,i=document.createElement(`section`);i.setAttribute(`data-annotation-id`,t.id),!(this instanceof ti)&&!(this instanceof $r)&&!(this instanceof wi)&&(i.tabIndex=0);let{style:a}=i;if(a.zIndex=this.parent.zIndex,this.parent.zIndex+=2,t.alternativeText&&(i.title=t.alternativeText),t.noRotate&&i.classList.add(`norotate`),!t.rect||this instanceof ci){let{rotation:e}=t;return!t.hasOwnCanvas&&e!==0&&this.setRotation(e,i),i}let{width:o,height:s}=this;if(!e&&t.borderStyle.width>0){a.borderWidth=`${t.borderStyle.width}px`;let e=t.borderStyle.horizontalCornerRadius,n=t.borderStyle.verticalCornerRadius;switch((e>0||n>0)&&(a.borderRadius=`calc(${e}px * var(--total-scale-factor)) / calc(${n}px * var(--total-scale-factor))`),t.borderStyle.style){case g.SOLID:a.borderStyle=`solid`;break;case g.DASHED:a.borderStyle=`dashed`;break;case g.BEVELED:T(`Unimplemented border style: beveled`);break;case g.INSET:T(`Unimplemented border style: inset`);break;case g.UNDERLINE:a.borderBottomStyle=`solid`}let r=t.borderColor||null;r?(this.#t=!0,a.borderColor=I.makeHexColor(...r)):a.borderWidth=0}let c=I.normalizeRect([t.rect[0],n.view[3]-t.rect[1]+n.view[1],t.rect[2],n.view[3]-t.rect[3]+n.view[1]]),{pageWidth:l,pageHeight:u,pageX:d,pageY:f}=r.rawDims;a.left=`${100*(c[0]-d)/l}%`,a.top=`${100*(c[1]-f)/u}%`;let{rotation:p}=t;return t.hasOwnCanvas||p===0?(a.width=`${100*o/l}%`,a.height=`${100*s/u}%`):this.setRotation(p,i),i}setRotation(e,t=this.container){if(!this.data.rect)return;let{pageWidth:n,pageHeight:r}=this.parent.viewport.rawDims,{width:i,height:a}=this;e%180!=0&&([i,a]=[a,i]),t.style.width=`${100*i/n}%`,t.style.height=`${100*a/r}%`,t.setAttribute(`data-main-rotation`,(360-e)%360)}get _commonActions(){let e=(e,t,n)=>{let r=n.detail[e],i=r[0],a=r.slice(1);n.target.style[t]=Gr[`${i}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[t]:Gr[`${i}_rgb`](a)})};return M(this,`_commonActions`,{display:e=>{let{display:t}=e.detail,n=t%2==1;this.container.style.visibility=n?`hidden`:`visible`,this.annotationStorage.setValue(this.data.id,{noView:n,noPrint:t===1||t===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{let{hidden:t}=e.detail;this.container.style.visibility=t?`hidden`:`visible`,this.annotationStorage.setValue(this.data.id,{noPrint:t,noView:t})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:t=>{e(`bgColor`,`backgroundColor`,t)},fillColor:t=>{e(`fillColor`,`backgroundColor`,t)},fgColor:t=>{e(`fgColor`,`color`,t)},textColor:t=>{e(`textColor`,`color`,t)},borderColor:t=>{e(`borderColor`,`borderColor`,t)},strokeColor:t=>{e(`strokeColor`,`borderColor`,t)},rotation:e=>{let t=e.detail.rotation;this.setRotation(t),this.annotationStorage.setValue(this.data.id,{rotation:t})}})}_dispatchEventFromSandbox(e,t){let n=this._commonActions;for(let r of Object.keys(t.detail))(e[r]||n[r])?.(t)}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;let t=this.annotationStorage.getRawValue(this.data.id);if(!t)return;let n=this._commonActions;for(let[r,i]of Object.entries(t)){let a=n[r];a&&(a({detail:{[r]:i},target:e}),delete t[r])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:e}=this.data;if(!e)return;let[t,n,r,i]=this.data.rect.map(e=>Math.fround(e));if(e.length===8){let[a,o,s,c]=e.subarray(2,6);if(r===a&&i===o&&t===s&&n===c)return}let{style:o}=this.container,s;if(this.#t){let{borderColor:e,borderWidth:t}=o;o.borderWidth=0,s=[`url('data:image/svg+xml;utf8,`,``,``],this.container.classList.add(`hasBorder`)}let c=r-t,l=i-n,{svgFactory:u}=this,d=u.createElement(`svg`);d.classList.add(`quadrilateralsContainer`),d.setAttribute(`width`,0),d.setAttribute(`height`,0),d.role=`none`;let f=u.createElement(`defs`);d.append(f);let p=u.createElement(`clipPath`),m=`clippath_${this.data.id}`;p.setAttribute(`id`,m),p.setAttribute(`clipPathUnits`,`objectBoundingBox`),f.append(p);for(let n=2,r=e.length;n`)}this.#t&&(s.push(`')`),o.backgroundImage=s.join(``)),this.container.append(d),this.container.style.clipPath=`url(#${m})`}_createPopup(e=null){let{data:t}=this,n,r;e?(n={str:e.text},r=e.date):(n=t.contentsObj,r=t.modificationDate),this.#n=new ci({data:{color:t.color,titleObj:t.titleObj,modificationDate:r,contentsObj:n,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#n||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#n}render(){E("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,t=null){let n=[];if(this._fieldObjects){let r=this._fieldObjects[e]||[];for(let{page:e,id:i,exportValues:a}of r){if(e===-1||i===t)continue;let r=typeof a==`string`?a:null,o=document.querySelector(`[data-element-id="${i}"]`);if(o&&!Yr.has(o)){T(`_getElementsByName - element not allowed: ${i}`);continue}n.push({id:i,exportValue:r,domElement:o})}return n}for(let r of document.getElementsByName(e)){let{exportValue:e}=r,i=r.getAttribute(`data-element-id`);i!==t&&Yr.has(r)&&n.push({id:i,exportValue:e,domElement:r})}return n}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(let t of e)t.classList.add(`highlightArea`);else e.classList.add(`highlightArea`)}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:e,data:{id:t}}=this;this.container.addEventListener(`dblclick`,()=>{this.linkService.eventBus?.dispatch(`switchannotationeditormode`,{source:this,mode:e,editId:t,mustEnterInEditMode:!0})})}updateOC(e){!this.data.oc||!e||(e.isVisible(this.data.oc)?this.show():this.hide())}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}_setBackgroundColor(e){let t=this.data.backgroundColor||null;e.style.backgroundColor=t===null?`transparent`:I.makeHexColor(...t)}},Qr=class extends Q{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.editor=e.editor}render(){return this.container.className=`editorAnnotation`,this.container}createOrUpdatePopup(){let{editor:e}=this;e.hasComment&&this._createPopup(e.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(e){this.editor.comment=e,e||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}},$r=class extends Q{constructor(e,t=null){super(e,{isRenderable:!0,ignoreBorder:!!t?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=e.data.isTooltipOnly}render(){let{data:e,linkService:t}=this,n=document.createElement(`a`);n.setAttribute(`data-element-id`,e.id);let r=!1;return e.url?(t.addLinkAttributes(n,e.url,e.newWindow),r=!0):e.action?(this._bindNamedAction(n,e.action,e.overlaidText),r=!0):e.attachment?(this.#t(n,e.attachmentId,e.attachment,e.overlaidText,e.attachmentDest),r=!0):e.setOCGState?(this.#n(n,e.setOCGState,e.overlaidText),r=!0):e.dest?(this._bindLink(n,e.dest,e.overlaidText),r=!0):(e.actions&&(e.actions.Action||e.actions[`Mouse Up`]||e.actions[`Mouse Down`])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(n,e),r=!0),e.resetForm?(this._bindResetFormAction(n,e.resetForm),r=!0):this.isTooltipOnly&&!r&&(this._bindLink(n,``),r=!0)),this.container.classList.add(`linkAnnotation`),r&&(this.contentElement=n,this.container.append(n)),this.container}#e(){this.container.setAttribute(`data-internal-link`,``)}_bindLink(e,t,n=``){e.href=this.linkService.getDestinationHash(t),e.onclick=()=>(t&&this.linkService.goToDestination(t),!1),(t||t===``)&&this.#e(),n&&(e.title=n)}_bindNamedAction(e,t,n=``){e.href=this.linkService.getAnchorUrl(``),e.onclick=()=>(this.linkService.executeNamedAction(t),!1),n&&(e.title=n),this.#e()}#t(e,t,n,r=``,i=null){e.href=this.linkService.getAnchorUrl(``),n.description?e.title=n.description:r&&(e.title=r);let a=async()=>{let e=await this.linkService.getAttachmentContent(t);e&&this.downloadManager?.openOrDownloadData(e,n.filename,i)};e.onclick=()=>(a(),!1),this.#e()}#n(e,t,n=``){e.href=this.linkService.getAnchorUrl(``),e.onclick=()=>(this.linkService.executeSetOCGState(t),!1),n&&(e.title=n),this.#e()}_bindJSAction(e,t){e.href=this.linkService.getAnchorUrl(``);let n=new Map([[`Action`,`onclick`],[`Mouse Up`,`onmouseup`],[`Mouse Down`,`onmousedown`]]);for(let r of Object.keys(t.actions)){let i=n.get(r);i&&(e[i]=()=>(this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t.id,name:r}}),!1))}t.overlaidText&&(e.title=t.overlaidText),e.onclick||=()=>!1,this.#e()}_bindResetFormAction(e,t){let n=e.onclick;if(n||(e.href=this.linkService.getAnchorUrl(``)),this.#e(),!this._fieldObjects){T('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),n||(e.onclick=()=>!1);return}e.onclick=()=>{n?.();let{fields:e,refs:r,include:i}=t,a=[];if(e.length!==0||r.length!==0){let t=new Set(r);for(let n of e){let e=this._fieldObjects[n]||[];for(let{id:n}of e)t.add(n)}for(let e of Object.values(this._fieldObjects))for(let n of e)t.has(n.id)===i&&a.push(n)}else for(let e of Object.values(this._fieldObjects))a.push(...e);let o=this.annotationStorage,s=[];for(let e of a){let{id:t}=e;switch(s.push(t),e.type){case`text`:{let n=e.defaultValue||``;o.setValue(t,{value:n});break}case`checkbox`:case`radiobutton`:{let n=e.defaultValue===e.exportValues;o.setValue(t,{value:n});break}case`combobox`:case`listbox`:{let n=e.defaultValue||``;o.setValue(t,{value:n});break}default:continue}let n=document.querySelector(`[data-element-id="${t}"]`);if(n){if(!Yr.has(n)){T(`_bindResetFormAction - element not allowed: ${t}`);continue}n.dispatchEvent(new Event(`resetform`))}}return this.enableScripting&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:`app`,ids:s,name:`ResetForm`}}),!1}}},ei=class extends Q{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add(`textAnnotation`);let e=document.createElement(`img`);return e.src=this.imageResourcesPath+`annotation-`+this.data.name.toLowerCase()+`.svg`,e.setAttribute(`data-l10n-id`,`pdfjs-text-annotation-type`),e.setAttribute(`data-l10n-args`,JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(e),this.container}},ti=class extends Q{render(){return this.container}_getKeyModifier(e){return F.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,t,n,r,i){n.includes(`mouse`)?e.addEventListener(n,e=>{this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:this.data.id,name:r,value:i(e),shift:e.shiftKey,modifier:this._getKeyModifier(e)}})}):e.addEventListener(n,e=>{if(n===`blur`){if(!t.focused||!e.relatedTarget)return;t.focused=!1}else if(n===`focus`){if(t.focused)return;t.focused=!0}i&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:this.data.id,name:r,value:i(e)}})})}_setEventListeners(e,t,n,r){for(let[i,a]of n)(a===`Action`||this.data.actions?.[a])&&((a===`Focus`||a===`Blur`)&&(t||={focused:!1}),this._setEventListener(e,t,i,a,r),a===`Focus`&&!this.data.actions?.Blur?this._setEventListener(e,t,`blur`,`Blur`,null):a===`Blur`&&!this.data.actions?.Focus&&this._setEventListener(e,t,`focus`,`Focus`,null))}_setTextStyle(e){let t=[`left`,`center`,`right`],{fontColor:n}=this.data.defaultAppearanceData,r=this.data.defaultAppearanceData.fontSize||Jr,i=e.style,a,o=e=>Math.round(10*e)/10;if(this.data.multiLine){let e=Math.abs(this.data.rect[3]-this.data.rect[1]-2),t=e/(Math.round(e/(1.35*r))||1);a=Math.min(r,o(t/1.35))}else{let e=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(r,o(e/1.35))}i.fontSize=`calc(${a}px * var(--total-scale-factor))`,i.color=I.makeHexColor(...n),this.data.textAlignment!==null&&!this.data.comb&&(i.textAlign=t[this.data.textAlignment])}_setRequired(e,t){t?e.setAttribute(`required`,!0):e.removeAttribute(`required`),e.setAttribute(`aria-required`,t)}},ni=class extends ti{constructor(e){let t=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:t})}setPropertyOnSiblings(e,t,n,r){let i=this.annotationStorage;for(let a of this._getElementsByName(e.name,e.id))a.domElement&&(a.domElement[t]=n),i.setValue(a.id,{[r]:n})}render(){let e=this.annotationStorage,t=this.data.id;this.container.classList.add(`textWidgetAnnotation`);let n=null;if(this.renderForms){let r=e.getValue(t,{value:this.data.fieldValue}),i=r.value||``,a=e.getValue(t,{charLimit:this.data.maxLen}).charLimit;a&&i.length>a&&(i=i.slice(0,a));let o=r.formattedValue||this.data.textContent?.join(` -`)||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,``));let s={userValue:i,formattedValue:o,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(n=document.createElement(`textarea`),n.textContent=o??i,this.data.doNotScroll&&(n.style.overflowY=`hidden`)):(n=document.createElement(`input`),n.type=this.data.password?`password`:`text`,n.setAttribute(`value`,o??i),this.data.doNotScroll&&(n.style.overflowX=`hidden`)),this.data.hasOwnCanvas&&(this.container.classList.add(`hasOwnCanvas`),e.has(t)&&this.container.classList.add(`sandboxModified`)),Yr.add(n),this.contentElement=n,n.setAttribute(`data-element-id`,t),n.disabled=this.data.readOnly,n.name=this.data.fieldName,n.tabIndex=0;let{datetimeFormat:c,datetimeType:l,timeStep:u}=this.data,d=!!l&&this.enableScripting;c&&(n.title=c),this._setRequired(n,this.data.required),a&&(n.maxLength=a),n.addEventListener(`input`,r=>{e.setValue(t,{value:r.target.value}),this.setPropertyOnSiblings(n,`value`,r.target.value,`value`),s.formattedValue=null}),n.addEventListener(`resetform`,e=>{let t=this.data.defaultFieldValue??``;n.value=s.userValue=t,s.formattedValue=null});let f=e=>{let{formattedValue:t}=s;t!=null&&(e.target.value=t),e.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){n.addEventListener(`focus`,e=>{if(s.focused)return;let{target:t}=e;if(d&&(t.type=l,u&&(t.step=u)),s.userValue){let e=s.userValue;if(d){if(l===`time`){let n=new Date(e);t.value=[n.getHours(),n.getMinutes(),n.getSeconds()].map(e=>e.toString().padStart(2,`0`)).join(`:`)}else t.value=new Date(e-Xr).toISOString().split(l===`date`?`T`:`.`,1)[0]}else t.value=e}s.lastCommittedValue=t.value,s.commitKey=1,this.data.actions?.Focus||(s.focused=!0)}),n.addEventListener(`updatefromsandbox`,n=>{this.container.classList.add(`sandboxModified`),this._dispatchEventFromSandbox({value(n){s.userValue=n.detail.value??``,d||e.setValue(t,{value:s.userValue.toString()}),n.target.value=s.userValue},formattedValue(n){let{formattedValue:r}=n.detail;s.formattedValue=r,r!=null&&n.target!==document.activeElement&&(n.target.value=r);let i={formattedValue:r};d&&(i.value=r),e.setValue(t,i)},selRange(e){e.target.setSelectionRange(...e.detail.selRange)},charLimit:n=>{let{charLimit:r}=n.detail,{target:i}=n;if(r===0){i.removeAttribute(`maxLength`);return}i.setAttribute(`maxLength`,r);let a=s.userValue;!a||a.length<=r||(a=a.slice(0,r),i.value=s.userValue=a,e.setValue(t,{value:a}),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:a,willCommit:!0,commitKey:1,selStart:i.selectionStart,selEnd:i.selectionEnd}}))}},n)}),n.addEventListener(`keydown`,e=>{s.commitKey=1;let n=-1;if(e.key===`Escape`?n=0:e.key===`Enter`&&!this.data.multiLine?n=2:e.key===`Tab`&&(s.commitKey=3),n===-1)return;let{value:r}=e.target;s.lastCommittedValue!==r&&(s.lastCommittedValue=r,s.userValue=r,this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:r,willCommit:!0,commitKey:n,selStart:e.target.selectionStart,selEnd:e.target.selectionEnd}}))});let r=f;f=null,n.addEventListener(`blur`,e=>{if(!s.focused||!e.relatedTarget)return;this.data.actions?.Blur||(s.focused=!1);let{target:n}=e,{value:i}=n;if(d){if(i&&l===`time`){let e=i.split(`:`).map(e=>parseInt(e,10));i=new Date(2e3,0,1,e[0],e[1],e[2]||0).valueOf(),n.step=``}else i.includes(`T`)||(i=`${i}T00:00`),i=new Date(i).valueOf();n.type=`text`}s.userValue=i,s.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:i,willCommit:!0,commitKey:s.commitKey,selStart:e.target.selectionStart,selEnd:e.target.selectionEnd}}),r(e)}),this.data.actions?.Keystroke&&n.addEventListener(`beforeinput`,e=>{s.lastCommittedValue=null;let{data:n,target:r}=e,{value:i,selectionStart:a,selectionEnd:o}=r,c=a,l=o;switch(e.inputType){case`deleteWordBackward`:{let e=i.substring(0,a).match(/\w*\W*$/);e&&(c-=e[0].length);break}case`deleteWordForward`:{let e=i.substring(a).match(/^\W*\w*/);e&&(l+=e[0].length);break}case`deleteContentBackward`:a===o&&--c;break;case`deleteContentForward`:a===o&&(l+=1)}e.preventDefault(),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:i,change:n||``,willCommit:!1,selStart:c,selEnd:l}})}),this._setEventListeners(n,s,[[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.value)}if(f&&n.addEventListener(`blur`,f),this.data.comb){let e=(this.data.rect[2]-this.data.rect[0])/a;n.classList.add(`comb`),n.style.setProperty(`--comb-width`,`calc(${e}px * var(--total-scale-factor))`);let t=this.data.textAlignment;if(t===1||t===2){let e=()=>{let e=a-n.value.length;n.style.setProperty(`--comb-offset`,`${t===1?e>>1:e}`)};e();for(let t of[`input`,`blur`,`resetform`,`updatefromsandbox`])n.addEventListener(t,e)}}}else n=document.createElement(`div`),n.textContent=this.data.fieldValue,n.style.verticalAlign=`middle`,n.style.display=`table-cell`,this.data.hasOwnCanvas&&(n.hidden=!0);return this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}},ri=class extends ti{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}},ii=class extends ti{constructor(e){super(e,{isRenderable:e.renderForms})}render(){let e=this.annotationStorage,t=this.data,n=t.id,r=e.getValue(n,{value:t.exportValue===t.fieldValue}).value;typeof r==`string`&&(r=r!==`Off`,e.setValue(n,{value:r})),this.container.classList.add(`buttonWidgetAnnotation`,`checkBox`);let i=document.createElement(`input`);return Yr.add(i),i.setAttribute(`data-element-id`,n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type=`checkbox`,i.name=t.fieldName,r&&i.setAttribute(`checked`,!0),i.setAttribute(`exportValue`,t.exportValue),i.tabIndex=0,i.addEventListener(`change`,r=>{let{name:i,checked:a}=r.target;for(let r of this._getElementsByName(i,n)){let n=a&&r.exportValue===t.exportValue;r.domElement&&(r.domElement.checked=n),e.setValue(r.id,{value:n})}e.setValue(n,{value:a})}),i.addEventListener(`resetform`,e=>{let n=t.defaultFieldValue||`Off`;e.target.checked=n===t.exportValue}),this.enableScripting&&this.hasJSActions&&(i.addEventListener(`updatefromsandbox`,t=>{this._dispatchEventFromSandbox({value(t){t.target.checked=t.detail.value!==`Off`,e.setValue(n,{value:t.target.checked})}},t)}),this._setEventListeners(i,null,[[`change`,`Validate`],[`change`,`Action`],[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.checked)),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},ai=class extends ti{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add(`buttonWidgetAnnotation`,`radioButton`);let e=this.annotationStorage,t=this.data,n=t.id,r=e.getValue(n,{value:t.buttonValue!==null&&t.fieldValue===t.buttonValue}).value;if(typeof r==`string`&&(r=r!==t.buttonValue,e.setValue(n,{value:r})),r)for(let r of this._getElementsByName(t.fieldName,n))e.setValue(r.id,{value:!1});let i=document.createElement(`input`);if(Yr.add(i),i.setAttribute(`data-element-id`,n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type=`radio`,i.name=t.fieldName,r&&i.setAttribute(`checked`,!0),i.tabIndex=0,i.addEventListener(`change`,t=>{let{name:r,checked:i}=t.target;for(let t of this._getElementsByName(r,n))e.setValue(t.id,{value:!1});e.setValue(n,{value:i})}),i.addEventListener(`resetform`,e=>{let n=t.defaultFieldValue;e.target.checked=n!=null&&n===t.buttonValue}),this.enableScripting&&this.hasJSActions){let r=t.buttonValue;i.addEventListener(`updatefromsandbox`,t=>{this._dispatchEventFromSandbox({value:t=>{let i=r===t.detail.value;for(let r of this._getElementsByName(t.target.name)){let t=i&&r.id===n;r.domElement&&(r.domElement.checked=t),e.setValue(r.id,{value:t})}}},t)}),this._setEventListeners(i,null,[[`change`,`Validate`],[`change`,`Action`],[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.checked)}return this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},oi=class extends $r{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){let e=super.render();e.classList.add(`buttonWidgetAnnotation`,`pushButton`);let t=e.lastChild;return this.enableScripting&&this.hasJSActions&&t&&(this._setDefaultPropertiesFromJS(t),t.addEventListener(`updatefromsandbox`,e=>{this._dispatchEventFromSandbox({},e)})),e}},si=class extends ti{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add(`choiceWidgetAnnotation`);let e=this.annotationStorage,t=this.data.id,n=e.getValue(t,{value:this.data.fieldValue}),r=document.createElement(`select`);Yr.add(r),r.setAttribute(`data-element-id`,t),r.disabled=this.data.readOnly,this._setRequired(r,this.data.required),r.name=this.data.fieldName,r.tabIndex=0;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(r.size=this.data.options.length,this.data.multiSelect&&(r.multiple=!0)),r.addEventListener(`resetform`,e=>{let t=this.data.defaultFieldValue;for(let e of r.options)e.selected=e.value===t});let a=(e,t)=>{let n=t.replaceAll(` `,`\xA0`);e.textContent=n,n!==t&&e.setAttribute(`display-value`,t)};for(let e of this.data.options){let t=document.createElement(`option`);a(t,e.displayValue),t.value=e.exportValue,n.value.includes(e.exportValue)&&(t.setAttribute(`selected`,!0),i=!1),r.append(t)}let o=null;if(i){let e=document.createElement(`option`);e.value=` `,e.setAttribute(`hidden`,!0),e.setAttribute(`selected`,!0),r.prepend(e),o=()=>{e.remove(),r.removeEventListener(`input`,o),o=null},r.addEventListener(`input`,o)}let s=e=>{let t=e?`value`:`textContent`,{options:n,multiple:i}=r;return i?Array.prototype.filter.call(n,e=>e.selected).map(e=>e[t]):n.selectedIndex===-1?null:n[n.selectedIndex][t]},c=s(!1),l=e=>{let t=e.target.options;return Array.prototype.map.call(t,e=>({displayValue:e.getAttribute(`display-value`)||e.textContent,exportValue:e.value}))};return this.enableScripting&&this.hasJSActions?(r.addEventListener(`updatefromsandbox`,n=>{this._dispatchEventFromSandbox({value(n){o?.();let i=n.detail.value,a=new Set(Array.isArray(i)?i:[i]);for(let e of r.options)e.selected=a.has(e.value);e.setValue(t,{value:s(!0)}),c=s(!1)},multipleSelection(e){r.multiple=!0},remove(n){let i=r.options,a=n.detail.remove;i[a].selected=!1,r.remove(a),i.length>0&&Array.prototype.findIndex.call(i,e=>e.selected)===-1&&(i[0].selected=!0),e.setValue(t,{value:s(!0),items:l(n)}),c=s(!1)},clear(n){for(;r.length!==0;)r.remove(0);e.setValue(t,{value:null,items:[]}),c=s(!1)},insert(n){let{index:i,displayValue:o,exportValue:u}=n.detail.insert,d=r.children[i],f=document.createElement(`option`);a(f,o),f.value=u,d?d.before(f):r.append(f),e.setValue(t,{value:s(!0),items:l(n)}),c=s(!1)},items(n){let{items:i}=n.detail;for(;r.length!==0;)r.remove(0);for(let e of i){let{displayValue:t,exportValue:n}=e,i=document.createElement(`option`);a(i,t),i.value=n,r.append(i)}r.options.length>0&&(r.options[0].selected=!0),e.setValue(t,{value:s(!0),items:l(n)}),c=s(!1)},indices(n){let r=new Set(n.detail.indices);for(let e of n.target.options)e.selected=r.has(e.index);e.setValue(t,{value:s(!0)}),c=s(!1)},editable(e){e.target.disabled=!e.detail.editable}},n)}),r.addEventListener(`input`,n=>{let r=s(!0),i=s(!1);e.setValue(t,{value:r}),n.preventDefault(),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:c,change:i,changeEx:r,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(r,null,[[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`],[`input`,`Action`],[`input`,`Validate`]],e=>e.target.value)):r.addEventListener(`input`,function(n){e.setValue(t,{value:s(!0)})}),this.data.combo&&this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}},ci=class extends Q{constructor(e){let{data:t,elements:n,parent:r}=e,i=!!r._commentManager;if(super(e,{isRenderable:!i&&Q._hasPopupData(t)}),this.elements=n,i&&Q._hasPopupData(t)){let e=this.popup=this.#e();for(let t of n)t.popup=e}else this.popup=null}#e(){return new li({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){let{container:e}=this;e.classList.add(`popupAnnotation`),e.role=`comment`;let t=this.popup=this.#e(),n=[];for(let e of this.elements)e.popup=t,e.container.ariaHasPopup=`dialog`,n.push(e.data.id),e.addHighlightArea();return this.container.setAttribute(`aria-controls`,n.map(e=>`${c}${e}`).join(`,`)),this.container}},li=class{#e=null;#t=this.#P.bind(this);#n=this.#R.bind(this);#r=this.#L.bind(this);#i=this.#I.bind(this);#a=null;#o=null;#s=null;#c=null;#l=null;#u=null;#d=null;#f=!1;#p=null;#m=null;#h=null;#g=null;#_=null;#v=null;#y=null;#b=null;#x=null;#S=null;#C=!1;#w=null;#T=null;constructor({container:e,color:t,elements:n,titleObj:r,modificationDate:i,contentsObj:a,richText:o,parent:s,rect:c,parentRect:l,open:u,commentManager:d=null}){this.#o=e,this.#x=r,this.#s=a,this.#b=o,this.#u=s,this.#a=t,this.#y=c,this.#d=l,this.#l=n,this.#e=d,this.#w=n[0],this.#c=je.toDateObject(i),this.trigger=n.flatMap(e=>e.getElementsToTriggerPopup()),d||(this.#E(),this.#o.hidden=!0,u&&this.#I())}#E(){if(this.#m)return;this.#m=new AbortController;let{signal:e}=this.#m;for(let t of this.trigger)t.addEventListener(`click`,this.#i,{signal:e}),t.addEventListener(`pointerenter`,this.#r,{signal:e}),t.addEventListener(`pointerleave`,this.#n,{signal:e}),t.classList.add(`popupTriggerArea`);for(let t of this.#l)t.container?.addEventListener(`keydown`,this.#t,{signal:e})}#D(){let e=this.#l.find(e=>e.hasCommentButton);e&&(this.#_=e._normalizePoint(e.commentButtonPosition))}renderCommentButton(){if(this.#g){this.#g.parentNode||this.#w.container.after(this.#g);return}if(this.#_||this.#D(),!this.#_)return;let{signal:e}=this.#m=new AbortController,t=this.#w.hasOwnCommentButton,n=()=>{this.#e.toggleCommentPopup(this,!0,void 0,!t)},r=()=>{this.#e.toggleCommentPopup(this,!1,!0,!t)},i=()=>{this.#e.toggleCommentPopup(this,!1,!1)};if(t){this.#g=this.#w.container;for(let t of this.trigger)t.ariaHasPopup=`dialog`,t.ariaControls=`commentPopup`,t.addEventListener(`keydown`,this.#t,{signal:e}),t.addEventListener(`click`,n,{signal:e}),t.addEventListener(`pointerenter`,r,{signal:e}),t.addEventListener(`pointerleave`,i,{signal:e}),t.classList.add(`popupTriggerArea`)}else{let t=this.#g=document.createElement(`button`);t.className=`annotationCommentButton`;let a=this.#w.container;t.style.zIndex=parseInt(a.style.zIndex,10)+1,t.tabIndex=0,t.ariaHasPopup=`dialog`,t.ariaControls=`commentPopup`,t.setAttribute(`data-l10n-id`,`pdfjs-show-comment-button`),this.#k(),this.#O(),t.addEventListener(`keydown`,this.#t,{signal:e}),t.addEventListener(`click`,n,{signal:e}),t.addEventListener(`pointerenter`,r,{signal:e}),t.addEventListener(`pointerleave`,i,{signal:e}),a.after(t)}}#O(){if(this.#w.extraPopupElement&&!this.#w.editor)return;this.#g||this.renderCommentButton();let[e,t]=this.#_,{style:n}=this.#g;n.left=`calc(${e}%)`,n.top=`calc(${t}% - var(--comment-button-dim))`}#k(){this.#w.extraPopupElement||(this.#g||this.renderCommentButton(),this.#g.style.backgroundColor=this.commentButtonColor||``)}get commentButtonColor(){let{color:e,opacity:t}=this.#w.commentData;return e?this.#u._commentManager.makeCommentColor(e,t):null}focusCommentButton(){setTimeout(()=>{this.#g?.focus()},0)}getData(){let{richText:e,color:t,opacity:n,creationDate:r,modificationDate:i}=this.#w.commentData;return{contentsObj:{str:this.comment},richText:e,color:t,opacity:n,creationDate:r,modificationDate:i}}get elementBeforePopup(){return this.#g}get comment(){return this.#T||=this.#w.commentText,this.#T}set comment(e){e!==this.comment&&(this.#w.commentText=this.#T=e)}focus(){this.#w.container?.focus()}get parentBoundingClientRect(){return this.#w.layer.getBoundingClientRect()}setCommentButtonStates({selected:e,hasPopup:t}){this.#g&&(this.#g.classList.toggle(`selected`,e),this.#g.ariaExpanded=t)}setSelectedCommentButton(e){this.#g.classList.toggle(`selected`,e)}get commentPopupPosition(){if(this.#v)return this.#v;let{x:e,y:t,height:n}=this.#g.getBoundingClientRect(),{x:r,y:i,width:a,height:o}=this.#w.layer.getBoundingClientRect();return[(e-r)/a,(t+n-i)/o]}set commentPopupPosition(e){this.#v=e}hasDefaultPopupPosition(){return this.#v===null}get commentButtonPosition(){return this.#_}get commentButtonWidth(){return this.#g.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(e){let[t,n]=this.#v||this.commentButtonPosition.map(e=>e/100),r=this.parentBoundingClientRect,{x:i,y:a,width:o,height:s}=r;this.#e.showDialog(null,this,i+t*o,a+n*s,{...e,parentDimensions:r})}render(){if(this.#p)return;let e=this.#p=document.createElement(`div`);if(e.className=`popup`,this.#a){let t=e.style.outlineColor=I.makeHexColor(...this.#a);e.style.backgroundColor=`color-mix(in srgb, ${t} 30%, white)`}let t=document.createElement(`span`);if(t.className=`header`,this.#x?.str){let e=document.createElement(`span`);e.className=`title`,t.append(e),{dir:e.dir,str:e.textContent}=this.#x}if(e.append(t),this.#c){let e=document.createElement(`time`);e.className=`popupDate`,e.setAttribute(`data-l10n-id`,`pdfjs-annotation-date-time-string`),e.setAttribute(`data-l10n-args`,JSON.stringify({dateObj:this.#c.valueOf()})),e.dateTime=this.#c.toISOString(),t.append(e)}qe({html:this.#A||this.#s.str,dir:this.#s?.dir,className:`popupContent`},e),this.#o.append(e)}get#A(){let e=this.#b,t=this.#s;return e?.str&&(!t?.str||t.str===e.str)&&this.#b.html||null}get#j(){return this.#A?.attributes?.style?.fontSize||0}get#M(){return this.#A?.attributes?.style?.color||null}#N(e){let t=[],n={str:e,html:{name:`div`,attributes:{dir:`auto`},children:[{name:`p`,children:t}]}},r={style:{color:this.#M,fontSize:this.#j?`calc(${this.#j}px * var(--total-scale-factor))`:``}};for(let n of e.split(` -`))t.push({name:`span`,value:n,attributes:r});return n}#P(e){e.altKey||e.shiftKey||e.ctrlKey||e.metaKey||(e.key===`Enter`||e.key===`Escape`&&this.#f)&&this.#I()}updateEdited({rect:e,popup:t,deleted:n}){if(this.#e){n?(this.remove(),this.#T=null):t&&(t.deleted?this.remove():(this.#k(),this.#T=t.text)),e&&(this.#_=null,this.#D(),this.#O());return}if(n||t?.deleted){this.remove();return}this.#E(),this.#S||={contentsObj:this.#s,richText:this.#b},e&&(this.#h=null),t&&t.text&&(this.#b=this.#N(t.text),this.#c=je.toDateObject(t.date),this.#s=null),this.#p?.remove(),this.#p=null}resetEdited(){this.#S&&({contentsObj:this.#s,richText:this.#b}=this.#S,this.#S=null,this.#p?.remove(),this.#p=null,this.#h=null)}remove(){if(this.#m?.abort(),this.#m=null,this.#p?.remove(),this.#p=null,this.#C=!1,this.#f=!1,this.#g?.remove(),this.#g=null,this.trigger)for(let e of this.trigger)e.classList.remove(`popupTriggerArea`)}#F(){if(this.#h!==null)return;let{page:{view:e},viewport:{rawDims:{pageWidth:t,pageHeight:n,pageX:r,pageY:i}}}=this.#u,a=!!this.#d,o=a?this.#d:this.#y;for(let e of this.#l)if(!o||I.intersect(e.data.rect,o)!==null){o=e.data.rect,a=!0;break}let s=I.normalizeRect([o[0],e[3]-o[1]+e[1],o[2],e[3]-o[3]+e[1]]),c=a?o[2]-o[0]+5:0,l=s[0]+c,u=s[1];this.#h=[100*(l-r)/t,100*(u-i)/n];let{style:d}=this.#o;d.left=`${this.#h[0]}%`,d.top=`${this.#h[1]}%`}#I(){if(this.#e){this.#e.toggleCommentPopup(this,!1);return}this.#f=!this.#f,this.#f?(this.#L(),this.#o.addEventListener(`click`,this.#i),this.#o.addEventListener(`keydown`,this.#t)):(this.#R(),this.#o.removeEventListener(`click`,this.#i),this.#o.removeEventListener(`keydown`,this.#t))}#L(){this.#p||this.render(),this.isVisible?this.#f&&this.#o.classList.add(`focused`):(this.#F(),this.#o.hidden=!1,this.#o.style.zIndex=parseInt(this.#o.style.zIndex,10)+1e3)}#R(){this.#o.classList.remove(`focused`),!(this.#f||!this.isVisible)&&(this.#o.hidden=!0,this.#o.style.zIndex=parseInt(this.#o.style.zIndex,10)-1e3)}forceHide(){this.#C=this.isVisible,this.#C&&(this.#o.hidden=!0)}maybeShow(){this.#e||(this.#E(),this.#C&&(this.#p||this.#L(),this.#C=!1,this.#o.hidden=!1))}get isVisible(){return!this.#e&&this.#o.hidden===!1}},ui=class extends Q{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=u.FREETEXT}render(){if(this.container.classList.add(`freeTextAnnotation`),this.textContent){let e=this.contentElement=document.createElement(`div`);e.classList.add(`annotationTextContent`),e.setAttribute(`role`,`comment`);for(let t of this.textContent){let n=document.createElement(`span`);n.textContent=t,e.append(n)}this.container.append(e)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}},di=class extends Q{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`lineAnnotation`);let{data:e,width:t,height:n}=this,r=this.svgFactory.create(t,n,!0),i=this.#e=this.svgFactory.createElement(`svg:line`);return i.setAttribute(`x1`,e.rect[2]-e.lineCoordinates[0]),i.setAttribute(`y1`,e.rect[3]-e.lineCoordinates[1]),i.setAttribute(`x2`,e.rect[2]-e.lineCoordinates[2]),i.setAttribute(`y2`,e.rect[3]-e.lineCoordinates[3]),i.setAttribute(`stroke-width`,e.borderStyle.width||1),i.setAttribute(`stroke`,`transparent`),i.setAttribute(`fill`,`transparent`),r.append(i),this.container.append(r),!e.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},fi=class extends Q{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`squareAnnotation`);let{data:e,width:t,height:n}=this,r=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,a=this.#e=this.svgFactory.createElement(`svg:rect`);return a.setAttribute(`x`,i/2),a.setAttribute(`y`,i/2),a.setAttribute(`width`,t-i),a.setAttribute(`height`,n-i),a.setAttribute(`stroke-width`,i||1),a.setAttribute(`stroke`,`transparent`),a.setAttribute(`fill`,`transparent`),r.append(a),this.container.append(r),!e.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},pi=class extends Q{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`circleAnnotation`);let{data:e,width:t,height:n}=this,r=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,a=this.#e=this.svgFactory.createElement(`svg:ellipse`);return a.setAttribute(`cx`,t/2),a.setAttribute(`cy`,n/2),a.setAttribute(`rx`,t/2-i/2),a.setAttribute(`ry`,n/2-i/2),a.setAttribute(`stroke-width`,i||1),a.setAttribute(`stroke`,`transparent`),a.setAttribute(`fill`,`transparent`),r.append(a),this.container.append(r),!e.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},mi=class extends Q{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName=`polylineAnnotation`,this.svgElementName=`svg:polyline`}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,vertices:t,borderStyle:n,popupRef:r},width:i,height:a}=this;if(!t)return this.container;let o=this.svgFactory.create(i,a,!0),s=[];for(let n=0,r=t.length;n=0&&i.setAttribute(`stroke-width`,t||1),n)for(let e=0,t=this.#t.length;e{e.key===`Enter`&&(r?e.metaKey:e.ctrlKey)&&this.#t()}),!t.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):n.classList.add(`popupTriggerArea`),e.append(n),e}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}async#t(){let{fileId:e,filename:t,content:n}=this,r=await this.linkService.getAttachmentContent(e)||n;r&&this.downloadManager?.openOrDownloadData(r,t)}},wi=class extends Q{#e=new AbortController;#t=null;#n=null;constructor(e){super(e,{isRenderable:!!e.data.richMedia})}render(){this.container.classList.add(`mediaAnnotation`);let{filename:e}=this.data.richMedia,t=document.createElement(`button`);return t.className=`mediaPlayButton`,t.type=`button`,t.title=t.ariaLabel=e,t.addEventListener(`click`,()=>this.#r(t),{signal:this.#e.signal}),this.container.append(t),this.container}async#r(e){let{fileId:t,filename:n,contentType:r}=this.data.richMedia;e.disabled=!0;let i;try{i=await this.linkService.getAttachmentContent(t)}catch{return}finally{e.disabled=!1}if(!i||!e.isConnected)return;let{signal:a}=this.#e,o=URL.createObjectURL(new Blob([i],{type:r}));this.#t=o;let s=r.startsWith(`audio/`),c=document.createElement(s?`audio`:`video`);if(this.#n=c,c.className=`mediaContent`,this._setBackgroundColor(c),c.src=o,c.title=n,c.controls=!0,c.autoplay=!0,c.tabIndex=0,s){let e=!1,t=!1,n=()=>{c.controls=e||t};this.container.addEventListener(`pointerenter`,()=>{e=!0,n()},{signal:a}),this.container.addEventListener(`pointerleave`,()=>{e=!1,n()},{signal:a}),this.container.addEventListener(`focusin`,()=>{t=!0,n()},{signal:a}),this.container.addEventListener(`focusout`,()=>{t=!1,n()},{signal:a})}c.addEventListener(`emptied`,()=>this.#i(o),{once:!0,signal:a}),e.replaceWith(c),c.play().catch(()=>{})}#i(e=this.#t){e&&e===this.#t&&(URL.revokeObjectURL(e),this.#t=null)}destroy(){this.#e.abort(),this.#n&&=(this.#n.pause(),this.#n.removeAttribute(`src`),this.#n.load(),null),this.#i()}},Ti=class e{#e=null;#t=null;#n=null;#r=new Map;#i=null;#a=null;#o=[];#s=!1;zIndex=0;constructor({div:e,accessibilityManager:t,annotationCanvasMap:n,annotationEditorUIManager:r,page:i,viewport:a,structTreeLayer:o,commentManager:s,linkService:c,annotationStorage:l}){this.div=e,this.#e=t,this.#t=n,this.#i=o||null,this.#a=c||null,this.#n=l||new pt,this.page=i,this.viewport=a,this._annotationEditorUIManager=r,this._commentManager=s||null}hasEditableAnnotations(){return this.#r.size>0}async render(e){let{annotations:t,optionalContentConfig:n}=e,r=this.div;Fe(r,this.viewport);let i=new Map,a=[],o={data:null,layer:r,linkService:this.#a,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||``,renderForms:e.renderForms!==!1,svgFactory:new qr,annotationStorage:this.#n,enableComment:e.enableComment===!0,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(let e of t){if(e.noHTML)continue;let t=e.annotationType===h.POPUP;if(t){let t=i.get(e.id);if(!t)continue;if(!this._commentManager){a.push(e);continue}o.elements=t}else if(e.rect[2]===e.rect[0]||e.rect[3]===e.rect[1])continue;o.data=e;let r=Zr.create(o);if(!r.isRenderable)continue;t||(this.#o.push(r),e.popupRef&&i.getOrInsertComputed(e.popupRef,pe).push(r));let s=r.render();e.hidden&&(s.style.visibility=`hidden`),r.updateOC(n),r._isEditable&&(this.#r.set(r.data.id,r),this._annotationEditorUIManager?.renderAnnotationElement(r))}await this.#c();for(let e of a){let t=o.elements=i.get(e.id);o.data=e;let n=Zr.create(o);if(!n.isRenderable)continue;let r=n.render();n.contentElement.id=`${c}${e.id}`,e.hidden&&(r.style.visibility=`hidden`),t.at(-1).container.after(r)}this.#l()}async#c(){if(this.#o.length===0)return;this.div.replaceChildren();let e=[];if(!this.#s){this.#s=!0;for(let{contentElement:t,data:{id:n}}of this.#o){let r=t.id=`${c}${n}`;e.push(this.#i?.getAriaAttributes(r).then(e=>{if(e)for(let[n,r]of e)t.setAttribute(n,r)}))}}this.#o.sort(({data:{rect:[e,t,n,r]}},{data:{rect:[i,a,o,s]}})=>{if(e===n&&t===r)return 1;if(i===o&&a===s)return-1;let c=r,l=t,u=(t+r)/2,d=s,f=a,p=(a+s)/2;return u>=d&&p<=l?-1:p>=c&&u<=f?1:(e+n)/2-(i+o)/2});let t=document.createDocumentFragment();for(let e of this.#o)t.append(e.container),this._commentManager?(e.extraPopupElement?.popup||e.popup)?.renderCommentButton():e.extraPopupElement&&t.append(e.extraPopupElement.render());if(this.div.append(t),await Promise.all(e),this.#e)for(let e of this.#o)this.#e.addPointerInTextLayer(e.contentElement,!1)}async addLinkAnnotations(t){let n={data:null,layer:this.div,linkService:this.#a,svgFactory:new qr,parent:this};for(let r of t){r.borderStyle||=e._defaultBorderStyle,n.data=r;let t=Zr.create(n);t.isRenderable&&(t.render(),t.contentElement.id=`${c}${r.id}`,this.#o.push(t))}await this.#c()}update({viewport:e,optionalContentConfig:t}){let n=this.div;this.viewport=e,Fe(n,{rotation:e.rotation});for(let e of this.#o)e.updateOC(t);this.#l(),n.hidden=!1}destroy(){for(let e of this.#o)e.destroy?.(),this.#e?.removePointerInTextLayer(e.contentElement);this.#o.length=0,this.#r.clear(),this.div.replaceChildren()}#l(){if(!this.#t)return;let e=this.div;for(let[t,n]of this.#t){let r=e.querySelector(`[data-annotation-id="${t}"]`);if(!r)continue;if(Array.isArray(n))for(let e of n)e.className=`annotationContent`,e.ariaHidden=!0;else n.className=`annotationContent`,n.ariaHidden=!0;let i=[];for(let e of r.children)e.nodeName===`CANVAS`&&i.push(e);for(let e of i)e.remove();let a=Array.isArray(n)?n[0]:n,{firstChild:o}=r;if(o?o.classList.contains(`annotationContent`)?o.after(a):o.before(a):r.append(a),Array.isArray(n)){let e=a;for(let t=1,r=n.length;tt.data.id===e);if(t<0)return;let[n]=this.#o.splice(t,1);this.#e?.removePointerInTextLayer(n.contentElement)}updateFakeAnnotations(e){if(e.length!==0){for(let t of e)t.updateFakeAnnotationElement(this);this.#c()}}togglePointerEvents(e=!1){this.div.classList.toggle(`disabled`,!e)}static get _defaultBorderStyle(){return M(this,`_defaultBorderStyle`,Object.freeze({width:1,rawWidth:1,style:g.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}},Ei=/\r\n?|\n/g,Di=class e extends U{#e=``;#t=`${this.id}-editor`;#n=null;#r;_colorPicker=null;static _freeTextDefaultContent=``;static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.isEmpty(),r=it.TRANSLATE_SMALL,i=it.TRANSLATE_BIG;return M(this,`_keyboardManager`,new nt([[[`ctrl+s`,`mac+meta+s`,`ctrl+p`,`mac+meta+p`],t.commitOrRemove,{bubbles:!0}],[[`ctrl+Enter`,`mac+meta+Enter`],t.commitOrRemove],[[`Escape`],t.commitOrRemove],[[`ArrowLeft`],t._translateEmpty,{args:[-r,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t._translateEmpty,{args:[-i,0],checker:n}],[[`ArrowRight`],t._translateEmpty,{args:[r,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t._translateEmpty,{args:[i,0],checker:n}],[[`ArrowUp`],t._translateEmpty,{args:[0,-r],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t._translateEmpty,{args:[0,-i],checker:n}],[[`ArrowDown`],t._translateEmpty,{args:[0,r],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t._translateEmpty,{args:[0,i],checker:n}]]))}static _type=`freetext`;static _editorType=u.FREETEXT;constructor(t){super({...t,name:`freeTextEditor`}),this.color=t.color||e._defaultColor||U._defaultLineColor,this.#r=t.fontSize||e._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert(U._l10nAlert.freetext),this.canAddComment=!1}static initialize(e,t){U.initialize(e,t);let n=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(n.getPropertyValue(`--freetext-padding`))}static updateDefaultParams(t,n){switch(t){case d.FREETEXT_SIZE:e._defaultFontSize=n;break;case d.FREETEXT_COLOR:e._defaultColor=n}}updateParams(e,t){switch(e){case d.FREETEXT_SIZE:this.#i(t);break;case d.FREETEXT_COLOR:this.#a(t)}}static get defaultPropertiesToUpdate(){return[[d.FREETEXT_SIZE,e._defaultFontSize],[d.FREETEXT_COLOR,e._defaultColor||U._defaultLineColor]]}get propertiesToUpdate(){return[[d.FREETEXT_SIZE,this.#r],[d.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new Hr(this),[[`colorPicker`,this._colorPicker]]}get colorType(){return d.FREETEXT_COLOR}#i(e){let t=e=>{this.editorDiv.style.fontSize=`calc(${e}px * var(--total-scale-factor))`,this.translate(0,-(e-this.#r)*this.parentScale),this.#r=e,this.#s()},n=this.#r;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#a(e){let t=e=>{this.color=e,this.onUpdatedColor()},n=this.color;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(e,t){this._uiManager.translateSelectedEditors(e,t,!0)}getInitialTranslation(){let t=this.parentScale;return[-e._internalPadding*t,-(e._internalPadding+this.#r)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove(`enabled`),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute(`aria-activedescendant`),this.#n=new AbortController;let e=this._uiManager.combinedSignal(this.#n);return this.editorDiv.addEventListener(`keydown`,this.editorDivKeydown.bind(this),{signal:e}),this.editorDiv.addEventListener(`focus`,this.editorDivFocus.bind(this),{signal:e}),this.editorDiv.addEventListener(`blur`,this.editorDivBlur.bind(this),{signal:e}),this.editorDiv.addEventListener(`input`,this.editorDivInput.bind(this),{signal:e}),this.editorDiv.addEventListener(`paste`,this.editorDivPaste.bind(this),{signal:e}),!0}disableEditMode(){return super.disableEditMode()?(this.overlayDiv.classList.add(`enabled`),this.editorDiv.contentEditable=!1,this.div.setAttribute(`aria-activedescendant`,this.#t),this._isDraggable=!0,this.#n?.abort(),this.#n=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add(`freetextEditing`),!0):!1}focusin(e){this._focusEventsAllowed&&(super.focusin(e),e.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(e){this.width||(this.enableEditMode(),e&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===``}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add(`freetextEditing`)),super.remove()}#o(){let t=[];this.editorDiv.normalize();let n=null;for(let r of this.editorDiv.childNodes)(n?.nodeType!==Node.TEXT_NODE||r.nodeName!==`BR`)&&(t.push(e.#c(r)),n=r);return t.join(` -`)}#s(){let[e,t]=this.parentDimensions,n;if(this.isAttachedToDOM)n=this.div.getBoundingClientRect();else{let{currentLayer:e,div:t}=this,r=t.style.display,i=t.classList.contains(`hidden`);t.classList.remove(`hidden`),t.style.display=`hidden`,e.div.append(this.div),n=t.getBoundingClientRect(),t.remove(),t.style.display=r,t.classList.toggle(`hidden`,i)}this.rotation%180==this.parentRotation%180?(this.width=n.width/e,this.height=n.height/t):(this.width=n.height/e,this.height=n.width/t),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let e=this.#e,t=this.#e=this.#o().trimEnd();if(e===t)return;let n=e=>{if(this.#e=e,!e){this.remove();return}this.#l(),this._uiManager.rebuild(this),this.#s()};this.addCommands({cmd:()=>{n(t)},undo:()=>{n(e)},mustExec:!1}),this.#s()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(e){e.target===this.div&&e.key===`Enter`&&(this.enterInEditMode(),e.preventDefault())}editorDivKeydown(t){e._keyboardManager.exec(this,t)}editorDivFocus(e){this.isEditing=!0}editorDivBlur(e){this.isEditing=!1}editorDivInput(e){this.parent.div.classList.toggle(`freetextEditing`,this.isEmpty())}disableEditing(){this.editorDiv.setAttribute(`role`,`comment`),this.editorDiv.removeAttribute(`aria-multiline`)}enableEditing(){this.editorDiv.setAttribute(`role`,`textbox`),this.editorDiv.setAttribute(`aria-multiline`,!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let e,t;(this._isCopy||this.annotationElementId)&&(e=this.x,t=this.y),super.render(),this.editorDiv=document.createElement(`div`),this.editorDiv.className=`internal`,this.editorDiv.setAttribute(`id`,this.#t),this.editorDiv.setAttribute(`data-l10n-id`,`pdfjs-free-text2`),this.editorDiv.setAttribute(`data-l10n-attrs`,`default-content`),this.enableEditing(),this.editorDiv.contentEditable=!0;let{style:n}=this.editorDiv;if(n.fontSize=`calc(${this.#r}px * var(--total-scale-factor))`,n.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement(`div`),this.overlayDiv.classList.add(`overlay`,`enabled`),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){let[n,r]=this.parentDimensions;if(this.annotationElementId){let{position:i}=this._initialData,[a,o]=this.getInitialTranslation();[a,o]=this.pageTranslationToScreen(a,o);let[s,c]=this.pageDimensions,[l,u]=this.pageTranslation,d,f;switch(this.rotation){case 0:d=e+(i[0]-l)/s,f=t+this.height-(i[1]-u)/c;break;case 90:d=e+(i[0]-l)/s,f=t-(i[1]-u)/c,[a,o]=[o,-a];break;case 180:d=e-this.width+(i[0]-l)/s,f=t-(i[1]-u)/c,[a,o]=[-a,-o];break;case 270:d=e+(i[0]-l-this.height*c)/s,f=t+(i[1]-u-this.width*s)/c,[a,o]=[-o,a]}this.setAt(d*n,f*r,a,o)}else this._moveAfterPaste(e,t);this.#l(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#c(e){return(e.nodeType===Node.TEXT_NODE?e.nodeValue:e.innerText).replaceAll(Ei,``)}editorDivPaste(t){let n=t.clipboardData||window.clipboardData,{types:r}=n;if(r.length===1&&r[0]===`text/plain`)return;t.preventDefault();let i=e.#d(n.getData(`text`)||``).replaceAll(Ei,` -`);if(!i)return;let a=window.getSelection();if(!a.rangeCount)return;this.editorDiv.normalize(),a.deleteFromDocument();let o=a.getRangeAt(0);if(!i.includes(` -`)){o.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),a.collapseToStart();return}let{startContainer:s,startOffset:c}=o,l=[],u=[];if(s.nodeType===Node.TEXT_NODE){let t=s.parentElement;if(u.push(s.nodeValue.slice(c).replaceAll(Ei,``)),t!==this.editorDiv){let n=l;for(let r of this.editorDiv.childNodes){if(r===t){n=u;continue}n.push(e.#c(r))}}l.push(s.nodeValue.slice(0,c).replaceAll(Ei,``))}else if(s===this.editorDiv){let t=l,n=0;for(let r of this.editorDiv.childNodes)n++===c&&(t=u),t.push(e.#c(r))}this.#e=`${l.join(` -`)}${i}${u.join(` -`)}`,this.#l();let d=new Range,f=Math.sumPrecise(l.map(e=>e.length));for(let{firstChild:e}of this.editorDiv.childNodes)if(e.nodeType===Node.TEXT_NODE){let t=e.nodeValue.length;if(f<=t){d.setStart(e,f),d.setEnd(e,f);break}f-=t}a.removeAllRanges(),a.addRange(d)}#l(){if(this.editorDiv.replaceChildren(),this.#e)for(let e of this.#e.split(` -`)){let t=document.createElement(`div`);t.append(e?document.createTextNode(e):document.createElement(`br`)),this.editorDiv.append(t)}}#u(){return this.#e.replaceAll(`\xA0`,` `)}static#d(e){return e.replaceAll(` `,`\xA0`)}get contentDiv(){return this.editorDiv}getPDFRect(){let t=e._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,n,r){let i=null;if(t instanceof ui){let{data:{defaultAppearanceData:{fontSize:e,fontColor:n},rect:r,rotation:a,id:o,popupRef:s,richText:c,contentsObj:l,creationDate:d,modificationDate:f},textContent:p,textPosition:m,parent:{page:{pageNumber:h}}}=t;if(!p?.length)return null;i=t={annotationType:u.FREETEXT,color:Array.from(n),fontSize:e,value:p.join(` -`),position:m,pageIndex:h-1,rect:r.slice(0),rotation:a,annotationElementId:o,id:o,deleted:!1,popupRef:s,comment:l?.str||null,richText:c,creationDate:d,modificationDate:f}}let a=await super.deserialize(t,n,r);return a.#r=t.fontSize,a.color=I.makeHexColor(...t.color),a.#e=e.#d(t.value),a._initialData=i,t.comment&&a.setCommentData(t),a}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let t=U._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),n=Object.assign(super.serialize(e),{color:t,fontSize:this.#r,value:this.#u()});return this.addComment(n),e?(n.isCopy=!0,n):this.annotationElementId&&!this.#f(n)?null:(n.id=this.annotationElementId,n)}#f(e){let{value:t,fontSize:n,color:r,pageIndex:i}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||e.value!==t||e.fontSize!==n||e.color.some((e,t)=>e!==r[t])||e.pageIndex!==i}renderAnnotationElement(e){let t=super.renderAnnotationElement(e);if(!t)return null;let{style:n}=t;n.fontSize=`calc(${this.#r}px * var(--total-scale-factor))`,n.color=this.color,t.replaceChildren();for(let e of this.#e.split(` -`)){let n=document.createElement(`div`);n.append(e?document.createTextNode(e):document.createElement(`br`)),t.append(n)}return e.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#e}}),t}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}},$=class{static PRECISION=1e-4;toSVGPath(){E("Abstract method `toSVGPath` must be implemented.")}get box(){E("Abstract getter `box` must be implemented.")}serialize(e,t){E("Abstract method `serialize` must be implemented.")}static _rescale(e,t,n,r,i,a){a||=new Float32Array(e.length);for(let o=0,s=e.length;o=6;e-=6)isNaN(t[e])?n.push(`L${t[e+4]} ${t[e+5]}`):n.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);return this.#v(n),n.join(` `)}#_(){let[e,t,n,r]=this.#e,[i,a,o,s]=this.#g();return`M${(this.#a[2]-e)/n} ${(this.#a[3]-t)/r} L${(this.#a[4]-e)/n} ${(this.#a[5]-t)/r} L${i} ${a} L${o} ${s} L${(this.#a[16]-e)/n} ${(this.#a[17]-t)/r} L${(this.#a[14]-e)/n} ${(this.#a[15]-t)/r} Z`}#v(e){let t=this.#t;e.push(`L${t[4]} ${t[5]} Z`)}#y(e){let[t,n,r,i]=this.#e,a=this.#a.subarray(4,6),o=this.#a.subarray(16,18),[s,c,l,u]=this.#g();e.push(`L${(a[0]-t)/r} ${(a[1]-n)/i} L${s} ${c} L${l} ${u} L${(o[0]-t)/r} ${(o[1]-n)/i}`)}newFreeDrawOutline(e,t,n,r,i,a){return new ki(e,t,n,r,i,a)}getOutlines(){let e=this.#i,t=this.#t,n=this.#a,[r,i,a,o]=this.#e,s=new Float32Array((this.#f?.length??0)+2);for(let e=0,t=s.length-2;e=6;e-=6)for(let n=0;n<6;n+=2){if(isNaN(t[e+n])){c[l]=c[l+1]=NaN,l+=2;continue}c[l]=t[e+n],c[l+1]=t[e+n+1],l+=2}return this.#x(c,l),this.newFreeDrawOutline(c,s,this.#e,this.#u,this.#n,this.#r)}#b(e){let t=this.#a,[n,r,i,a]=this.#e,[o,s,c,l]=this.#g(),u=new Float32Array(36);return u.set([NaN,NaN,NaN,NaN,(t[2]-n)/i,(t[3]-r)/a,NaN,NaN,NaN,NaN,(t[4]-n)/i,(t[5]-r)/a,NaN,NaN,NaN,NaN,o,s,NaN,NaN,NaN,NaN,c,l,NaN,NaN,NaN,NaN,(t[16]-n)/i,(t[17]-r)/a,NaN,NaN,NaN,NaN,(t[14]-n)/i,(t[15]-r)/a],0),this.newFreeDrawOutline(u,e,this.#e,this.#u,this.#n,this.#r)}#x(e,t){let n=this.#t;return e.set([NaN,NaN,NaN,NaN,n[4],n[5]],t),t+=6}#S(e,t){let n=this.#a.subarray(4,6),r=this.#a.subarray(16,18),[i,a,o,s]=this.#e,[c,l,u,d]=this.#g();return e.set([NaN,NaN,NaN,NaN,(n[0]-i)/o,(n[1]-a)/s,NaN,NaN,NaN,NaN,c,l,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(r[0]-i)/o,(r[1]-a)/s],t),t+=24}},ki=class extends ${#e;#t=new Float32Array(4);#n;#r;#i;#a;#o;constructor(e,t,n,r,i,a){super(),this.#o=e,this.#i=t,this.#e=n,this.#a=r,this.#n=i,this.#r=a,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#s(a);let[o,s,c,l]=this.#t;for(let t=0,n=e.length;tp?(o=f,s=p):s===p&&(o=u(o,f)),ld[1]?(o=d[0],s=d[1]):s===d[1]&&(o=u(o,d[0])),le[0]-t[0]||e[1]-t[1]||e[2]-t[2]);let e=[];for(let t of this.#r)t[3]?(e.push(...this.#l(t)),this.#s(t)):(this.#c(t),e.push(...this.#l(t)));return this.#a(e)}#a(e){let t=[],n=new Set;for(let n of e){let[e,r,i]=n;t.push([e,r,n],[e,i,n])}t.sort((e,t)=>e[1]-t[1]||e[0]-t[0]);for(let e=0,r=t.length;e0;){let e=n.values().next().value,[t,a,o,s,c]=e;n.delete(e);let l=t,u=a;for(i=[t,o],r.push(i);;){let e;if(n.has(s))e=s;else if(n.has(c))e=c;else break;n.delete(e),[t,a,o,s,c]=e,l!==t&&(i.push(l,u,t,u===a?a:o),l=t),u=u===a?o:a}i.push(l,u)}return new ji(r,this.#e,this.#t,this.#n)}#o(e){let t=this.#i,n=0,r=t.length-1;for(;n<=r;){let i=n+r>>1,a=t[i][0];if(a===e)return i;a=0;r--){let[n,i]=this.#i[r];if(n!==e)break;if(n===e&&i===t){this.#i.splice(r,1);return}}}#l(e){let[t,n,r]=e,i=[[t,n,r]],a=this.#o(r);for(let e=0;e=n){if(s>r)i[e][1]=r;else{if(a===1)return[];i.splice(e,1),e--,a--}continue}i[e][2]=n,s>r&&i.push([t,r,s])}}}return i}},ji=class extends ${#e;#t;constructor(e,t,n,r){super(),this.#t=e,this.#e=t,this.firstPoint=n,this.lastPoint=r}toSVGPath(){let e=[];for(let t of this.#t){let[n,r]=t;e.push(`M${n} ${r}`);for(let i=2;i-1?(this.#d=!0,this.#y(t),this.#w()):this.#n&&(this.#e=t.anchorNode,this.#t=t.anchorOffset,this.#o=t.focusNode,this.#s=t.focusOffset,this.#v(),this.#w(),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert(U._l10nAlert.highlight)}get telemetryInitialData(){return{action:`added`,type:this.#d?`free_highlight`:`highlight`,color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#g,methodOfCreation:this.#_}}get telemetryFinalData(){return{type:`highlight`,color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(e){return{numberOfColors:e.get(`color`).size}}#v(){let e=new Ai(this.#n,.001);this.#l=e.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;let t=new Ai(this.#n,.0025,.001,this._uiManager.direction===`ltr`);this.#a=t.getOutlines();let{firstPoint:n}=this.#l;this.#f=[(n[0]-this.x)/this.width,(n[1]-this.y)/this.height];let{lastPoint:r}=this.#a;this.#p=[(r[0]-this.x)/this.width,(r[1]-this.y)/this.height]}#y({highlightOutlines:t,highlightId:n,clipPathId:r}){if(this.#l=t,this.#a=t.getNewOutline(this.#g/2+1.5,.0025),n>=0)this.#u=n,this.#r=r,this.parent.drawLayer.finalizeDraw(n,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#m=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#a.box,path:{d:this.#a.toSVGPath()}},!0);else if(this.parent){let n=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#u,{bbox:e.#T(this.#l.box,(n-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#m,{bbox:e.#T(this.#a.box,n),path:{d:this.#a.toSVGPath()}})}let[i,a,o,s]=t.box;switch(this.rotation){case 0:this.x=i,this.y=a,this.width=o,this.height=s;break;case 90:{let[e,t]=this.parentDimensions;this.x=a,this.y=1-i,this.width=o*t/e,this.height=s*e/t;break}case 180:this.x=1-i,this.y=1-a,this.width=o,this.height=s;break;case 270:{let[e,t]=this.parentDimensions;this.x=1-a,this.y=i,this.width=o*t/e,this.height=s*e/t;break}}let{firstPoint:c}=t;this.#f=[(c[0]-i)/o,(c[1]-a)/s];let{lastPoint:l}=this.#a;this.#p=[(l[0]-i)/o,(l[1]-a)/s]}static initialize(t,n){U.initialize(t,n),e._defaultColor||=n.highlightColors?.values().next().value||`#fff066`}static updateDefaultParams(t,n){switch(t){case d.HIGHLIGHT_COLOR:e._defaultColor=n;break;case d.HIGHLIGHT_THICKNESS:e._defaultThickness=n}}translateInPage(e,t){}get toolbarPosition(){return this.#p}get commentButtonPosition(){return this.#f}updateParams(e,t){switch(e){case d.HIGHLIGHT_COLOR:this.#b(t);break;case d.HIGHLIGHT_THICKNESS:this.#x(t)}}static get defaultPropertiesToUpdate(){return[[d.HIGHLIGHT_COLOR,e._defaultColor],[d.HIGHLIGHT_THICKNESS,e._defaultThickness]]}get propertiesToUpdate(){return[[d.HIGHLIGHT_COLOR,this.color||e._defaultColor],[d.HIGHLIGHT_THICKNESS,this.#g||e._defaultThickness],[d.HIGHLIGHT_FREE,this.#d]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#u,{root:{fill:this.color,"fill-opacity":this.opacity}}),this.#i?.updateColor(this.color),super.onUpdatedColor()}#b(t){let n=(e,t)=>{this.color=e,this.opacity=t,this.onUpdatedColor()},r=this.color,i=this.opacity;this.addCommands({cmd:n.bind(this,t,e._defaultOpacity),undo:n.bind(this,r,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:`color_changed`,color:this._uiManager.getNonHCMColorName(t)},!0)}#x(e){let t=this.#g,n=e=>{this.#g=e,this.#S(e)};this.addCommands({cmd:n.bind(this,e),undo:n.bind(this,t),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:`thickness_changed`,thickness:e},!0)}get toolbarButtons(){return this._uiManager.highlightColors?[[`colorPicker`,this.#i=new Vr({editor:this})]]:super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle(`disabled`,!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle(`disabled`,!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#O())}getBaseTranslation(){return[0,0]}getRect(e,t){return super.getRect(e,t,this.#O())}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),e&&this.div.focus()}remove(){this.#C(),this._reportTelemetry({action:`deleted`}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#w(),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){let t=!1;this.parent&&!e?this.#C():e&&(this.#w(e),t=!this.parent&&this.div?.classList.contains(`selectedEditor`)),super.setParent(e),this.show(this._isVisible),t&&this.select()}#S(e){this.#d&&(this.#y({highlightOutlines:this.#l.getNewOutline(e/2)}),this.fixAndSetPosition(),this.setDims())}#C(){this.#u===null||!this.parent||(this.parent.drawLayer.remove(this.#u),this.#u=null,this.parent.drawLayer.remove(this.#m),this.#m=null)}#w(e=this.parent){this.#u===null&&({id:this.#u,clipPathId:this.#r}=e.drawLayer.draw({bbox:this.#l.box,root:{viewBox:`0 0 1 1`,fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#d},path:{d:this.#l.toSVGPath()}},!1,!0),this.#m=e.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#d},bbox:this.#a.box,path:{d:this.#a.toSVGPath()}},this.#d),this.#c&&(this.#c.style.clipPath=this.#r))}static#T([e,t,n,r],i){switch(i){case 90:return[1-t-r,e,r,n];case 180:return[1-e-n,1-t-r,n,r];case 270:return[t,1-e-n,r,n]}return[e,t,n,r]}rotate(t){let{drawLayer:n}=this.parent,r;this.#d?(t=(t-this.rotation+360)%360,r=e.#T(this.#l.box,t)):r=e.#T([this.x,this.y,this.width,this.height],t),n.updateProperties(this.#u,{bbox:r,root:{"data-main-rotation":t}}),n.updateProperties(this.#m,{bbox:e.#T(this.#a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;let e=super.render();this.#h&&(e.setAttribute(`aria-label`,this.#h),e.setAttribute(`role`,`mark`)),this.#d?e.classList.add(`free`):this.div.addEventListener(`keydown`,this.#E.bind(this),{signal:this._uiManager._signal});let t=this.#c=document.createElement(`div`);return e.append(t),t.setAttribute(`aria-hidden`,`true`),t.className=`internal`,t.style.clipPath=this.#r,this.setDims(),Qe(this,this.#c,[`pointerover`,`pointerleave`]),this.enableEditing(),e}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!1}})}#E(t){e._keyboardManager.exec(this,t)}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:this.#D(!0);break;case 1:case 3:this.#D(!1)}}#D(e){if(!this.#e)return;let t=window.getSelection();e?t.setPosition(this.#e,this.#t):t.setPosition(this.#o,this.#s)}select(){super.select(),this.#m&&this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#m&&(this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{selected:!1}}),this.#d||this.#D(!1))}get _mustFixPosition(){return!this.#d}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.updateProperties(this.#u,{rootClass:{hidden:!e}}),this.parent.drawLayer.updateProperties(this.#m,{rootClass:{hidden:!e}}))}#O(){return this.#d?this.rotation:0}#k(){if(this.#d)return null;let[e,t]=this.pageDimensions,[n,r]=this.pageTranslation,i=this.#n,a=new Float32Array(i.length*8),o=0;for(let{x:s,y:c,width:l,height:u}of i){let i=s*e+n,d=(1-c)*t+r;a[o]=a[o+4]=i,a[o+1]=a[o+3]=d,a[o+2]=a[o+6]=i+l*e,a[o+5]=a[o+7]=d-u*t,o+=8}return a}#A(e){return this.#l.serialize(e,this.#O())}static startHighlighting(e,t,{target:n,x:r,y:i}){let{x:a,y:o,width:s,height:c}=n.getBoundingClientRect(),l=new AbortController,u=e.combinedSignal(l),d=t=>{l.abort(),this.#M(e,t)};window.addEventListener(`blur`,d,{signal:u}),window.addEventListener(`pointerup`,d,{signal:u}),window.addEventListener(`pointerdown`,z,{capture:!0,passive:!1,signal:u}),window.addEventListener(`contextmenu`,R,{signal:u}),n.addEventListener(`pointermove`,this.#j.bind(this,e),{signal:u}),this._freeHighlight=new Mi({x:r,y:i},[a,o,s,c],e.scale,this._defaultThickness/2,t,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:`0 0 1 1`,fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static#j(e,t){this._freeHighlight.add(t)&&e.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#M(e,t){this._freeHighlight.isEmpty()?e.drawLayer.remove(this._freeHighlightId):e.createAndAddNewEditor(t,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:`main_toolbar`}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=``}static async deserialize(e,t,n){let r=null;if(e instanceof vi){let{data:{quadPoints:t,rect:n,rotation:i,id:a,color:o,opacity:s,popupRef:c,richText:l,contentsObj:d,creationDate:f,modificationDate:p},parent:{page:{pageNumber:m}}}=e;r=e={annotationType:u.HIGHLIGHT,color:Array.from(o),opacity:s,quadPoints:t,boxes:null,pageIndex:m-1,rect:n.slice(0),rotation:i,annotationElementId:a,id:a,deleted:!1,popupRef:c,richText:l,comment:d?.str||null,creationDate:f,modificationDate:p}}else if(e instanceof _i){let{data:{inkLists:t,rect:n,rotation:i,id:a,color:o,borderStyle:{rawWidth:s},popupRef:c,richText:l,contentsObj:d,creationDate:f,modificationDate:p},parent:{page:{pageNumber:m}}}=e;r=e={annotationType:u.HIGHLIGHT,color:Array.from(o),thickness:s,inkLists:t,boxes:null,pageIndex:m-1,rect:n.slice(0),rotation:i,annotationElementId:a,id:a,deleted:!1,popupRef:c,richText:l,comment:d?.str||null,creationDate:f,modificationDate:p}}let{color:i,quadPoints:a,inkLists:o,outlines:s,opacity:c}=e,l=await super.deserialize(e,t,n);l.color=I.makeHexColor(...i),l.opacity=c||1,o&&(l.#g=e.thickness),l._initialData=r,e.comment&&l.setCommentData(e);let[d,f]=l.pageDimensions,[p,m]=l.pageTranslation;if(a){let e=l.#n=[];for(let t=0;te!==t[n])}renderAnnotationElement(e){return this.deleted?(e.hide(),null):(e.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}},Fi=class{#e=Object.create(null);updateProperty(e,t){this[e]=t,this.updateSVGProperty(e,t)}updateProperties(e){if(e)for(let[t,n]of Object.entries(e))t.startsWith(`_`)||this.updateProperty(t,n)}updateSVGProperty(e,t){this.#e[e]=t}toSVGProperties(){let e=this.#e;return this.#e=Object.create(null),{root:e}}reset(){this.#e=Object.create(null)}updateAll(e=this){this.updateProperties(e)}clone(){E(`Not implemented`)}},Ii=class e extends U{#e=null;#t;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#n=null;static#r=null;static#i=null;static _INNER_MARGIN=3;constructor(e){super(e),this.#t=e.mustBeCommitted||!1,this._addOutlines(e)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(e){e.drawOutlines&&(this.#a(e),this.#c())}#a({drawOutlines:e,drawId:t,drawingOptions:n}){this.#e=e,this._drawingOptions||=n,this.annotationElementId||this._uiManager.a11yAlert(U._l10nAlert[this.editorType]),t>=0?(this._drawId=t,this.parent.drawLayer.finalizeDraw(t,e.defaultProperties)):this._drawId=this.#o(e,this.parent),this.#d(e.box)}#o(t,n){let{id:r}=n.drawLayer.draw(e._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return r}static _mergeSVGProperties(e,t){let n=new Set(Object.keys(e));for(let[r,i]of Object.entries(t))n.has(r)?Object.assign(e[r],i):e[r]=i;return e}static getDefaultDrawingOptions(e){E(`Not implemented`)}static get typesMap(){E(`Not implemented`)}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,n){let r=this.typesMap.get(t);r&&this._defaultDrawingOptions.updateProperty(r,n),this._currentParent&&(e.#n.updateProperty(r,n),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(e,t){let n=this.constructor.typesMap.get(e);n&&this._updateProperty(e,n,t)}static get defaultPropertiesToUpdate(){let e=[],t=this._defaultDrawingOptions;for(let[n,r]of this.typesMap)e.push([n,t[r]]);return e}get propertiesToUpdate(){let e=[],{_drawingOptions:t}=this;for(let[n,r]of this.constructor.typesMap)e.push([n,t[r]]);return e}_updateProperty(e,t,n){let r=this._drawingOptions,i=r[t],a=n=>{r.updateProperty(t,n);let i=this.#e.updateProperty(t,n);i&&this.#d(i),this.parent?.drawLayer.updateProperties(this._drawId,r.toSVGProperties()),e===this.colorType?this.onUpdatedColor():e===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:a.bind(this,n),undo:a.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:e,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(e,t){let n=this.constructor.typesMap.get(this.colorType),r=this.constructor.typesMap.get(this.opacityType),i=this._drawingOptions,a=i[n],o=i[r],s=(e,t)=>{i.updateProperty(n,e),i.updateProperty(r,t),this.#e.updateProperty(n,e),this.#e.updateProperty(r,t),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:s.bind(this,e,t),undo:s.bind(this,a,o),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathResizingSVGProperties(this.#u()),{bbox:this.#f()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathResizedSVGProperties(this.#u()),{bbox:this.#f()}))}_onTranslating(e,t){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#f()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathTranslatedSVGProperties(this.#u(),this.parentDimensions),{bbox:this.#f()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle(`disabled`,!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle(`disabled`,!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#t&&(this.#t=!1,this.commit(),this.parent.setSelected(this),e&&this.isOnScreen&&this.div.focus())}remove(){this.#s(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#c(),this.#d(this.#e.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){let t=!1;this.parent&&!e?(this._uiManager.removeShouldRescale(this),this.#s()):e&&(this._uiManager.addShouldRescale(this),this.#c(e),t=!this.parent&&this.div?.classList.contains(`selectedEditor`)),super.setParent(e),t&&this.select()}#s(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#c(e=this.parent){if(this._drawId===null||this.parent!==e){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,e.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#o(this.#e,e)}}#l([e,t,n,r]){let{parentDimensions:[i,a],rotation:o}=this;switch(o){case 90:return[t,1-e,a/i*n,i/a*r];case 180:return[1-e,1-t,n,r];case 270:return[1-t,e,a/i*n,i/a*r];default:return[e,t,n,r]}}#u(){let{x:e,y:t,width:n,height:r,parentDimensions:[i,a],rotation:o}=this;switch(o){case 90:return[1-t,e,i/a*n,a/i*r];case 180:return[1-e,1-t,n,r];case 270:return[t,1-e,i/a*n,a/i*r];default:return[e,t,n,r]}}#d(e){[this.x,this.y,this.width,this.height]=this.#l(e),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#f(){let{x:e,y:t,width:n,height:r,rotation:i,parentRotation:a,parentDimensions:[o,s]}=this;switch((i*4+a)/90){case 1:return[1-t-r,e,r,n];case 2:return[1-e-n,1-t-r,n,r];case 3:return[t,1-e-n,r,n];case 4:return[e,t-o/s*n,s/o*r,o/s*n];case 5:return[1-t,e,o/s*n,s/o*r];case 6:return[1-e-s/o*r,1-t,s/o*r,o/s*n];case 7:return[t-o/s*n,1-e-s/o*r,o/s*n,s/o*r];case 8:return[e-n,t-r,n,r];case 9:return[1-t,e-n,r,n];case 10:return[1-e,1-t,n,r];case 11:return[t-r,1-e,r,n];case 12:return[e-s/o*r,t,s/o*r,o/s*n];case 13:return[1-t-o/s*n,e-s/o*r,o/s*n,s/o*r];case 14:return[1-e,1-t-o/s*n,s/o*r,o/s*n];case 15:return[t,1-e,o/s*n,s/o*r];default:return[e,t,n,r]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties({bbox:this.#f()},this.#e.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#d(this.#e.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let e,t;this._isCopy&&(e=this.x,t=this.y);let n=super.render();n.classList.add(`draw`);let r=document.createElement(`div`);return n.append(r),r.setAttribute(`aria-hidden`,`true`),r.className=`internal`,this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(e,t),n}static createDrawerInstance(e,t,n,r,i){E(`Not implemented`)}static startDrawing(t,n,r,i){let{target:a,offsetX:o,offsetY:s,pointerId:c,pointerType:l}=i;if(H.isInitializedAndDifferentPointerType(l))return;let{viewport:{rotation:u}}=t,{width:d,height:f}=a.getBoundingClientRect(),p=e.#r=new AbortController,m=t.combinedSignal(p);if(H.setPointer(l,c),window.addEventListener(`pointerup`,e=>{H.isSamePointerIdOrRemove(e.pointerId)&&this._endDraw(e)},{signal:m}),window.addEventListener(`pointercancel`,e=>{H.isSamePointerIdOrRemove(e.pointerId)&&this._currentParent.endDrawingSession()},{signal:m}),window.addEventListener(`pointerdown`,t=>{H.isSamePointerType(t.pointerType)&&(H.initializeAndAddPointerId(t.pointerId),e.#n.isCancellable()&&(e.#n.removeLastElement(),e.#n.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:m}),window.addEventListener(`contextmenu`,R,{signal:m}),a.addEventListener(`pointermove`,this._drawMove.bind(this),{signal:m}),a.addEventListener(`touchmove`,e=>{H.isSameTimeStamp(e.timeStamp)&&z(e)},{signal:m}),t.toggleDrawing(),n._editorUndoBar?.hide(),e.#n){t.drawLayer.updateProperties(this._currentDrawId,e.#n.startNew(o,s,d,f,u));return}n.updateUIForDefaultProperties(this),e.#n=this.createDrawerInstance(o,s,d,f,u),e.#i=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(e.#i.toSVGProperties(),e.#n.defaultSVGProperties),!0,!1)}static _drawMove(t){if(H.isSameTimeStamp(t.timeStamp),!e.#n)return;let{offsetX:n,offsetY:r,pointerId:i}=t;if(H.isSamePointerId(i)){if(H.isUsingMultiplePointers()){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,e.#n.add(n,r)),H.setTimeStamp(t.timeStamp),z(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,e.#n=null,e.#i=null,H.clearTimeStamp()),e.#r&&(e.#r.abort(),e.#r=null,H.clearPointerIds())}static _endDraw(t){let n=this._currentParent;if(n){if(n.toggleDrawing(!0),this._cleanup(!1),t?.target===n.div&&n.drawLayer.updateProperties(this._currentDrawId,e.#n.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){let t=e.#n,r=this._currentDrawId,i=t.getLastElement();n.addCommands({cmd:()=>{n.drawLayer.updateProperties(r,t.setLastElement(i))},undo:()=>{n.drawLayer.updateProperties(r,t.removeLastElement())},mustExec:!1,type:d.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){let n=this._currentParent;if(!n)return null;if(n.toggleDrawing(!0),n.cleanUndoStack(d.DRAW_STEP),!e.#n.isEmpty()){let{pageDimensions:[r,i],scale:a}=n,o=n.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:e.#n.getOutlines(r*a,i*a,a,this._INNER_MARGIN),drawingOptions:e.#i,mustBeCommitted:!t});return this._cleanup(!0),o}return n.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(e){}static deserializeDraw(e,t,n,r,i,a){E(`Not implemented`)}static async deserialize(e,t,n){let{rawDims:{pageWidth:r,pageHeight:i,pageX:a,pageY:o}}=t.viewport,s=this.deserializeDraw(a,o,r,i,this._INNER_MARGIN,e),c=await super.deserialize(e,t,n);return c.createDrawingOptions(e),c.#a({drawOutlines:s}),c.#c(),c.onScaleChanging(),c.rotate(),c}serializeDraw(e){let[t,n]=this.pageTranslation,[r,i]=this.pageDimensions;return this.#e.serialize([t,n,r,i],e)}renderAnnotationElement(e){return e.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}},Li=class{#e=new Float64Array(6);#t;#n;#r;#i;#a;#o=``;#s=0;#c=new Ri;#l;#u;constructor(e,t,n,r,i,a){this.#l=n,this.#u=r,this.#r=i,this.#i=a,[e,t]=this.#d(e,t);let o=this.#t=[NaN,NaN,NaN,NaN,e,t];this.#a=[e,t],this.#n=[{line:o,points:this.#a}],this.#e.set(o,0)}updateProperty(e,t){e===`stroke-width`&&(this.#i=t)}#d(e,t){return $._normalizePoint(e,t,this.#l,this.#u,this.#r)}isEmpty(){return!this.#n?.length}isCancellable(){return this.#a.length<=10}add(e,t){[e,t]=this.#d(e,t);let[n,r,i,a]=this.#e.subarray(2,6),o=e-i,s=t-a;return Math.hypot(this.#l*o,this.#u*s)<=2?null:(this.#a.push(e,t),isNaN(n)?(this.#e.set([i,a,e,t],2),this.#t.push(NaN,NaN,NaN,NaN,e,t),{path:{d:this.toSVGPath()}}):(isNaN(this.#e[0])&&this.#t.splice(6,6),this.#e.set([n,r,i,a,e,t],0),this.#t.push(...$.createBezierPoints(n,r,i,a,e,t)),{path:{d:this.toSVGPath()}}))}end(e,t){return this.add(e,t)||(this.#a.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(e,t,n,r,i){this.#l=n,this.#u=r,this.#r=i,[e,t]=this.#d(e,t);let a=this.#t=[NaN,NaN,NaN,NaN,e,t];this.#a=[e,t];let o=this.#n.at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),this.#n.push({line:a,points:this.#a}),this.#e.set(a,0),this.#s=0,this.toSVGPath(),null}getLastElement(){return this.#n.at(-1)}setLastElement(e){return this.#n?(this.#n.push(e),this.#t=e.line,this.#a=e.points,this.#s=0,{path:{d:this.toSVGPath()}}):this.#c.setLastElement(e)}removeLastElement(){if(!this.#n)return this.#c.removeLastElement();this.#n.pop(),this.#o=``;for(let e=0,t=this.#n.length;ee??NaN),u,d,f,p),points:m(o[e].map(e=>e??NaN),u,d,f,p)});let h=new this.prototype.constructor;return h.build(l,n,r,1,s,c,i),h}#l(e=this.#c){let t=this.#n+e/2*this.#o;return this.#s%180==0?[t/this.#i,t/this.#a]:[t/this.#a,t/this.#i]}#u(){let[e,t,n,r]=this.#e,[i,a]=this.#l(0);return[e+i,t+a,n-2*i,r-2*a]}#d(){let e=this.#e=r.slice();for(let{line:t}of this.#r){if(t.length<=12){for(let n=4,r=t.length;ne!==t[n])||e.thickness!==n||e.opacity!==r||e.pageIndex!==i}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let{points:t,rect:n}=this.serializeDraw(!1);return e.updateEdited({rect:n,thickness:this._drawingOptions[`stroke-width`],points:t,popup:this.comment}),null}},Vi=class extends Ri{toSVGPath(){let e=super.toSVGPath();return e.endsWith(`Z`)||(e+=`Z`),e}},Hi=8,Ui=3,Wi=class{static#e={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#t(e,t,n,r){return n-=e,r-=t,n===0?r>0?0:4:n===1?r+6:2-r}static#n=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#r(e,t,n,r,i,a,o){let s=this.#t(n,r,i,a);for(let i=0;i<8;i++){let a=(-i+s-o+16)%8,c=this.#n[2*a],l=this.#n[2*a+1];if(e[(n+c)*t+(r+l)]!==0)return a}return-1}static#i(e,t,n,r,i,a,o){let s=this.#t(n,r,i,a);for(let i=0;i<8;i++){let a=(i+s+o+16)%8,c=this.#n[2*a],l=this.#n[2*a+1];if(e[(n+c)*t+(r+l)]!==0)return a}return-1}static#a(e,t,n,r){let i=e.length,a=new Int32Array(i);for(let t=0;t=1&&a[r+1]===0)o+=1,u+=1,i>1&&(s=i);else{i!==1&&(s=Math.abs(i));continue}let d=[n,e],f=u===n+1,p={isHole:f,points:d,id:o,parent:0};c.push(p);let m;for(let e of c)if(e.id===s){m=e;break}p.parent=m?m.isHole?f?m.parent:s:f?s:m.parent:f?s:0;let h=this.#r(a,t,e,n,l,u,0);if(h===-1){a[r]=-o,a[r]!==1&&(s=Math.abs(a[r]));continue}let g=this.#n[2*h],_=this.#n[2*h+1],v=e+g,y=n+_;l=v,u=y;let b=e,x=n;for(;;){let i=this.#i(a,t,b,x,l,u,1);g=this.#n[2*i],_=this.#n[2*i+1];let c=b+g,f=x+_;d.push(f,c);let p=b*t+x;if(a[p+1]===0?a[p]=-o:a[p]===1&&(a[p]=o),c===e&&f===n&&b===v&&x===y){a[r]!==1&&(s=Math.abs(a[r]));break}l=b,u=x,b=c,x=f}}}return c}static#o(e,t,n,r){if(n-t<=4){for(let i=t;ib&&(x=r,b=t)}b>(c*y)**2?(this.#o(e,t,x+2,r),this.#o(e,x,n,r)):r.push(i,a)}static#s(e){let t=[],n=e.length;return this.#o(e,0,n,t),t.push(e[n-2],e[n-1]),t.length<=4?null:t}static#c(e,t,n,r,i,a){let o=new Float32Array(a**2),s=-2*r**2,c=a>>1;for(let e=0;e=n))for(let n=0;n=t)continue;let p=e[f*t+r],h=o[s*a+n]*l[Math.abs(p-u)];d+=p*h,m+=h}}let h=f[s]=Math.round(d/m);p[h]++}return[f,p]}static#l(e){let t=new Uint32Array(256);for(let n of e)t[n]++;return t}static#u(e){let t=e.length,n=new Uint8ClampedArray(t>>2),r=-1/0,i=1/0;for(let t=0,a=n.length;te!==0),a=i,o=i;for(t=i;t<256;t++){let i=e[t];i>n&&(t-a>r&&(r=t-a,o=t-1),n=i,a=t)}for(t=o-1;t>=0&&!(e[t]>e[t+1]);t--);return t}static#f(e){let t=e,{width:n,height:r}=e,{maxDim:i}=this.#e,a=n,o=r;if(n>i||r>i){let s=n,c=r,l=Math.log2(Math.max(n,r)/i),u=Math.floor(l);l=l===u?u-1:u;for(let n=0;n=-128&&o<=127?Int8Array:a>=-32768&&o<=32767?Int16Array:Int32Array;let l=e.length,u=Hi+Ui*l,d=new Uint32Array(u),f=0;d[f++]=u*Uint32Array.BYTES_PER_ELEMENT+(s-2*l)*c.BYTES_PER_ELEMENT,d[f++]=0,d[f++]=r,d[f++]=i,d[f++]=+!t,d[f++]=Math.max(0,Math.floor(n??0)),d[f++]=l,d[f++]=c.BYTES_PER_ELEMENT;for(let t of e)d[f++]=t.length-2,d[f++]=t[0],d[f++]=t[1];let p=new CompressionStream(`deflate-raw`),m=p.writable.getWriter();await m.ready,m.write(d);let h=c.prototype.constructor;for(let t of e){let e=new h(t.length-2);for(let n=2,r=t.length;n{await i.ready,await i.close()}).catch(()=>{});let a=null,o=0;for await(let e of n)a||=new Uint8Array(new Uint32Array(e.buffer,0,4)[0]),a.set(e,o),o+=e.length;let s=new Uint32Array(a.buffer,0,a.length>>2),c=s[1];if(c!==0)throw Error(`Invalid version: ${c}`);let l=s[2],u=s[3],d=s[4]===0,f=s[5],p=s[6],m=s[7],h=[],g=(Hi+Ui*p)*Uint32Array.BYTES_PER_ELEMENT,_;switch(m){case Int8Array.BYTES_PER_ELEMENT:_=new Int8Array(a.buffer,g);break;case Int16Array.BYTES_PER_ELEMENT:_=new Int16Array(a.buffer,g);break;case Int32Array.BYTES_PER_ELEMENT:_=new Int32Array(a.buffer,g)}o=0;for(let e=0;e{t?.updateEditSignatureButton(e)}))}getSignaturePreview(){let{newCurves:e,areContours:t,thickness:n,width:r,height:i}=this.#n,a=Math.max(r,i);return{areContours:t,outline:Wi.processDrawnLines({lines:{curves:e.map(e=>({points:e})),thickness:n,width:r,height:i},pageWidth:a,pageHeight:a,rotation:0,innerMargin:0,mustSmooth:!1,areContours:t}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[[`editSignature`,this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,n,r,i){let{x:a,y:o}=this,{outline:s}=this.#n=t;this.#e=s instanceof Vi,this.description=r;let c;this.#e?c=e.getDefaultDrawingOptions():(c=e._defaultDrawnSignatureOptions.clone(),c.updateProperties({"stroke-width":s.thickness})),this._addOutlines({drawOutlines:s,drawingOptions:c});let[,l]=this.pageDimensions,u=n/l;u=u>=1?.5:u,this.width*=u/this.height,this.width>=1&&(u*=.9/this.width,this.width=.9),this.height=u,this.setDims(),this.x=a,this.y=o,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(i),this._reportTelemetry({action:`pdfjs.signature.inserted`,data:{hasBeenSaved:!!i,hasDescription:!!r}}),this.div.hidden=!1}getFromImage(t){let{rawDims:{pageWidth:n,pageHeight:r},rotation:i}=this.parent.viewport;return Wi.process(t,n,r,i,e._INNER_MARGIN)}getFromText(t,n){let{rawDims:{pageWidth:r,pageHeight:i},rotation:a}=this.parent.viewport;return Wi.extractContoursFromText(t,n,r,i,a,e._INNER_MARGIN)}getDrawnSignature(t){let{rawDims:{pageWidth:n,pageHeight:r},rotation:i}=this.parent.viewport;return Wi.processDrawnLines({lines:t,pageWidth:n,pageHeight:r,rotation:i,innerMargin:e._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:n}){t?this._drawingOptions=e.getDefaultDrawingOptions():(this._drawingOptions=e._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":n}))}serialize(e=!1){if(this.isEmpty())return null;let{lines:t,points:n}=this.serializeDraw(e),{_drawingOptions:{"stroke-width":r}}=this,i=Object.assign(super.serialize(e),{isSignature:!0,areContours:this.#e,color:[0,0,0],thickness:this.#e?0:r});return this.addComment(i),e?(i.paths={lines:t,points:n},i.uuid=this.#r,i.isCopy=!0):i.lines=t,this.#t&&(i.accessibilityData={type:`Figure`,alt:this.#t}),i}static deserializeDraw(e,t,n,r,i,a){return a.areContours?Vi.deserialize(e,t,n,r,i,a):Ri.deserialize(e,t,n,r,i,a)}static async deserialize(e,t,n){let r=await super.deserialize(e,t,n);return r.#e=e.areContours,r.description=e.accessibilityData?.alt||``,r.#r=e.uuid,r}},Ji=class extends U{#e=null;#t=null;#n=null;#r=null;#i=null;#a=``;#o=null;#s=!1;#c=null;#l=!1;#u=!1;static _type=`stamp`;static _editorType=u.STAMP;constructor(e){super({...e,name:`stampEditor`}),this.#r=e.bitmapUrl,this.#i=e.bitmapFile,this.defaultL10nId=`pdfjs-editor-stamp-editor`}static initialize(e,t){U.initialize(e,t)}static isHandlingMimeForPasting(e){return Le.includes(e)}static paste(e,t){t.pasteEditor({mode:u.STAMP},{bitmapFile:e.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:`stamp`,hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(e){let t=e.get(`hasAltText`);return{hasAltText:t.get(!0)??0,hasNoAltText:t.get(!1)??0}}#d(e,t=!1){if(!e){this.remove();return}this.#e=e.bitmap,t||(this.#t=e.id,this.#l=e.isSvg),e.file&&(this.#a=e.file.name),this.#m()}#f(){if(this.#n=null,this._uiManager.enableWaiting(!1),this.#o){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this._reportTelemetry({action:`pdfjs.image.image_added`,data:{alt_text_modal:!1,alt_text_type:`empty`}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(e=null,t=!0){if(this.hasAltTextData())return null;let{mlManager:n}=this._uiManager;if(!n)throw Error(`No ML.`);if(!await n.isEnabledFor(`altText`))throw Error(`ML isn't enabled for alt text.`);let{data:r,width:i,height:a}=e||this.copyCanvas(null,null,!0).imageData,o=await n.guess({name:`altText`,request:{data:r,width:i,height:a,channels:r.length/(i*a)}});if(!o)throw Error(`No response from the AI service.`);if(o.error)throw Error(`Error from the AI service.`);if(o.cancel)return null;if(!o.output)throw Error(`No valid response from the AI service.`);let s=o.output;return await this.setGuessedAltText(s),t&&!this.hasAltTextData()&&(this.altTextData={alt:s,decorative:!1}),s}#p(){if(this.#t){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#t).then(e=>this.#d(e,!0)).finally(()=>this.#f());return}if(this.#r){let e=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromUrl(e).then(e=>this.#d(e)).finally(()=>this.#f());return}if(this.#i){let e=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromFile(e).then(e=>this.#d(e)).finally(()=>this.#f());return}let e=document.createElement(`input`);e.type=`file`,e.accept=Le.join(`,`);let t=this._uiManager._signal;this.#n=new Promise(n=>{e.addEventListener(`change`,async()=>{if(!e.files||e.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);let t=await this._uiManager.imageManager.getFromFile(e.files[0]);this._reportTelemetry({action:`pdfjs.image.image_selected`,data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#d(t)}n()},{signal:t}),e.addEventListener(`cancel`,()=>{this.remove(),n()},{signal:t})}).finally(()=>this.#f()),e.click()}remove(){this.#t&&(this.#e=null,this._uiManager.imageManager.deleteId(this.#t),this.#o?.remove(),this.#o=null,this.#c&&=(clearTimeout(this.#c),null)),super.remove()}rebuild(){if(!this.parent){this.#t&&this.#p();return}super.rebuild(),this.div!==null&&(this.#t&&this.#o===null&&this.#p(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(e){this._isDraggable=!0,e&&this.div.focus()}isEmpty(){return!(this.#n||this.#e||this.#r||this.#i||this.#t||this.#s)}get toolbarButtons(){return[[`altText`,this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let e,t;return this._isCopy&&(e=this.x,t=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#s||(this.#e?this.#m():this.#p()),this._isCopy&&this._moveAfterPaste(e,t),this._uiManager.addShouldRescale(this),this.div}setCanvas(e,t){let{id:n,bitmap:r}=this._uiManager.imageManager.getFromCanvas(e,t);t.remove(),n&&this._uiManager.imageManager.isValidId(n)&&(this.#t=n,r&&(this.#e=r),this.#s=!1,this.#m())}_onResized(){this.onScaleChanging()}onScaleChanging(){this.parent&&(this.#c!==null&&clearTimeout(this.#c),this.#c=setTimeout(()=>{this.#c=null,this.#g()},200))}#m(){let{div:e}=this,{width:t,height:n}=this.#e,[r,i]=this.pageDimensions,a=.75;if(this.width)t=this.width*r,n=this.height*i;else if(t>a*r||n>a*i){let e=Math.min(a*r/t,a*i/n);t*=e,n*=e}this._uiManager.enableWaiting(!1);let o=this.#o=document.createElement(`canvas`);o.setAttribute(`role`,`img`),this.addContainer(o),this.width=t/r,this.height=n/i,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(e.hidden=!1),this.#g(),this.#u||=(this.parent.addUndoableEditor(this),!0),this._reportTelemetry({action:`inserted_image`}),this.#a&&this.div.setAttribute(`aria-description`,this.#a),this.annotationElementId||this._uiManager.a11yAlert(U._l10nAlert.stamp)}copyCanvas(e,t,n=!1){e||=224;let{width:r,height:i}=this.#e,a=new Ie,o=this.#e,s=r,c=i,l=null;if(t){if(r>t||i>t){let e=Math.min(t/r,t/i);s=Math.floor(r*e),c=Math.floor(i*e)}l=document.createElement(`canvas`);let e=l.width=Math.ceil(s*a.sx),n=l.height=Math.ceil(c*a.sy);this.#l||(o=this.#h(e,n));let u=l.getContext(`2d`);u.filter=this._uiManager.hcmFilter;let d=`white`,f=`#cfcfd8`;this._uiManager.hcmFilter===`none`?Re.isDarkMode&&(d=`#8f8f9d`,f=`#42414d`):f=`black`;let p=15*a.sx,m=15*a.sy,h=new OffscreenCanvas(p*2,m*2),g=h.getContext(`2d`);g.fillStyle=d,g.fillRect(0,0,p*2,m*2),g.fillStyle=f,g.fillRect(0,0,p,m),g.fillRect(p,m,p,m),u.fillStyle=u.createPattern(h,`repeat`),u.fillRect(0,0,e,n),u.drawImage(o,0,0,o.width,o.height,0,0,e,n)}let u=null;if(n){let t,n;if(a.symmetric&&o.widthe||i>e){let a=Math.min(e/r,e/i);t=Math.floor(r*a),n=Math.floor(i*a),this.#l||(o=this.#h(t,n))}let s=new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0});s.drawImage(o,0,0,o.width,o.height,0,0,t,n),u={width:t,height:n,data:s.getImageData(0,0,t,n).data}}return{canvas:l,width:s,height:c,imageData:u}}#h(e,t){let{width:n,height:r}=this.#e,i=n,a=r,o=this.#e;for(;i>2*e||a>2*t;){let n=i,r=a;i>2*e&&(i=Math.ceil(i/2)),a>2*t&&(a=Math.ceil(a/2));let s=new OffscreenCanvas(i,a);s.getContext(`2d`).drawImage(o,0,0,n,r,0,0,i,a),o=s.transferToImageBitmap()}return o}#g(){let[e,t]=this.parentDimensions,{width:n,height:r}=this,i=new Ie,a=Math.ceil(n*e*i.sx),o=Math.ceil(r*t*i.sy),s=this.#o;if(!s||s.width===a&&s.height===o)return;s.width=a,s.height=o;let c=this.#l?this.#e:this.#h(a,o),l=s.getContext(`2d`);l.filter=this._uiManager.hcmFilter,l.drawImage(c,0,0,c.width,c.height,0,0,a,o)}#_(e){if(e){if(this.#l){let e=this._uiManager.imageManager.getSvgUrl(this.#t);if(e)return e}let e=document.createElement(`canvas`);return{width:e.width,height:e.height}=this.#e,e.getContext(`2d`).drawImage(this.#e,0,0),e.toDataURL()}if(this.#l){let[e,t]=this.pageDimensions,n=Math.round(this.width*e*Se.PDF_TO_CSS_UNITS),r=Math.round(this.height*t*Se.PDF_TO_CSS_UNITS),i=new OffscreenCanvas(n,r);return i.getContext(`2d`).drawImage(this.#e,0,0,this.#e.width,this.#e.height,0,0,n,r),i.transferToImageBitmap()}return structuredClone(this.#e)}static async deserialize(e,t,n){let r=null,i=!1;if(e instanceof Si){let{data:{rect:a,rotation:o,id:s,structParent:l,popupRef:d,richText:f,contentsObj:p,creationDate:m,modificationDate:h},container:g,parent:{page:{pageNumber:_}},canvas:v}=e,y,b;v?(delete e.canvas,{id:y,bitmap:b}=n.imageManager.getFromCanvas(g.id,v),v.remove()):(i=!0,e._hasNoCanvas=!0);let x=(await t._structTree.getAriaAttributes(`${c}${s}`))?.get(`aria-label`)||``;r=e={annotationType:u.STAMP,bitmapId:y,bitmap:b,pageIndex:_-1,rect:a.slice(0),rotation:o,annotationElementId:s,id:s,deleted:!1,accessibilityData:{decorative:!1,altText:x},isSvg:!1,structParent:l,popupRef:d,richText:f,comment:p?.str||null,creationDate:m,modificationDate:h}}let a=await super.deserialize(e,t,n),{rect:o,bitmap:s,bitmapUrl:l,bitmapId:d,isSvg:f,accessibilityData:p}=e;i?(n.addMissingCanvas(e.id,a),a.#s=!0):d&&n.imageManager.isValidId(d)?(a.#t=d,s&&(a.#e=s)):a.#r=l,a.#l=f;let[m,h]=a.pageDimensions;return a.width=(o[2]-o[0])/m,a.height=(o[3]-o[1])/h,p&&(a.altTextData=p),a._initialData=r,e.comment&&a.setCommentData(e),a.#u=!!r,a}serialize(e=!1,t=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let n=Object.assign(super.serialize(e),{bitmapId:this.#t,isSvg:this.#l});if(this.addComment(n),e)return n.bitmapUrl=this.#_(!0),n.accessibilityData=this.serializeAltText(!0),n.isCopy=!0,n;let{decorative:r,altText:i}=this.serializeAltText(!1);if(!r&&i&&(n.accessibilityData={type:`Figure`,alt:i}),this.annotationElementId){let e=this.#v(n);return e.isSame?null:(e.isSameAltText?delete n.accessibilityData:n.accessibilityData.structParent=this._initialData.structParent??-1,n.id=this.annotationElementId,delete n.bitmapId,n)}if(t===null)return n;t.stamps||=new Map;let a=this.#l?(n.rect[2]-n.rect[0])*(n.rect[3]-n.rect[1]):null;if(!t.stamps.has(this.#t))t.stamps.set(this.#t,{area:a,serialized:n}),n.bitmap=this.#_(!1);else if(this.#l){let e=t.stamps.get(this.#t);a>e.area&&(e.area=a,e.serialized.bitmap.close(),e.serialized.bitmap=this.#_(!1))}return n}#v(e){let{pageIndex:t,accessibilityData:{altText:n}}=this._initialData,r=e.pageIndex===t,i=(e.accessibilityData?.alt||``)===n;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&r&&i,isSameAltText:i}}renderAnnotationElement(e){return this.deleted?(e.hide(),null):(e.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}},Yi=class e{#e;#t=!1;#n=null;#r=null;#i=null;#a=new Map;#o=!1;#s=!1;#c=!1;#l=null;#u=null;#d=null;#f=null;#p=null;#m=-1;#h;static _initialized=!1;static#g=new Map([Di,Bi,Ji,Pi,qi].map(e=>[e._editorType,e]));constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:i,accessibilityManager:a,annotationLayer:o,drawLayer:s,textLayer:c,viewport:l,l10n:u}){let d=[...e.#g.values()];if(!e._initialized){e._initialized=!0;for(let e of d)e.initialize(u,t)}t.registerEditorTypes(d),this.#h=t,this.pageIndex=n,this.div=r,this.#e=a,this.#n=o,this.viewport=l,this.#d=c,this.drawLayer=s,this._structTree=i,this.#h.addLayer(this)}get isEmpty(){return this.#a.size===0}get isInvisible(){return this.isEmpty&&this.#h.getMode()===u.NONE}updateToolbar(e){this.#h.updateToolbar(e)}updateMode(t=this.#h.getMode()){switch(this.#S(),t){case u.NONE:this.div.classList.toggle(`nonEditing`,!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case u.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case u.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:n}=this.div;if(n.toggle(`nonEditing`,!1),t===u.POPUP)n.toggle(`commentEditing`,!0);else{n.toggle(`commentEditing`,!1);for(let r of e.#g.values())n.toggle(`${r._type}Editing`,t===r._editorType)}this.div.hidden=!1}hasTextLayer(e){return e===this.#d?.div}setEditingState(e){this.#h.setEditingState(e)}addCommands(e){this.#h.addCommands(e)}cleanUndoStack(e){this.#h.cleanUndoStack(e)}toggleDrawing(e=!1){this.div.classList.toggle(`drawing`,!e)}togglePointerEvents(e=!1){this.div.classList.toggle(`disabled`,!e)}toggleAnnotationLayerPointerEvents(e=!1){this.#n?.togglePointerEvents(e)}get#_(){return this.#a.size===0?this.#h.getEditors(this.pageIndex):this.#a.values()}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle(`nonEditing`,!1),this.#p?.abort(),this.#p=null;let e=new Set;for(let t of this.#_)t.enableEditing(),t.show(!0),t.annotationElementId&&(this.#h.removeChangedExistingAnnotation(t),e.add(t.annotationElementId));let t=this.#n;if(t)for(let n of t.getEditableAnnotations()){if(n.hide(),this.#h.isDeletedAnnotationElement(n.data.id)||e.has(n.data.id))continue;let t=await this.deserialize(n);t&&(this.addOrRebuild(t),t.enableEditing())}this.#c=!1,this.#h._eventBus.dispatch(`editorsrendered`,{source:this,pageNumber:this.pageIndex+1})}disable(){if(this.#s=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle(`nonEditing`,!0),this.#d&&!this.#p){this.#p=new AbortController;let e=this.#h.combinedSignal(this.#p);this.#d.div.addEventListener(`pointerdown`,e=>{let{clientX:t,clientY:n,timeStamp:r}=e;if(r-this.#m>500){this.#m=r;return}this.#m=-1;let{classList:i}=this.div;i.toggle(`getElements`,!0);let a=document.elementsFromPoint(t,n);if(i.toggle(`getElements`,!1),!this.div.contains(a[0]))return;let o,s=RegExp(`^${l}[0-9]+$`);for(let e of a)if(s.test(e.id)){o=e.id;break}if(!o)return;let c=this.#a.get(o);c?.annotationElementId===null&&(z(e),c.dblclick(e))},{signal:e,capture:!0})}let t=this.#n,n=[];if(t){let e=new Map,r=new Map;for(let t of this.#_){if(t.disableEditing(),!t.annotationElementId){n.push(t);continue}if(t.serialize()!==null){e.set(t.annotationElementId,t);continue}r.set(t.annotationElementId,t),this.getEditableAnnotation(t.annotationElementId)?.show(),t.remove()}for(let n of t.getEditableAnnotations()){let{id:t}=n.data;if(this.#h.isDeletedAnnotationElement(t)){n.updateEdited({deleted:!0});continue}let i=r.get(t);if(i){i.resetAnnotationElement(n),i.show(!1),n.show();continue}i=e.get(t),i&&(this.#h.addChangedExistingAnnotation(i),i.renderAnnotationElement(n)&&i.show(!1)),n.show()}}this.#S(),this.isEmpty&&(this.div.hidden=!0);let{classList:r}=this.div;for(let t of e.#g.values())r.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),t?.updateFakeAnnotations(n),this.#s=!1}getEditableAnnotation(e){return this.#n?.getEditableAnnotation(e)||null}setActiveEditor(e){this.#h.getActive()!==e&&this.#h.setActiveEditor(e)}enableTextSelection(){if(this.div.tabIndex=-1,this.#d?.div&&!this.#f){this.#f=new AbortController;let e=this.#h.combinedSignal(this.#f);this.#d.div.addEventListener(`pointerdown`,this.#v.bind(this),{signal:e}),this.#d.div.classList.add(`highlighting`)}}disableTextSelection(){this.div.tabIndex=0,this.#d?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#d.div.classList.remove(`highlighting`))}#v(e){this.#h.unselectAll();let{target:t}=e;if(t===this.#d.div||(t.getAttribute(`role`)===`img`||t.classList.contains(`endOfContent`)||t.classList.contains(`textLayerImages`)||t.classList.contains(`textLayerImagePlaceholder`))&&this.#d.div.contains(t)){let{isMac:t}=F.platform;if(e.button!==0||e.ctrlKey&&t)return;this.#h.showAllEditors(`highlight`,!0,!0),this.#d.div.classList.add(`free`),this.toggleDrawing(),Pi.startHighlighting(this,this.#h.direction===`ltr`,{target:this.#d.div,x:e.x,y:e.y}),this.#d.div.addEventListener(`pointerup`,()=>{this.#d.div.classList.remove(`free`),this.toggleDrawing(!0)},{once:!0,signal:this.#h._signal}),e.preventDefault()}}enableClick(){if(this.#r)return;this.#r=new AbortController;let e=this.#h.combinedSignal(this.#r);this.div.addEventListener(`pointerdown`,this.pointerdown.bind(this),{signal:e});let t=this.pointerup.bind(this);this.div.addEventListener(`pointerup`,t,{signal:e}),this.div.addEventListener(`pointercancel`,t,{signal:e})}disableClick(){this.#r?.abort(),this.#r=null}attach(e){this.#a.set(e.id,e);let{annotationElementId:t}=e;t&&this.#h.isDeletedAnnotationElement(t)&&this.#h.removeDeletedAnnotationElement(e)}detach(e){this.#a.delete(e.id),this.#e?.removePointerInTextLayer(e.contentDiv),!this.#s&&e.annotationElementId&&this.#h.addDeletedAnnotationElement(e)}remove(e){this.detach(e),this.#h.removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1}changeParent(e){e.parent!==this&&(e.parent&&e.annotationElementId&&(this.#h.addDeletedAnnotationElement(e),U.deleteAnnotationElement(e),e.annotationElementId=null),this.attach(e),e.parent?.detach(e),e.setParent(this),e.div&&e.isAttachedToDOM&&(e.div.remove(),this.div.append(e.div)))}add(e){if(!(e.parent===this&&e.isAttachedToDOM)){if(this.changeParent(e),this.#h.addEditor(e),this.attach(e),!e.isAttachedToDOM){let t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(!this.#c),this.#h.addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}}moveEditorInDOM(e){if(!e.isAttachedToDOM)return;let{activeElement:t}=document;e.div.contains(t)&&!this.#i&&(e._focusEventsAllowed=!1,this.#i=setTimeout(()=>{this.#i=null,e.div.contains(document.activeElement)?e._focusEventsAllowed=!0:(e.div.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this.#h._signal}),t.focus())},0)),e._structTreeParentId=this.#e?.moveElementInDOM(this.div,e.div,e.contentDiv,!0)}addOrRebuild(e){e.needsToBeRebuilt()?(e.parent||=this,e.rebuild(),e.show()):this.add(e)}addUndoableEditor(e){this.addCommands({cmd:()=>e._uiManager.rebuild(e),undo:()=>{e.remove()},mustExec:!1})}getEditorByUID(e){for(let t of this.#a.values())if(t.uid===e)return t;return null}get#y(){return e.#g.get(this.#h.getMode())}combinedSignal(e){return this.#h.combinedSignal(e)}#b(e){let t=this.#y;return t?new t.prototype.constructor(e):null}canCreateNewEmptyEditor(){return this.#y?.canCreateNewEmptyEditor()}async pasteEditor(e,t){this.updateToolbar(e),await this.#h.updateMode(e.mode);let{offsetX:n,offsetY:r}=this.#x(),i=this.#h.getId(),a=this.#b({parent:this,id:i,x:n,y:r,uiManager:this.#h,isCentered:!0,...t});a&&this.add(a)}async deserialize(t){return await e.#g.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#h)||null}createAndAddNewEditor(e,t,n={}){let r=this.#h.getId(),i=this.#b({parent:this,id:r,x:e.offsetX,y:e.offsetY,uiManager:this.#h,isCentered:t,...n});return i&&this.add(i),i}get boundingClientRect(){return this.div.getBoundingClientRect()}#x(){let{x:e,y:t,width:n,height:r}=this.boundingClientRect,i=Math.max(0,e),a=Math.max(0,t),o=Math.min(window.innerWidth,e+n),s=Math.min(window.innerHeight,t+r),c=(i+o)/2-e,l=(a+s)/2-t,[u,d]=this.viewport.rotation%180==0?[c,l]:[l,c];return{offsetX:u,offsetY:d}}addNewEditor(e={}){this.createAndAddNewEditor(this.#x(),!0,e)}setSelected(e){this.#h.setSelected(e)}toggleSelected(e){this.#h.toggleSelected(e)}unselect(e){this.#h.unselect(e)}pointerup(e){let{isMac:t}=F.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div||!this.#o||(this.#o=!1,this.#y?.isDrawer&&this.#y.supportMultipleDrawings))return;if(!this.#t){this.#t=!0;return}let n=this.#h.getMode();if(n===u.STAMP||n===u.POPUP||n===u.SIGNATURE){this.#h.unselectAll();return}this.createAndAddNewEditor(e,!1)}pointerdown(e){if(this.#h.getMode()===u.HIGHLIGHT&&this.enableTextSelection(),this.#o){this.#o=!1;return}let{isMac:t}=F.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div)return;if(this.#o=!0,this.#y?.isDrawer){this.startDrawingSession(e);return}let n=this.#h.getActive();this.#t=!n||n.isEmpty()}startDrawingSession(e){if(this.div.focus({preventScroll:!0}),this.#l){this.#y.startDrawing(this,this.#h,!1,e);return}this.#h.setCurrentDrawingSession(this),this.#l=new AbortController;let t=this.#h.combinedSignal(this.#l);this.div.addEventListener(`blur`,({relatedTarget:e})=>{e&&!this.div.contains(e)&&(this.#u=null,this.commitOrRemove())},{signal:t}),this.#y.startDrawing(this,this.#h,!1,e)}pause(e){if(e){let{activeElement:e}=document;this.div.contains(e)&&(this.#u=e);return}this.#u&&setTimeout(()=>{this.#u?.focus(),this.#u=null},0)}endDrawingSession(e=!1){return this.#l?(this.#h.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#u=null,this.#y.endDrawing(e)):null}findNewParent(e,t,n){let r=this.#h.findParent(t,n);return r===null||r===this?!1:(r.changeParent(e),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#y.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#h.getActive()?.parent===this&&(this.#h.commitOrRemove(),this.#h.setActiveEditor(null)),this.#i&&=(clearTimeout(this.#i),null);for(let e of this.#a.values())this.#e?.removePointerInTextLayer(e.contentDiv),e.setParent(null),e.isAttachedToDOM=!1,e.div.remove();this.div=null,this.#a.clear(),this.#h.removeLayer(this)}#S(){for(let e of this.#a.values())e.isEmpty()&&e.remove()}async render({viewport:e}){this.viewport=e,Fe(this.div,e);for(let e of this.#h.getEditors(this.pageIndex))this.add(e),e.rebuild();await this.#h.findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:e}){this.#h.commitOrRemove(),this.#S();let t=this.viewport.rotation,n=e.rotation;if(this.viewport=e,Fe(this.div,{rotation:n}),t!==n)for(let e of this.#a.values())e.rotate(n)}get pageDimensions(){let{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return this.#h.viewParameters.realScale}};function Xi(e,t){return e===t?0:e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function Zi(e){return e?e.nodeType===Node.ELEMENT_NODE?e.closest(`.textLayer`):e.parentElement?.closest(`.textLayer`)||null:null}function Qi(e,t,n,r){if(e===n)return t<=r;let i=e.compareDocumentPosition(n);return i&Node.DOCUMENT_POSITION_FOLLOWING?!0:i&Node.DOCUMENT_POSITION_PRECEDING?!1:null}function $i(e,t,n){if(e.nodeType!==Node.ELEMENT_NODE||!e.classList.contains(`textLayer`)||t!==e.childNodes.length)return{container:e,offset:t};let r=e.lastChild;return r?.nodeType===Node.ELEMENT_NODE&&r.classList.contains(`endOfContent`)&&(r=r.previousSibling),!r||!n.contains(r)?null:r.nodeType===Node.TEXT_NODE?{container:r,offset:r.textContent.length}:{container:r,offset:r.childNodes.length}}var ea=class e{#e=null;#t=new Map;#n=null;#r=null;#i=null;#a=null;#o=new Map;static#s=0;static#c=0;static#l=null;static#u=new Set;static#d=!1;static#f=new Set;static#p=new WeakMap;constructor({filterFactory:t=null,pageColors:n=null,pageIndex:r,textLayer:i=null}){if(this.pageIndex=r,this.#r=t,this.#i=n,i){let t=e.#p.get(i);if(t?.selectionDiv&&(t.selectionDiv.remove(),e.#u.delete(t.selectionDiv)),e.#p.set(i,{drawLayer:this}),e.#f.add(i),this.#n=i,this.#a=new MutationObserver(t=>{if(!(!this.#e||!this.#n?.isConnected||!e.#h())){for(let{addedNodes:n}of t)for(let t of n)if(t.nodeType===Node.ELEMENT_NODE&&t.classList.contains(`endOfContent`)){e.#_();return}}}),this.#a.observe(i,{childList:!0}),e.#l===null){e.#l=new AbortController;let{signal:t}=e.#l;document.addEventListener(`selectionchange`,e.#_.bind(e),{signal:t}),document.addEventListener(`pointerdown`,()=>{e.#d=!0},{signal:t}),document.addEventListener(`pointerup`,()=>{e.#d=!1},{signal:t}),window.addEventListener(`blur`,()=>{e.#d=!1},{signal:t})}}}setParent(t){if(!this.#e){this.#e=t,this.#n?.isConnected&&e.#h()&&e.#_();return}if(this.#e!==t){if(this.#t.size>0)for(let e of this.#t.values())e.remove(),t.append(e);this.#e=t}}static#m(e){let t=this.#p.get(e);t?.selectionDiv&&(t.selectionDiv.remove(),this.#u.delete(t.selectionDiv),t.selectionDiv=null,t.path=null)}static#h(){let e=document.getSelection();return!!e&&!e.isCollapsed}static#g(){return this.#f.keys().filter(e=>e.isConnected).toArray().sort(Xi)}static#_(){let t=document.getSelection();if(!t||t.isCollapsed){for(let e of this.#u)e.remove();this.#u.clear();return}let n=new WeakMap,r=this.#g(),i=[];for(let e=0,n=t.rangeCount;en.intersectsNode(e));if(p.length===0)continue;let m=!1;if(l||(l=p[0],a=l,o=0,m=!0),u||(u=p.at(-1),s=u,c=u.childNodes.length,m=!0),s.nodeType===Node.ELEMENT_NODE){if(s.classList.contains(`endOfContent`)){let e=s.previousSibling;if(!e)continue;s=e,c=e.nodeType===Node.TEXT_NODE?e.textContent.length:e.childNodes.length}else if(s.classList.contains(`textLayer`)&&s.childNodes.length===c){let e=$i(s,c,u);if(!e)continue;s=e.container,c=e.offset}}if(a.nodeType===Node.ELEMENT_NODE){let e=$i(a,o,l);if(!e)continue;a=e.container,o=e.offset}if(l===u&&!m&&p.includes(l)){i.push([n,l]);continue}for(let e of p){let t=e.firstChild;if(!t)continue;let n=document.createRange();if(e===l?n.setStart(a,o):n.setStartBefore(t),e===u)n.setEnd(s,c);else{let t=e.lastChild;if(!t)continue;if(t.nodeType===Node.ELEMENT_NODE&&t.classList.contains(`endOfContent`)){let e=t.previousSibling;if(!e)continue;n.setEndAfter(e)}else n.setEndAfter(t)}n.collapsed||i.push([n,e])}}let a=new Set(i.map(e=>e[1]));for(let e of this.#f)a.has(e)||this.#m(e);for(let[t,r]of i){let i=e.#p.get(r);if(!i)continue;let a=n.get(r);if(!a){let e=r.getBoundingClientRect();a=(t,n,r,i)=>({x:(t-e.x)/e.width,y:(n-e.y)/e.height,width:r/e.width,height:i/e.height}),n.set(r,a)}let o=[];for(let{x:e,y:n,width:r,height:i}of t.getClientRects())r!==0&&i!==0&&({x:e,y:n,width:r,height:i}=a(e,n,r,i),(r!==1||i!==1)&&o.push(`M${e} ${n} h${r} v${i} h-${r} Z`));if(o.length===0)continue;let s=i.drawLayer,c=i.selectionDiv,l=i.path;if(!c){let t=`clip_selection_${e.#c++}`;c=document.createElement(`div`),c.className=`selection`,c.style.clipPath=`url(#${t})`;let n=s.#r?.createSelectionStyle(s.#i);if(n)for(let[e,t]of Object.entries(n))c.style.setProperty(e,t);let r=e._svgFactory.create(1,1,!0);r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`width`,`100%`),r.setAttribute(`height`,`100%`);let a=e._svgFactory.createElement(`clipPath`);a.setAttribute(`id`,t),a.setAttribute(`clipPathUnits`,`objectBoundingBox`),l=e._svgFactory.createElement(`path`),a.append(l),r.append(a),c.append(r),i.path=l,i.selectionDiv=c}!c.parentNode&&s.#e&&(s.#e.append(c),this.#u.add(c)),l.setAttribute(`d`,o.join(` `))}}static get _svgFactory(){return M(this,`_svgFactory`,new qr)}static#v(e,[t,n,r,i]){let{style:a}=e;a.top=`${100*n}%`,a.left=`${100*t}%`,a.width=`${100*r}%`,a.height=`${100*i}%`}#y(){let t=e._svgFactory.create(1,1,!0);return this.#e.append(t),t.setAttribute(`aria-hidden`,`true`),t}#b(t,n){let r=e._svgFactory.createElement(`clipPath`);t.append(r);let i=`clip_${n}`;r.setAttribute(`id`,i),r.setAttribute(`clipPathUnits`,`objectBoundingBox`);let a=e._svgFactory.createElement(`use`);return r.append(a),a.setAttribute(`href`,`#${n}`),a.classList.add(`clip`),i}#x(e,t){for(let[n,r]of Object.entries(t))r===null?e.removeAttribute(n):e.setAttribute(n,r)}draw(t,n=!1,r=!1){let i=e.#s++,a=this.#y(),o=e._svgFactory.createElement(`defs`);a.append(o);let s=e._svgFactory.createElement(`path`);o.append(s);let c=`path_${i}`;s.setAttribute(`id`,c),s.setAttribute(`vector-effect`,`non-scaling-stroke`),n&&this.#o.set(i,s);let l=r?this.#b(o,c):null,u=e._svgFactory.createElement(`use`);return a.append(u),u.setAttribute(`href`,`#${c}`),this.updateProperties(a,t),this.#t.set(i,a),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,n){let r=e.#s++,i=this.#y(),a=e._svgFactory.createElement(`defs`);i.append(a);let o=e._svgFactory.createElement(`path`);a.append(o);let s=`path_${r}`;o.setAttribute(`id`,s),o.setAttribute(`vector-effect`,`non-scaling-stroke`);let c;if(n){let t=e._svgFactory.createElement(`mask`);a.append(t),c=`mask_${r}`,t.setAttribute(`id`,c),t.setAttribute(`maskUnits`,`objectBoundingBox`);let n=e._svgFactory.createElement(`rect`);t.append(n),n.setAttribute(`width`,`1`),n.setAttribute(`height`,`1`),n.setAttribute(`fill`,`white`);let i=e._svgFactory.createElement(`use`);t.append(i),i.setAttribute(`href`,`#${s}`),i.setAttribute(`stroke`,`none`),i.setAttribute(`fill`,`black`),i.setAttribute(`fill-rule`,`nonzero`),i.classList.add(`mask`)}let l=e._svgFactory.createElement(`use`);i.append(l),l.setAttribute(`href`,`#${s}`),c&&l.setAttribute(`mask`,`url(#${c})`);let u=l.cloneNode();return i.append(u),l.classList.add(`mainOutline`),u.classList.add(`secondaryOutline`),this.updateProperties(i,t),this.#t.set(r,i),r}finalizeDraw(e,t){this.#o.delete(e),this.updateProperties(e,t)}updateProperties(t,n){if(!n)return;let{root:r,bbox:i,rootClass:a,path:o}=n,s=typeof t==`number`?this.#t.get(t):t;if(s){if(r&&this.#x(s,r),i&&e.#v(s,i),a){let{classList:e}=s;for(let[t,n]of Object.entries(a))e.toggle(t,n)}if(o){let e=s.firstElementChild.firstElementChild;this.#x(e,o)}}}updateParent(e,t){if(t===this)return;let n=this.#t.get(e);n&&(t.#e.append(n),this.#t.delete(e),t.#t.set(e,n))}remove(e){this.#o.delete(e),this.#e!==null&&(this.#t.get(e).remove(),this.#t.delete(e))}destroy(){this.#e=null;for(let e of this.#t.values())e.remove();this.#t.clear(),this.#o.clear(),this.#a?.disconnect(),this.#a=null,this.#n&&=(e.#p.get(this.#n)?.drawLayer===this&&(e.#m(this.#n),e.#p.delete(this.#n),e.#f.delete(this.#n),e.#f.size===0&&(e.#l?.abort(),e.#l=null,e.#d=!1)),null)}};function ta(e){return`${(e*100).toFixed(2)}%`}var na=class e{#e=[];#t=new Map;#n=null;#r=0;#i=0;#a=0;static#o=null;constructor(e,t,n,r){this.#r=e,this.#e=t,this.#i=n.rawDims.pageWidth,this.#a=n.rawDims.pageHeight,this.#n=r}render(){let t=document.createElement(`div`);t.className=`textLayerImages`;for(let e=0;e{if(!(t.target instanceof HTMLCanvasElement))return;let n=t.target,r=this.#t.get(n);if(!r)return;let i=e.#o?.deref();if(i===n)return;i&&(i.width=0,i.height=0),e.#o=new WeakRef(n);let{inverseTransform:a,x1:o,y1:s,width:c,height:l}=r,u=this.#n(),d=Math.ceil(o*u.width),f=Math.ceil(s*u.height),p=Math.floor((o+c/this.#i)*u.width),m=Math.floor((s+l/this.#a)*u.height);n.width=p-d,n.height=m-f;let h=n.getContext(`2d`);h.setTransform(...a),h.translate(-d,-f),h.drawImage(u,0,0)}),t}#s([e,t,n,r,i,a]){let o=Math.hypot((i-e)*this.#i,(a-t)*this.#a),s=Math.hypot((n-e)*this.#i,(r-t)*this.#a);if(o0}clear(){this.reads.clear()}prune(){for(let e of this.reads)e.current()||this.reads.delete(e)}updateMessage(e){for(let t of this.reads)if(t.messages.size+t.authors.size<=1e3){let n=t.messages.get(e.id);t.messages.set(e.id,n?pe(n,e):e)}return t=>t.id===e.id?pe(t,e):t}updateAuthor(e){for(let t of this.reads)t.messages.size+t.authors.size<=1e3&&t.authors.set(e.id,{...t.authors.get(e.id),...e});let t=t=>t?.id===e.id?{...t,...e}:t;return e=>({...e,author:t(e.author),quoted_author:t(e.quoted_author)})}async run(e,t,n=()=>!0){let r=this.scope(),i={messages:new Map,authors:new Map,current:()=>this.reads.has(i)&&this.scope()===r&&n()};this.reads.add(i);try{let n=await e();if(!i.current())return;if(i.messages.size+i.authors.size>1e3)throw Error(`Too many messages changed while loading. Please try again.`);let r=e=>{let t=i.messages.get(e.id);return t&&(e=pe(e,t)),{...e,author:e.author&&{...e.author,...i.authors.get(e.author.id)},quoted_author:e.quoted_author&&{...e.quoted_author,...i.authors.get(e.quoted_author.id)}}};return`messages`in n?n.messages=n.messages.map(r):`message`in n?n.message=r(n.message):(n.root=r(n.root),n.replies=n.replies.map(r),n.thread_state=oe(n.root.thread_state??null,n.thread_state)),t(n),n}catch(e){if(i.current())throw e}finally{this.reads.delete(i)}}},V={bash:{glyph:`🖥`,action:`Ran shell command`},exec:{glyph:`🖥`,action:`Ran shell command`},command:{glyph:`🖥`,action:`Ran shell command`},bashsession:{glyph:`🖥`,action:`Managed shell session`},sessions_send:{glyph:`🖥`,action:`Managed shell session`},read:{glyph:`📖`,action:`Read file`},write:{glyph:`📝`,action:`Wrote file`},edit:{glyph:`✏`,action:`Edited file`},apply_patch:{glyph:`🧩`,action:`Applied patch`},applypatch:{glyph:`🧩`,action:`Applied patch`},browsercontrol:{glyph:`🌐`,action:`Controlled browser`},websearch:{glyph:`🔍`,action:`Searched the web`},webfetch:{glyph:`🔗`,action:`Fetched a page`},image:{glyph:`🖼`,action:`Analyzed image`},imagecreate:{glyph:`🎨`,action:`Generated image`},scheduler:{glyph:`⏰`,action:`Scheduled a job`},sendmessage:{glyph:`📤`,action:`Sent a message`},message:{glyph:`📤`,action:`Sent a message`},systemctl:{glyph:`⚙`,action:`Controlled the system`},process:{glyph:`⚙`,action:`Managed a process`},devicecontrol:{glyph:`📱`,action:`Controlled a device`},pdfparse:{glyph:`📄`,action:`Parsed a PDF`},statuscheck:{glyph:`📊`,action:`Checked status`}},H=[{test:e=>e.includes(`search`),glyph:`🔍`,action:`Searched`},{test:e=>e.includes(`fetch`),glyph:`🔗`,action:`Fetched`},{test:e=>e.includes(`browser`),glyph:`🌐`,action:`Controlled browser`},{test:e=>e.includes(`patch`),glyph:`🧩`,action:`Applied patch`},{test:e=>e.includes(`write`),glyph:`📝`,action:`Wrote file`},{test:e=>e.includes(`edit`),glyph:`✏`,action:`Edited file`},{test:e=>e.includes(`read`),glyph:`📖`,action:`Read file`},{test:e=>e.includes(`session`),glyph:`🖥`,action:`Managed shell session`},{test:e=>e.includes(`bash`)||e.includes(`shell`)||e.includes(`exec`),glyph:`🖥`,action:`Ran command`},{test:e=>e.includes(`image`),glyph:`🖼`,action:`Worked with image`},{test:e=>e.includes(`message`)||e.includes(`send`),glyph:`📤`,action:`Sent a message`},{test:e=>e.includes(`agent`)||e.includes(`subagent`),glyph:`🤖`,action:`Ran a sub-agent`},{test:e=>e.includes(`schedul`)||e.includes(`cron`),glyph:`⏰`,action:`Scheduled a job`},{test:e=>e.includes(`device`),glyph:`📱`,action:`Controlled a device`},{test:e=>e.includes(`file`)||e.includes(`dir`),glyph:`📁`,action:`Worked with files`}];function U(e,t){let n=String(e||``).trim(),r=n.toLowerCase().replace(/[^a-z0-9_]/g,``),i=String(t||``).trim()||void 0,a=V[r];if(a)return{name:n,glyph:a.glyph,action:a.action,detail:i};for(let e of H)if(e.test(r))return{name:n,glyph:e.glyph,action:e.action,detail:i};return{name:n||`tool`,glyph:`🔧`,action:`Used tool`,detail:i}}var we=a(`
`),Te=a(` `),W=a(` `),Ee=a(`
`),De=a(`
`),G=a(`
`),Oe=a(`
`),ke=a(`
`),K=a(`
`);function Ae(a,u){r(u,!0);let p=h(u,`mentionPeople`,19,()=>[]),m=b(!0),w=b(void 0);g(()=>{(o(w)===void 0||u.block.final!==o(w))&&(x(w,u.block.final,!0),x(m,!u.block.final))});let ee=O({});function T(e){ee[e]=!ee[e]}function te(e){let t=e.match(/^\*\*([^]*?)\*\*\s*\n*([^]*)$/);if(!t)return{text:e};let n=t[1].trim(),r=t[2].trim();return{head:n||void 0,text:r}}let k=j(()=>u.block.items.map(e=>e.type===`tool`?{item:e,tool:U(e.name,e.detail)}:{item:e,tool:null})),ne=j(()=>u.block.final?o(m)?`expanded`:`collapsed`:`live`),M=j(()=>o(m)?`Hide preamble`:`Show preamble`);var N=K();let P;var F=E(N),ie=E(F);let ae;var oe=y(ie,2);let se;var ce=v(oe,!0),le=y(oe,2),ue=v(le,!0);e(F);var de=y(F,2),fe=r=>{var a=ke();c(a,21,()=>o(k),e=>e.item.id,(r,a)=>{var c=i(),f=A(c),m=t=>{var r=we();n(r,()=>I(o(a).item.body),!0),e(r),d(r,e=>re?.(e)),d(r,(e,t)=>ve?.(e,t),()=>({people:p(),attentionUserID:u.mentionAttentionUserID})),l(t,r)},h=r=>{let i=j(()=>ee[o(a).item.id]===!0);var c=Oe();let f;var m=E(c),h=E(m);let g;var b=y(h,2),x=v(b,!0),w=y(b,2),O=v(w,!0),k=y(w,2),A=e=>{var t=Te(),n=v(t,!0);S(()=>s(n,o(a).tool.name)),l(e,t)};C(k,e=>{o(a).tool.name&&o(a).tool.name!==`tool`&&e(A)});var ne=y(k,2),M=e=>{var t=W(),n=v(t,!0);S(()=>{D(t,`title`,o(a).tool.detail),s(n,o(a).tool.detail)}),l(e,t)};C(ne,e=>{!o(i)&&o(a).tool.detail&&e(M)}),e(m);var N=y(m,2),P=t=>{let r=j(()=>te(o(a).item.full));var i=G(),c=E(i),f=e=>{var t=Ee(),n=v(t,!0);S(()=>s(n,o(r).head)),l(e,t)};C(c,e=>{o(r).head&&e(f)});var m=y(c,2),h=t=>{var i=De();n(i,()=>I(o(r).text),!0),e(i),d(i,e=>re?.(e)),d(i,(e,t)=>ve?.(e,t),()=>({people:p(),attentionUserID:u.mentionAttentionUserID})),l(t,i)};C(m,e=>{o(r).text&&e(h)}),e(i),l(t,i)};C(N,e=>{o(i)&&e(P)}),e(c),S(()=>{f=_(c,1,`preamble-tool`,null,f,{expanded:o(i)}),D(m,`aria-expanded`,o(i)),g=_(h,1,`tool-line-chevron`,null,g,{open:o(i)}),s(x,o(a).tool.glyph),s(O,o(a).tool.action)}),t(`click`,m,()=>T(o(a).item.id)),l(r,c)};C(f,e=>{o(a).item.type===`commentary`?e(m):o(a).tool&&e(h,1)}),l(r,c)}),e(a),l(r,a)};C(de,e=>{o(m)&&e(fe)}),e(N),S(()=>{P=_(N,1,`preamble-contract`,null,P,{"is-final":u.block.final}),D(F,`aria-expanded`,o(m)),ae=_(ie,1,`preamble-chevron`,null,ae,{open:o(m)}),se=_(oe,1,`preamble-state`,null,se,{"is-live":!u.block.final}),s(ce,o(ne)),s(ue,o(M))}),t(`click`,F,()=>x(m,!o(m))),l(a,N),f()}M([`click`]);var je=a(``),Me=a(` `);function Ne(e,n){r(n,!0);var a=i(),o=A(a),c=e=>{var r=i(),a=A(r),o=e=>{var r=je(),i=v(r,!0);S(()=>{D(r,`aria-label`,`Filter by topic ${n.topic.name}`),s(i,n.topic.name)}),t(`click`,r,e=>{e.stopPropagation(),n.onSelect(n.topic.id)}),l(e,r)},c=e=>{var t=Me(),r=v(t,!0);S(()=>s(r,n.topic.name)),l(e,t)};C(a,e=>{n.onSelect?e(o):e(c,-1)}),l(e,r)};C(o,e=>{n.topic&&e(c)}),l(e,a),f()}M([`click`]);var Pe=a(`
This message was deleted.
`),Fe=a(`(edited)`),Ie=a(`
`),Le=a(``),Re=a(``),ze=a(``),Be=a(`
`,1),Ve=a(``),He=a(` `,1),Ue=a(``),q=a(` `),We=a(``),Ge=a(`Couldn't create link`),Ke=a(` `,1),qe=a(` `),Je=a(` `,1),Ye=a(` `,1),Xe=a(` `,1),Ze=a(`
`),Qe=a(`
`),$e=a(`
`);function et(a,u){r(u,!0);let w=h(u,`mentionPeople`,19,()=>[]),T=h(u,`reactionsDisabled`,3,!1),ne=h(u,`canDeleteAnyMessage`,3,!1),M=h(u,`deleting`,3,!1),P=h(u,`editScope`,3,``),oe=h(u,`topics`,19,()=>[]),ue=h(u,`onSelectTopic`,3,()=>{}),pe=h(u,`channelID`,3,``),ye=h(u,`pinned`,3,!1),z=j(()=>u.editController?.session(P())),be=j(()=>o(z)?.surface===`timeline`&&o(z).messageID===u.message.id);async function B(){await m(),o(Z)?.focus()}function xe(){u.editController?.start(P(),u.message,`timeline`)===`cancelled`&&B()}function Se(){u.editController?.cancel(P(),`timeline`)&&B()}async function Ce(){if(!u.editController)return;let e=await u.editController.save(P(),u.message,e=>u.onMessageEdited?.(e));(e===`saved`||e===`cancelled`)&&await B()}let V=j(()=>u.message.status===`pending`),H=j(()=>u.message.status===`failed`),U=j(()=>!!u.message.deleted_at),we=j(()=>ne()||!!u.currentUserID&&(u.message.author?.id||u.message.author_id)===u.currentUserID),Te=j(()=>!!u.currentUserID&&(u.message.author?.id||u.message.author_id)===u.currentUserID),W=j(()=>u.message.preamble_block),Ee=j(()=>!!u.previousMessage?.preamble_block&&!o(W)),De=j(()=>!!o(W)&&!!u.nextMessage&&!u.nextMessage?.preamble_block),G=j(()=>u.message.thread_state?.reply_count||0),Oe=j(()=>o(G)>0),ke=j(()=>ae(u.message)),K=j(()=>u.selectedThreadID===u.message.id),je=j(()=>!o(W)&&!o(V)&&!o(H)&&(!o(U)||o(Oe)||o(K))),Me=j(()=>oe().find(e=>e.id===u.message.topic_id));function et(e){if(qt||o(Ht)){qt=!1,e.preventDefault(),e.stopPropagation();return}o(je)&&(window.getSelection()?.toString()||e.target?.closest(zt)||u.onOpenThread(u.message))}function tt(e){return e.addEventListener(`click`,et),{destroy(){e.removeEventListener(`click`,et)}}}let J=b(!1),Y=b(!1),nt=b(``),X=b(``),rt=b(``),it=b(void 0),at=b(!1),ot=b(``),st=b(!1),ct=b(!1),lt=b(void 0),ut=b(!1),dt=b(!1),ft=j(()=>o(ut)||o(dt)||u.selected),pt=b(!1);function mt(){let e=o(lt)?.closest(`.messages-scroll`);if(!o(lt)||!e){x(pt,!1);return}let t=o(lt).getBoundingClientRect().top-e.getBoundingClientRect().top;x(pt,t<26)}let ht=b(void 0),gt=b(void 0),_t=b(void 0),Z=b(void 0),vt,yt,bt=!1,xt=j(()=>`toolbar-reaction-picker-${u.message.id}`),St=j(()=>u.reactionController.pending(u.message.id)),Q=j(()=>T()||!u.currentUserID||o(V)||o(H)||o(St));function Ct(e){o(Q)||u.reactionController.toggle(u.message,e)}function wt(){o(Q)||(o(J)||x(st,fe(o(ht),130),!0),x(J,!o(J)))}function Tt(e){o(Q)||(u.reactionController.toggle(u.message,e),x(J,!1))}function Et(){x(J,!1),o(_t)?.focus()}async function Dt(){o(Y)||x(ct,fe(o(gt),160),!0),x(Y,!o(Y)),o(Y)&&(await m(),At()[0]?.focus())}function Ot(){if(o(Vt)){Qt(o(Z));return}Dt()}function kt(e=!0){x(Y,!1),e&&o(Z)?.focus()}function At(){return[...o(gt)?.querySelectorAll(`[role="menuitem"]:not(:disabled)`)??[]].filter(e=>e.getClientRects().length>0)}function jt(e){if(e.key===`Escape`){e.preventDefault(),kt();return}if(e.key===`Tab`){kt(!1);return}let t=At();if(t.length===0)return;let n=t.indexOf(document.activeElement),r;e.key===`ArrowDown`?r=n<0?0:(n+1)%t.length:e.key===`ArrowUp`?r=n<=0?t.length-1:n-1:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==void 0&&(e.preventDefault(),t[r]?.focus())}function Mt(e){bt||(x(nt,e,!0),vt&&window.clearTimeout(vt),vt=window.setTimeout(()=>{x(nt,``),vt=void 0},1800))}async function Nt(){kt(),await Pt()}async function Pt(){try{if(!navigator.clipboard)throw Error(`Clipboard unavailable`);return await navigator.clipboard.writeText(u.message.body??``),Mt(`copied`),!0}catch{return Mt(`failed`),!1}}async function Ft(){if(!u.onCopyLink||o(X)===`pending`)return{copied:!1};x(X,`pending`);let e;try{e=await u.onCopyLink(u.message)}catch{return x(X,`failed`),{copied:!1}}try{if(!navigator.clipboard)throw Error(`Clipboard unavailable`);return await navigator.clipboard.writeText(e),x(X,``),Mt(`copied`),{copied:!0}}catch{return x(X,``),{copied:!1,fallback:e}}}async function It(){let e=await Ft();!e.copied&&!e.fallback||(kt(!1),e.fallback?(x(it,o(Z),!0),x(rt,e.fallback,!0)):o(Z)?.focus())}function Lt(){kt(!1),xe()}function Rt(){kt(!1),u.onDeleteMessage?.(u.message)}let zt=`a, button, input, textarea, select, .attachment-grid, .media-tile, .markdown img, .gif-player, .markdown-table-scroll, .message-actions, .message-failed`,Bt=typeof window<`u`?window.matchMedia(`(hover: none), (pointer: coarse)`):null,Vt=b(O(Bt?.matches??!1)),Ht=b(!1),Ut,Wt,Gt=0,Kt=b(void 0),qt=!1,Jt=j(()=>`message-action-sheet-${u.message.id}`);g(()=>{if(!Bt)return;let e=()=>{x(Vt,Bt.matches,!0)};return Bt.addEventListener(`change`,e),()=>Bt.removeEventListener(`change`,e)});function Yt(){Ut!==void 0&&(window.clearTimeout(Ut),Ut=void 0)}function Xt(){Wt?.(),Wt=void 0}function Zt(){yt!==void 0&&(window.clearTimeout(yt),yt=void 0)}function Qt(e){Zt(),Gt+=1,x(Kt,e,!0),x(Y,!1),x(J,!1),x(Ht,!0)}function $t(e){if(e.pointerType!==`touch`||!e.isPrimary||e.button!==0||o(W)||o(U)||o(V)||o(H)||o(be)||e.target?.closest(zt))return;Xt();let t=e.pointerId,n=e.clientX,r=e.clientY;Ut=window.setTimeout(()=>{Ut=void 0,qt=!0,Qt()},450);let i=e=>{e.pointerId===t&&(Math.abs(e.clientX-n)>10||Math.abs(e.clientY-r)>10)&&s()},a=e=>{e.pointerId===t&&s()},s=()=>{Yt(),window.removeEventListener(`pointermove`,i),window.removeEventListener(`pointerup`,a),window.removeEventListener(`pointercancel`,a),Wt===s&&(Wt=void 0)};Wt=s,window.addEventListener(`pointermove`,i),window.addEventListener(`pointerup`,a),window.addEventListener(`pointercancel`,a)}function en(e){(o(Ht)||Ut!==void 0)&&e.preventDefault()}function tn(){Zt(),Gt+=1,x(Ht,!1),qt=!1}function nn(e){tn(),!o(Q)&&u.reactionController.toggle(u.message,e)}function rn(){tn(),u.onOpenThread(u.message)}function an(){tn(),u.onReply(u.message,u.replyContext)}async function on(){Zt();let e=Gt;!await Pt()||!o(Ht)||e!==Gt||(yt=window.setTimeout(()=>{yt=void 0,!bt&&e===Gt&&tn()},900))}async function sn(){let e=await Ft();if(!e.copied&&!e.fallback)return;let t=o(Kt);tn(),e.fallback&&(await m(),x(it,t,!0),x(rt,e.fallback,!0))}function cn(){tn(),xe()}function ln(){tn(),u.onDeleteMessage?.(u.message)}async function un(){if(!(!pe()||!u.onTogglePin||o(at))){x(at,!0),x(ot,``);try{await u.onTogglePin(u.message,ye()),kt()}catch(e){x(ot,N(e,`Could not update pin`),!0)}finally{x(at,!1)}}}async function dn(){await un(),o(ot)||tn()}g(()=>{if(!o(J)&&!o(Y))return;let e=e=>{let t=e.target;o(J)&&o(ht)&&!o(ht).contains(t)&&x(J,!1),o(Y)&&o(gt)&&!o(gt).contains(t)&&x(Y,!1)};return document.addEventListener(`click`,e),()=>document.removeEventListener(`click`,e)}),g(()=>{o(Q)&&x(J,!1)}),te(()=>{bt=!0,vt&&window.clearTimeout(vt),Zt(),Xt()}),g(()=>{if(!(o(Y)||o(J)||o(ft))||!o(lt))return;let e=o(lt).parentElement;for(;e&&e.style.position!==`absolute`;)e=e.parentElement;if(!e)return;let t=e.style.zIndex;return e.style.zIndex=`10`,()=>{e.style.zIndex=t}});var $=$e();let fn;var pn=E($),mn=v(pn,!0),hn=y(pn,2),gn=E(hn),_n=e=>{Ae(e,{get block(){return o(W)},get mentionPeople(){return w()},get mentionAttentionUserID(){return u.mentionAttentionUserID}})},vn=e=>{var t=Pe();l(e,t)},yn=e=>{var t=i(),n=A(t),r=e=>{L(e,{get body(){return o(z).draft},get errorMessage(){return o(z).error},get saving(){return o(z).saving},onBody:e=>u.editController?.updateDraft(P(),e),onCancel:Se,onSave:Ce})};C(n,e=>{o(z)&&e(r)}),l(e,t)},bn=r=>{var i=Be(),a=A(i);Ne(a,{get topic(){return o(Me)},get onSelect(){return ue()}});var s=y(a,2);_e(s,{get message(){return u.message},get onJump(){return u.onJumpToQuote}});var f=y(s,2);n(f,()=>I(u.message.body),!0),e(f),d(f,e=>re?.(e)),d(f,(e,t)=>ve?.(e,t),()=>({people:w(),attentionUserID:u.mentionAttentionUserID}));var p=y(f,2),m=e=>{var t=Fe();S(e=>D(t,`title`,`Edited ${e??``}`),[()=>de(u.message.edited_at)]),l(e,t)};C(p,e=>{u.message.edited_at&&e(m)});var h=y(p,2),g=e=>{{let t=j(()=>u.reactionController.reactionsFor(u.message)),n=j(()=>u.reactionController.pending(u.message.id)),r=j(()=>u.reactionController.error(u.message.id)),i=j(()=>T()||!u.currentUserID);ge(e,{get messageId(){return u.message.id},get reactions(){return o(t)},get pending(){return o(n)},get error(){return o(r)},get disabled(){return o(i)},onToggle:e=>void u.reactionController.toggle(u.message,e)})}};C(h,e=>{!o(V)&&!o(H)&&e(g)});var _=y(h,2),v=t=>{var n=Ie();c(n,21,()=>u.message.attachments,e=>e.id,(e,t)=>{{let n=j(()=>F(o(t)));R(e,{get upload(){return o(t)},get url(){return o(n)},get onOpenImage(){return u.onOpenImage},get onOpenArtifact(){return u.onOpenArtifact}})}}),e(n),l(t,n)};C(_,e=>{u.message.attachments?.length&&e(v)});var b=y(_,2),x=n=>{var r=ze(),i=y(E(r),2),a=e=>{var n=Le();t(`click`,n,()=>u.onRetry?.(u.message)),l(e,n)};C(i,e=>{u.onRetry&&e(a)});var o=y(i,2),s=e=>{var n=Re();t(`click`,n,()=>u.onDiscard?.(u.message)),l(e,n)};C(o,e=>{u.onDiscard&&e(s)}),e(r),l(n,r)};C(b,e=>{o(H)&&e(x)}),l(r,i)};C(gn,e=>{o(W)?e(_n):o(U)?e(vn,1):o(be)?e(yn,2):e(bn,-1)});var xn=y(gn,2),Sn=n=>{var r=Ue();let i;var a=y(E(r),2),c=e=>{var t=He(),n=A(t),r=v(n,!0),i=y(n,2),a=e=>{var t=Ve(),n=v(t,!0);S(()=>{D(t,`datetime`,u.message.thread_state?.last_reply_at),s(n,o(ke))}),l(e,t)};C(i,e=>{o(ke)&&e(a)}),S(e=>s(r,e),[()=>ie(u.message)]),l(e,t)};C(a,e=>{(o(Oe)||o(K))&&e(c)}),e(r),S((e,t)=>{i=_(r,1,`thread-hint tooltip`,null,i,{"has-replies":o(Oe),"is-open":o(K)}),D(r,`data-tooltip`,e),D(r,`aria-label`,t)},[()=>se(u.message,u.selectedThreadID),()=>se(u.message,u.selectedThreadID)]),t(`click`,r,()=>u.onOpenThread(u.message)),l(n,r)};C(xn,e=>{o(je)&&e(Sn)}),e(hn);var Cn=y(hn,2),wn=n=>{var r=Qe(),i=E(r),a=e=>{var t=q();let n;var r=v(t,!0);S(()=>{n=_(t,1,`message-copy-status`,null,n,{"is-error":o(nt)===`failed`}),s(r,o(nt)===`copied`?`Copied`:`Couldn't copy`)}),l(e,t)};C(i,e=>{o(nt)&&e(a)});var d=y(i,2);c(d,17,()=>me,ee,(e,n)=>{var r=We(),i=v(r,!0);S(()=>{D(r,`aria-label`,`React with ${o(n)}`),D(r,`data-tooltip`,`React with ${o(n)}`),r.disabled=o(Q),s(i,o(n))}),t(`click`,r,()=>Ct(o(n))),l(e,r)});var f=y(d,2),p=E(f);k(p,e=>x(_t,e),()=>o(_t));var m=y(p,2),h=e=>{{let t=j(()=>o(st)?`above-right`:`below`);le(e,{get id(){return o(xt)},get placement(){return o(t)},get disabled(){return o(Q)},onPick:Tt,onEscape:Et})}};C(m,e=>{o(J)&&e(h)}),e(f),k(f,e=>x(ht,e),()=>o(ht));var g=y(f,4),b=y(g,2),w=y(b,4),T=E(w);let te;k(T,e=>x(Z,e),()=>o(Z));var O=y(T,2),ne=n=>{var r=Ze();let i;var a=E(r),c=y(a,2),d=n=>{var r=Ke(),i=A(r),a=y(E(i));e(i);var c=y(i,2),u=e=>{var t=Ge();l(e,t)};C(c,e=>{o(X)===`failed`&&e(u)}),S(()=>{i.disabled=o(X)===`pending`,s(a,` ${o(X)===`pending`?`Creating link…`:`Copy link`}`)}),t(`click`,i,()=>void It()),l(n,r)};C(c,e=>{pe()&&u.onCopyLink&&e(d)});var f=y(c,2),p=n=>{var r=Je(),i=A(r),a=y(E(i));e(i);var c=y(i,2),u=e=>{var t=qe(),n=v(t,!0);S(()=>s(n,o(ot))),l(e,t)};C(c,e=>{o(ot)&&e(u)}),S(()=>{i.disabled=o(at),s(a,` ${ye()?`Unpin message`:`Pin message`}`)}),t(`click`,i,un),l(n,r)};C(f,e=>{pe()&&u.onTogglePin&&e(p)});var m=y(f,2),h=e=>{var n=Ye(),r=y(A(n),2);t(`click`,r,Lt),l(e,n)};C(m,e=>{o(Te)&&u.editController&&P()&&!o(be)&&e(h)});var g=y(m,2),b=e=>{var n=Xe(),r=y(A(n),2);S(()=>r.disabled=M()),t(`click`,r,Rt),l(e,n)};C(g,e=>{o(we)&&u.onDeleteMessage&&e(b)}),e(r),S(()=>i=_(r,1,`message-menu`,null,i,{above:o(ct)})),t(`keydown`,r,jt),t(`click`,a,Nt),l(n,r)};C(O,e=>{o(Y)&&e(ne)}),e(w),k(w,e=>x(gt,e),()=>o(gt)),e(r),S(e=>{D(p,`aria-controls`,o(xt)),D(p,`aria-expanded`,o(J)),p.disabled=o(Q),D(g,`data-tooltip`,e),g.disabled=o(V)||o(H),b.disabled=o(V)||o(H),te=_(T,1,`message-actions-trigger`,null,te,{tooltip:!o(Vt),"tooltip-align-end":!o(Vt)}),D(T,`data-tooltip`,o(Vt)?void 0:`More actions`),D(T,`aria-haspopup`,o(Vt)?`dialog`:`menu`),D(T,`aria-controls`,o(Vt)?o(Jt):void 0),D(T,`aria-expanded`,o(Vt)?o(Ht):o(Y)),T.disabled=o(V)||o(H)},[()=>se(u.message,u.selectedThreadID)]),t(`click`,p,wt),t(`click`,g,()=>u.onOpenThread(u.message)),t(`click`,b,()=>u.onReply(u.message,u.replyContext)),t(`click`,T,Ot),l(n,r)};C(Cn,e=>{!o(W)&&!o(U)&&e(wn)});var Tn=y(Cn,2),En=e=>{{let t=j(()=>!o(Q)),n=j(()=>!o(V)&&!o(H)),r=j(()=>o(Te)&&!!u.editController&&!!P()&&!o(be)),i=j(()=>!!(pe()&&u.onTogglePin)),a=j(()=>o(we)&&!!u.onDeleteMessage),s=j(()=>!!(pe()&&u.onCopyLink));he(e,{get id(){return o(Jt)},get canReact(){return o(t)},get canReply(){return o(n)},get canOpenThread(){return o(je)},get canEdit(){return o(r)},get canPin(){return o(i)},get pinned(){return ye()},get pinning(){return o(at)},get pinError(){return o(ot)},get canDelete(){return o(a)},get deleting(){return M()},get copyStatus(){return o(nt)},get canCopyLink(){return o(s)},get copyLinkStatus(){return o(X)},onReact:nn,onOpenThread:rn,onReply:an,onCopy:on,onCopyLink:sn,onEdit:cn,onTogglePin:dn,onDelete:ln,onClose:tn,get returnFocus(){return o(Kt)}})}};C(Tn,e=>{o(Ht)&&e(En)});var Dn=y(Tn,2),On=e=>{ce(e,{get url(){return o(rt)},onClose:()=>x(rt,``),get returnFocus(){return o(it)}})};C(Dn,e=>{o(rt)&&e(On)}),e($),k($,e=>x(lt,e),()=>o(lt)),d($,e=>tt?.(e)),S((e,t)=>{fn=_($,1,`message-row`,null,fn,{selected:u.selected,"is-pending":o(V),"is-failed":o(H),"is-deleted":o(U),"is-preamble":e,"is-preamble-collapsed":o(W)?.final===!0,"is-preamble-live":o(W)?.final===!1,"before-final-message":o(De),"after-preamble":o(Ee),"can-open-thread":o(je),editing:o(be),"menu-open":o(Y)||o(J),"actions-flip":o(pt)}),D($,`data-message-id`,u.message.id),s(mn,t)},[()=>!!o(W),()=>u.index===0?``:de(u.message.created_at)]),t(`pointerdown`,$,$t),t(`contextmenu`,$,en),p(`mouseenter`,$,()=>{!o(ut)&&!o(dt)&&mt(),x(ut,!0)}),p(`mouseleave`,$,()=>x(ut,!1)),t(`focusin`,$,()=>{!o(ut)&&!o(dt)&&mt(),x(dt,!0)}),t(`focusout`,$,e=>{o(lt)?.contains(e.relatedTarget)||x(dt,!1)}),l(a,$),f()}M([`pointerdown`,`contextmenu`,`focusin`,`focusout`,`click`,`keydown`]);var tt=a(` deleted bot`,1),J=a(`bot`),Y=a(` `,1),nt=a(` `),X=a(`
`);function rt(n,i){r(i,!0);let a=h(i,`reactionsDisabled`,3,!1),u=h(i,`mentionPeople`,19,()=>[]),d=h(i,`canDeleteAnyMessage`,3,!1),p=h(i,`deletingMessageIDs`,19,()=>new Set),m=h(i,`channelID`,3,``),g=h(i,`pinnedMessageIDs`,19,()=>new Set),b=h(i,`editScope`,3,``),x=h(i,`topics`,19,()=>[]),w=h(i,`onSelectTopic`,3,()=>{}),ee=j(()=>i.group.messages[0]?.author),te=j(()=>o(ee)?.kind===`bot`),D=j(()=>!o(te)&&!!i.currentUserID&&i.group.authorID===i.currentUserID);var O=X();let k;var ne=E(O);{let e=j(()=>i.group.authorDeleted?`avatar`:`avatar avatar-button`),t=j(()=>i.group.authorDeleted?void 0:`View profile for ${i.group.authorName}`);B(ne,{get class(){return o(e)},get id(){return i.group.authorID},get name(){return i.group.authorName},get src(){return i.group.authorAvatarURL},size:38,get buttonLabel(){return o(t)},onclick:()=>i.onOpenProfile(i.group.messages[0]?.author)})}var M=y(ne,2),N=E(M),P=E(N),F=e=>{var t=tt(),n=A(t),r=v(n,!0);T(2),S(()=>s(r,i.group.authorName)),l(e,t)},re=e=>{var n=Y(),r=A(n),a=v(r,!0),c=y(r,2),u=e=>{var t=J();l(e,t)};C(c,e=>{o(te)&&e(u)}),S(()=>s(a,i.group.authorName)),t(`click`,r,()=>i.onOpenProfile(i.group.messages[0]?.author)),l(e,n)};C(P,e=>{i.group.authorDeleted?e(F):e(re,-1)});var ie=y(P,2),ae=e=>{var t=nt(),n=v(t,!0);S(e=>s(n,e),[()=>z(i.group.authorHandle)]),l(e,t)};C(ie,e=>{i.group.authorHandle&&e(ae)});var oe=y(ie,2),se=v(oe,!0);e(N);var ce=y(N,2);c(ce,19,()=>i.group.messages,e=>e.id,(e,t,n)=>{{let r=j(()=>i.selectedThreadID===o(t).id),s=j(()=>p().has(o(t).id)),c=j(()=>g().has(o(t).id));et(e,{get message(){return o(t)},get index(){return o(n)},get previousMessage(){return i.group.messages[o(n)-1]},get nextMessage(){return i.group.messages[o(n)+1]},get selected(){return o(r)},get replyContext(){return i.replyContext},get selectedThreadID(){return i.selectedThreadID},get mentionPeople(){return u()},get mentionAttentionUserID(){return i.mentionAttentionUserID},get currentUserID(){return i.currentUserID},get reactionController(){return i.reactionController},get reactionsDisabled(){return a()},get canDeleteAnyMessage(){return d()},get deleting(){return o(s)},get editController(){return i.editController},get editScope(){return b()},get onMessageEdited(){return i.onMessageEdited},get onReply(){return i.onReply},get onOpenThread(){return i.onOpenThread},get onJumpToQuote(){return i.onJumpToQuote},get onOpenImage(){return i.onOpenImage},get onOpenArtifact(){return i.onOpenArtifact},get onRetry(){return i.onRetry},get onDiscard(){return i.onDiscard},get onDeleteMessage(){return i.onDeleteMessage},get topics(){return x()},get onSelectTopic(){return w()},get channelID(){return m()},get pinned(){return o(c)},get onTogglePin(){return i.onTogglePin},get onCopyLink(){return i.onCopyLink}})}}),e(M),e(O),S(e=>{k=_(O,1,`message-group`,null,k,{"is-agent":o(te),"is-self":o(D)}),s(se,e)},[()=>de(i.group.timestamp)]),l(n,O),f()}M([`click`]);var it=a(`
Send a message in Markdown — code fences, lists, links all work. Threads open from any message.
`),at=a(`
`),ot=a(`
`),st=a(`
New
`),ct=a(`
`),lt=a(`
`),ut=a(`
`);function dt(n,a){r(a,!0);let c=h(a,`loading`,3,!1),d=h(a,`unreadCount`,3,0),p=h(a,`unreadBoundarySeq`,3,0),ee=h(a,`unreadBoundaryLoaded`,3,!1),O=h(a,`unreadSince`,3,``),ne=h(a,`hasOlder`,3,!1),M=h(a,`hasNewer`,3,!1),N=h(a,`loadingOlder`,3,!1),F=h(a,`loadingNewer`,3,!1),re=h(a,`prepending`,3,!1),ie=h(a,`mentionPeople`,19,()=>[]),ae=h(a,`reactionsDisabled`,3,!1),oe=h(a,`canDeleteAnyMessage`,3,!1),se=h(a,`deletingMessageIDs`,19,()=>new Set),ce=h(a,`channelID`,3,``),le=h(a,`pinnedMessageIDs`,19,()=>new Set),de=h(a,`editScope`,3,``),fe=h(a,`topics`,19,()=>[]),pe=h(a,`onSelectTopic`,3,()=>{}),me=1.5,I=b(void 0),L=b(void 0),he=b(void 0),R=b(0),ge=b(0),_e=j(()=>a.selectedDirect?`dm`:`channel`),ve=b(``),z=b(-1),be=b(0),B=j(()=>o(ve)===a.viewKey&&o(z)===p()&&d()<=o(be)?0:d()),Ce=b(``),V=b(0),H=b(!1),U,we=j(()=>o(B)>0?o(B):o(V));function Te(){U&&=(window.clearTimeout(U),void 0)}g(()=>{if(o(Ce)&&o(Ce)!==a.viewKey){Te(),x(V,0),x(Ce,``),x(H,!1);return}if(o(B)>0){Te(),x(Ce,a.viewKey,!0),x(V,o(B),!0),x(H,!1);return}o(V)>0&&!o(H)&&(x(H,!0),U=window.setTimeout(()=>{U=void 0,!(o(B)>0)&&(x(V,0),x(Ce,``),x(H,!1))},180))}),te(Te);let W=j(()=>{let e=p()+1;if(o(we)<=0||e<=0)return!1;let t=1/0,n=0;for(let e of a.messages){if(e.parent_message_id)continue;let r=e.channel_seq||0;r<=0||(t=Math.min(t,r),n=Math.max(n,r))}return t<=e&&n>=e}),Ee=j(()=>ee()&&o(W)),De=j(()=>{let e=[],t=!1,n=e=>!o(Ee)||e.parent_message_id||e.author?.id===a.currentUserID||e.author_id===a.currentUserID?!1:o(we)>0&&(e.channel_seq||0)>p();for(let r of P(a.messages)){let i=-1;if(!t){for(let e=0;ea.messages.map(e=>{let t=e.preamble_block;if(!t)return``;let n=t.items.map(e=>e.type===`commentary`?`${e.id}\u0000${e.body}`:`${e.id}\u0000${e.name}\u0000${e.detail||``}\u0000${e.full}`).join(``);return`${e.id}\u0000${t.final?`final`:`live`}\u0000${n}`}).filter(Boolean).join(``)),ke=b(!0),K=b(!1),Ae,je=0,Me=``,Ne=``,Pe,Fe=b(void 0),Ie=0,Le=!1,Re=!1,ze=!1,Be=!1,Ve=0,He=0;function Ue(e=!0){return e&&(Le=!1,x(K,!0)),He+=1,He}function q(e,t){return dt(e)&&t===He}function We(e=2){let t=++Ve;Re=!0;let n=e=>{requestAnimationFrame(()=>{if(t===Ve){if(e<=1){Re=!1;return}n(e-1)}})};n(e)}function Ge(){if(!o(I))return 0;let e=o(I).getScrollSize()+o(R);return Math.max(0,e-o(I).getScrollOffset()-o(I).getViewportSize())}function Ke(){return!o(I)||Ge()<=me}function qe(e=me){return!o(I)||Ge()<=e}function Je(){if(!o(I))return{atBottom:!0,nearOlder:!1,nearNewer:!1};let e=Ge();return{atBottom:Ke(),nearOlder:o(I).getScrollOffset()-o(R)<=160,nearNewer:e<=260}}function Ye(){a.onHistorySettled?.(Je())}function Xe(e=!1){M()||!e&&o(B)>0||a.onReachedBottom?.()}g(()=>{if(F()){Be=!0;return}Be&&(Be=!1,ze=!1)});async function Ze(){!o(I)||o(De).length===0||(G=!M(),await Qe(Ue()))}async function Qe(e=Ue()){if(!o(I)||!o(L)||o(De).length===0)return;let t=a.viewKey;document.activeElement===o(L)&&o(L).blur();let n=-1;for(let r=0;r<6;r+=1){if(await m(),!o(I)||!o(L)||!q(t,e)||(G=!M(),We(2),o(L).scrollTop=o(L).scrollHeight,await X(),!o(I)||!q(t,e)))return;let r=o(I).getScrollSize(),i=n>=0&&Math.abs(r-n)<=me;if(n=r,i&&Ke())break}x(K,!0),G=!M(),Ke()&&(x(ke,!0),Xe(!0)),Ye()}g(()=>{if(!o(L))return;let e=o(L),t=()=>{let e=Ue();Re=!1,Z(a.viewKey,e)},n=e=>{e.defaultPrevented||e.ctrlKey||e.deltaY===0||(t(),e.deltaY>0&&M()&&Ke()&&(ze=!0,a.onLoadNewer?.(`wheel`)))},r=e=>{let n=e.target;e.defaultPrevented||!(n instanceof HTMLElement)||n.isContentEditable||n.closest(`input, textarea, select`)||e.key===` `&&n.closest(`button, [role=button]`)||[`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)&&t()},i=e=>{!e.defaultPrevented&&e.touches.length===1&&t()},s=n=>{n.target===e&&n.button===0&&t()};return e.addEventListener(`wheel`,n,{passive:!0}),e.addEventListener(`keydown`,r),e.addEventListener(`touchmove`,i,{passive:!0}),e.addEventListener(`pointerdown`,s),()=>{e.removeEventListener(`wheel`,n),e.removeEventListener(`keydown`,r),e.removeEventListener(`touchmove`,i),e.removeEventListener(`pointerdown`,s)}});function $e(e){return o(De).findIndex(t=>t.kind===`group`&&t.group.messages.some(t=>t.id===e))}let et=j(()=>{if(!ne()||c()||!re())return 0;let e=Math.max(o(ge),480);return Math.max(4,Math.ceil(e/52))});g(()=>{if(!o(L))return;let e=()=>{o(L)&&x(ge,o(L).clientHeight,!0)};e();let t=new ResizeObserver(e);return t.observe(o(L)),()=>t.disconnect()});let tt=0;g(()=>{if(!o(he)||!o(L)){x(R,0),tt=0;return}let e=o(he),t=()=>{let t=e.offsetHeight,n=tt;if(x(R,t,!0),tt=t,n>0&&t!==n){let e=t-n;o(L)&&o(L).scrollTop>0&&(o(L).scrollTop+=e)}};t();let n=new ResizeObserver(t);return n.observe(e),()=>{n.disconnect(),x(R,0),tt=0}});function J(){return o(De).findIndex(e=>e.kind===`divider`)}function Y(){let e=0;for(let t of a.messages)e=Math.max(e,t.channel_seq||0);return e}function nt(){x(ve,a.viewKey,!0),x(z,p()),x(be,d()),a.onMarkRead?.(Y())}function X(){return new Promise(e=>requestAnimationFrame(()=>e()))}function dt(e){return e===a.viewKey&&e===Ae}async function ft(e,t,n,r,i=0){We(3);for(let a=0;a<24;a++){if(!q(e,t)||!o(I)||!o(L))return!1;let a=o(L).querySelector(r);if(a){let e=a.getBoundingClientRect().top-o(L).getBoundingClientRect().top-i;if(Math.abs(e)<=me)return!0;o(L).scrollTop+=e}else{let e=n();if(e<0)return!1;o(L).scrollTop=o(R)+o(I).getItemOffset(e)}await X()}return!1}function pt(e,t,n){if(!o(I)||e()<0)return!1;G=!1;let r=a.viewKey,i=Ue();return ft(r,i,e,t).then(async a=>{q(r,i)&&(Ye(),await m(),q(r,i)&&(a&&=await ft(r,i,e,t),!a&&q(r,i)&&n?.()))}),!0}function mt(e){return pt(()=>$e(e),`[data-message-id="${CSS.escape(e)}"]`)}function ht(e=!0){return pt(J,`[data-unread-divider='true']`,e?a.onJumpToUnread:void 0)}function gt(){if(!(o(Ee)&&ht(!1))&&a.onJumpToUnread){a.onJumpToUnread();return}}function _t(){if(!o(I)||!o(L))return null;if(x(Fe,{atBottom:Ke()},!0),Ie=He,!o(Fe).atBottom){let e=o(L).getBoundingClientRect().top;for(let t of o(L).querySelectorAll(`[data-message-id]`)){let n=t.getBoundingClientRect();if(!(n.bottom<=e)){o(Fe).anchorMessageID=t.dataset.messageId,o(Fe).anchorPixelOffset=n.top-e;break}}}return o(Fe)}g(()=>(a.onListRef({scrollToBottom:Ze,scrollToMessage:mt,scrollToDivider:ht,captureState:_t,isFollowing:()=>G,isNearBottom:e=>qe(e)}),()=>a.onListRef(null))),g(()=>{let e=a.viewKey,t=o(De).length,n=o(Oe),r=a.messages.at(-1)?.id||``,i=r!==Me;if(Me=r,e!==Ae){Ae=e,je=t,Ne=n,Pe=a.restoreState,x(Fe,void 0),G=!0,x(ke,!0),x(K,!1),ze=!1,Le=!0,vt(e,a.restoreState,!0);return}let s=a.restoreState,c=s&&s!==Pe;if(c){let r=s===o(Fe)&&Ie!==He;if(x(Fe,void 0),Pe=s,!r&&(s.atBottom||s.anchorMessageID)){je=t,Ne=n,Le=!0,vt(e,s,s.atBottom);return}r&&!G&&o(I)&&yt(o(I).getScrollOffset())}let l=c||t!==je||i||n!==Ne;l&&G&&!M()&&!Le?Qe():l&&!Le&&Z(e),je=t,Ne=n});async function Z(e,t=He){await m(),await X(),q(e,t)&&Ye()}async function vt(e,t,n){let r=Ue(!1),i=t&&!t.atBottom?t.anchorMessageID:void 0,a=i?()=>ft(e,r,()=>$e(i),`[data-message-id="${CSS.escape(i)}"]`,t?.anchorPixelOffset??0):void 0,s=!1;if(await m(),await X(),q(e,r)){if(a){let t=await a();if(!q(e,r))return;!t&&n?await Qe(r):G=!1}else o(De).findIndex(e=>e.kind===`divider`)>=0&&o(I)?(s=!0,await ft(e,r,()=>J(),`[data-unread-divider='true']`),G=!1):await Qe(r);await X(),q(e,r)&&(Le=!1,x(K,!0),x(ke,Ke(),!0),G=o(ke)&&!M(),s||(o(ke)&&Xe(),o(I)&&yt(o(I).getScrollOffset())),Ye(),a&&(await m(),q(e,r)&&await a()))}}function yt(e){if(!o(I)||Le&&!o(K))return;let t=Ge(),n=Ke(),r=n||t<=260;G=n&&!M(),x(ke,n,!0),M()||(ze=!1),!n&&ne()&&e-o(R)<=160&&a.onLoadOlder?.(),!Re&&M()&&r&&!ze&&(ze=!0,a.onLoadNewer?.(`scroll`)),n&&!Re&&Xe()}var bt=ut();let xt;var St=E(bt),Q=t=>{var n=it(),r=E(n),i=E(r),o=e=>{var t=u(`@`);l(e,t)},c=e=>{var t=u(`#`);l(e,t)};C(i,e=>{a.selectedDirect?e(o):e(c,-1)}),e(r);var d=y(r,2),f=E(d),p=e=>{var t=u();S(e=>s(t,`This is the start of your conversation with ${e??``}.`),[()=>ye(a.selectedDirect,a.currentUserID)]),l(e,t)},m=e=>{var t=u();S(e=>s(t,`Welcome to #${e??``}!`),[()=>xe(a.selectedChannel)]),l(e,t)},h=e=>{var t=u(`Pick a channel to get started.`);l(e,t)};C(f,e=>{a.selectedDirect?e(p):a.selectedChannel?e(m,1):e(h,-1)}),e(d),T(2),e(n),l(t,n)},Ct=t=>{var n=ct(),r=y(E(n),2),u=t=>{var n=at(),r=E(n);ue(r,{direction:`older`,get rows(){return o(et)}}),e(n),k(n,e=>x(he,e),()=>o(he)),S(()=>D(n,`aria-hidden`,N()?`false`:`true`)),l(t,n)};C(r,e=>{o(et)>0&&e(u)});var d=y(r,2);k(Se(d,{get data(){return o(De)},getKey:e=>e.id,itemProps:()=>c()||!o(K)?void 0:{style:{"pointer-events":`auto`}},get scrollRef(){return o(L)},get shift(){return re()},get startMargin(){return o(R)},onscroll:yt,children:(t,n=w,r=w)=>{var c=i(),u=A(c),d=e=>{ue(e,{get direction(){return n().direction},get rows(){return n().rows}})},f=t=>{var r=ot(),i=E(r),a=v(i,!0);e(r),S(()=>s(a,n().label)),l(t,r)},p=e=>{var t=st();let n;S(()=>n=_(t,1,`new-messages-divider`,null,n,{"is-clearing":o(H)})),l(e,t)},m=e=>{rt(e,{get group(){return n().group},get currentUserID(){return a.currentUserID},get reactionController(){return a.reactionController},get reactionsDisabled(){return ae()},get selectedThreadID(){return a.selectedThreadID},get mentionPeople(){return ie()},get mentionAttentionUserID(){return a.mentionAttentionUserID},get replyContext(){return o(_e)},get canDeleteAnyMessage(){return oe()},get deletingMessageIDs(){return se()},get editController(){return a.editController},get editScope(){return de()},get onMessageEdited(){return a.onMessageEdited},get onOpenProfile(){return a.onOpenProfile},get onReply(){return a.onReply},get onOpenThread(){return a.onOpenThread},get onJumpToQuote(){return a.onJumpToQuote},get onOpenImage(){return a.onOpenImage},get onOpenArtifact(){return a.onOpenArtifact},get onRetry(){return a.onRetry},get onDiscard(){return a.onDiscard},get onDeleteMessage(){return a.onDeleteMessage},get topics(){return fe()},get onSelectTopic(){return pe()},get channelID(){return ce()},get pinnedMessageIDs(){return le()},get onTogglePin(){return a.onTogglePin},get onCopyLink(){return a.onCopyLink}})};C(u,e=>{n().kind===`loader`?e(d):n().kind===`day`?e(f,1):n().kind===`divider`?e(p,2):n().kind===`group`&&e(m,3)}),l(t,c)},$$slots:{default:!0}}),e=>x(I,e,!0),()=>o(I)),e(n),k(n,e=>x(L,e),()=>o(L)),l(t,n)};C(St,e=>{!c()&&a.messages.length===0?e(Q):a.messages.length>0&&e(Ct,1)});var wt=y(St,2),Tt=n=>{var r=lt();let i;var a=E(r),c=E(a),u=v(c);e(a);var d=y(a,2);e(r),S(e=>{i=_(r,1,`unread-bar`,null,i,{"is-clearing":o(H)}),D(r,`aria-hidden`,o(H)?`true`:void 0),a.disabled=o(H),D(a,`aria-label`,e),s(u,`${(o(V)>99?`99+`:o(V))??``} new message${o(V)===1?``:`s`}${O()?` since ${O()}`:``}`),d.disabled=o(H)},[()=>`Jump to ${o(V)>0?o(V):``} new message${o(V)===1?``:`s`}`.replace(/ +/g,` `)]),t(`click`,a,gt),t(`click`,d,nt),l(n,r)};C(wt,e=>{!c()&&a.messages.length>0&&o(V)>0&&e(Tt)}),e(bt),S(()=>xt=_(bt,1,`messages`,null,xt,{"is-revealing":c()||!o(K)&&a.messages.length>0})),t(`pointerdown`,bt,function(...e){a.onActivateMessageComposer?.apply(this,e)}),t(`pointerup`,bt,function(...e){a.onInlineImagePointerUp?.apply(this,e)}),l(n,bt),f()}M([`pointerdown`,`pointerup`,`click`]);var ft=a(` `),pt=a(` `),mt=a(``),ht=a(`
`),gt=a(``),_t=a(`
User kind
`),Z=a(`

`),vt=a(`

Blocked.

`),yt=a(``),bt=a(``),xt=a(``),St=a(``),Q=a(`
Moderation
`),Ct=a(`

Profile

Active
Contact information
Handle
User ID
About

`,1);function wt(n,i){r(i,!0);let a=h(i,`messagePending`,3,!1),c=h(i,`messageError`,3,``),u=j(()=>i.profile.kind===`bot`?i.profile.owner_user_id?`Bot of ${i.profile.owner_user_id}`:`Service bot`:``),d=j(()=>i.moderation?.role||`member`),p=j(()=>!!i.moderation&&o(d)!==`owner`&&(i.currentUserRole===`owner`||i.currentUserRole===`moderator`&&(o(d)===`member`||o(d)===`guest`))),m=j(()=>i.currentUser?.id!==i.profile.id&&o(p)),g=j(()=>!!i.moderation?.blocked_at),_=j(()=>o(d));var b=Ct(),x=A(b),w=E(x),ee=y(E(w),2),T=v(ee,!0);e(w);var te=y(w,2);e(x);var D=y(x,2),O=E(D),k=E(O);B(k,{class:`profile-avatar`,get id(){return i.profile.id},get name(){return i.profile.display_name},get src(){return i.profile.avatar_url},size:240,loading:`eager`,fetchPriority:`auto`}),e(O);var M=y(O,2),N=E(M),P=E(N),F=E(P),re=v(F,!0),ie=y(F,2),ae=e=>{var t=ft(),n=v(t,!0);S(()=>s(n,o(u))),l(e,t)};C(ie,e=>{o(u)&&e(ae)});var oe=y(ie,2),se=e=>{var t=pt(),n=v(t,!0);S(e=>s(n,e),[()=>z(i.profile.handle)]),l(e,t)};C(oe,e=>{i.profile.handle&&e(se)}),e(P);var ce=y(P,2),le=e=>{var n=mt();t(`click`,n,function(...e){i.onEdit?.apply(this,e)}),l(e,n)};C(ce,e=>{i.currentUser?.id===i.profile.id&&i.onEdit&&e(le)}),e(N);var ue=y(N,4),de=n=>{var r=ht(),o=E(r),c=v(o,!0);e(r),S(()=>{o.disabled=a(),s(c,a()?`Starting…`:`Message`)}),t(`click`,o,()=>i.onMessage?.(i.profile.id)),l(n,r)};C(ue,e=>{i.currentUser?.id!==i.profile.id&&i.onMessage&&e(de)});var fe=y(ue,2),pe=e=>{var t=gt(),n=v(t,!0);S(()=>s(n,c())),l(e,t)};C(fe,e=>{c()&&e(pe)});var me=y(fe,2),I=E(me),L=y(E(I),2),he=e=>{var n=mt();t(`click`,n,function(...e){i.onEdit?.apply(this,e)}),l(e,n)};C(L,e=>{i.currentUser?.id===i.profile.id&&i.onEdit&&e(he)}),e(I);var R=y(I,2),ge=y(E(R),2),_e=y(E(ge),2),ve=v(_e,!0);e(ge),e(R);var ye=y(R,2),xe=y(E(ye),2),Se=y(E(xe),2),Ce=v(Se,!0);e(xe),e(ye);var V=y(ye,2),H=t=>{var n=_t(),r=y(E(n),2),i=y(E(r),2),a=v(i,!0);e(r),e(n),S(()=>s(a,o(u))),l(t,n)};C(V,e=>{i.profile.kind===`bot`&&e(H)}),e(me);var U=y(me,2),we=y(E(U),2),Te=v(we);e(U);var W=y(U,2),Ee=n=>{var r=Q(),a=E(r),c=y(E(a),2),u=v(c,!0);e(a);var d=y(a,2),f=e=>{var t=Z(),n=v(t);S(()=>s(n,`${i.moderation.posts_remaining??``} of ${i.moderation.post_limit??``} waiting-room posts left today.`)),l(e,t)};C(d,e=>{i.moderation.role===`guest`&&i.moderation.post_limit>0&&e(f)});var p=y(d,2),m=e=>{var t=Z(),n=v(t);S(e=>s(n,`Timed out until ${e??``}.`),[()=>new Date(i.moderation.timeout_until).toLocaleString()]),l(e,t)};C(p,e=>{i.moderation.timeout_until&&e(m)});var h=y(p,2),b=e=>{var t=vt();l(e,t)};C(h,e=>{i.moderation.blocked_at&&e(b)});var x=y(h,2),w=E(x),ee=e=>{var n=yt();t(`click`,n,()=>i.onApprove?.(i.profile.id)),l(e,n)};C(w,e=>{i.moderation.role===`guest`&&i.onApprove&&e(ee)});var T=y(w,2),te=e=>{var n=bt();t(`click`,n,()=>i.onTimeout?.(i.profile.id)),l(e,n)};C(T,e=>{i.onTimeout&&e(te)});var D=y(T,2),O=e=>{var n=xt();t(`click`,n,()=>i.onUnblock?.(i.profile.id)),l(e,n)},k=e=>{var n=St();t(`click`,n,()=>i.onBlock?.(i.profile.id)),l(e,n)};C(D,e=>{o(g)&&i.onUnblock?e(O):!o(g)&&i.onBlock&&e(k,1)}),e(x),e(r),S(()=>s(u,o(_))),l(n,r)};C(W,e=>{o(m)&&i.moderation&&e(Ee)}),e(M),e(D),S((e,t)=>{s(T,i.profile.display_name),ne(O,`--hue: ${e??``}deg`),s(re,i.profile.display_name),s(ve,t),s(Ce,i.profile.id),s(Te,`Member of ${(i.workspaceName||`this workspace`)??``}.`)},[()=>be(i.profile.id),()=>i.profile.handle?z(i.profile.handle):`No handle set`]),t(`click`,te,function(...e){i.onClose?.apply(this,e)}),l(n,b),f()}M([`click`]);export{Ce as i,dt as n,Ne as r,wt as t}; \ No newline at end of file +import{At as e,B as t,D as n,Et as r,F as i,I as a,K as o,N as s,O as c,P as l,R as u,S as d,Tt as f,V as p,X as m,a as h,at as g,b as _,dt as v,ft as y,gt as b,ht as x,it as S,j as C,jt as w,k as ee,kt as T,lt as E,n as te,p as D,pt as O,s as k,ut as A,y as ne,yt as j,z as M}from"./CxKeDCcw.js";import"./xihTtKlq.js";import{u as N}from"./Dsl_OP1c.js";import{A as P,C as F,L as re,M as ie,N as ae,O as oe,P as se,a as ce,c as le,d as ue,h as de,i as fe,k as pe,l as me,m as I,n as L,o as he,r as R,s as ge,t as _e,u as ve}from"./HlY492D_.js";import{c as ye,l as z,n as be,t as B}from"./ZgTSXUg-.js";import{t as xe}from"./DlGnnCJo.js";import{t as Se}from"./FDulIy0t.js";var Ce=class{scope;reads=new Set;constructor(e){this.scope=e}get pending(){return this.reads.size>0}clear(){this.reads.clear()}prune(){for(let e of this.reads)e.current()||this.reads.delete(e)}updateMessage(e){for(let t of this.reads)if(t.messages.size+t.authors.size<=1e3){let n=t.messages.get(e.id);t.messages.set(e.id,n?pe(n,e):e)}return t=>t.id===e.id?pe(t,e):t}updateAuthor(e){for(let t of this.reads)t.messages.size+t.authors.size<=1e3&&t.authors.set(e.id,{...t.authors.get(e.id),...e});let t=t=>t?.id===e.id?{...t,...e}:t;return e=>({...e,author:t(e.author),quoted_author:t(e.quoted_author)})}async run(e,t,n=()=>!0){let r=this.scope(),i={messages:new Map,authors:new Map,current:()=>this.reads.has(i)&&this.scope()===r&&n()};this.reads.add(i);try{let n=await e();if(!i.current())return;if(i.messages.size+i.authors.size>1e3)throw Error(`Too many messages changed while loading. Please try again.`);let r=e=>{let t=i.messages.get(e.id);return t&&(e=pe(e,t)),{...e,author:e.author&&{...e.author,...i.authors.get(e.author.id)},quoted_author:e.quoted_author&&{...e.quoted_author,...i.authors.get(e.quoted_author.id)}}};return`messages`in n?n.messages=n.messages.map(r):`message`in n?n.message=r(n.message):(n.root=r(n.root),n.replies=n.replies.map(r),n.thread_state=oe(n.root.thread_state??null,n.thread_state)),t(n),n}catch(e){if(i.current())throw e}finally{this.reads.delete(i)}}},V={bash:{glyph:`🖥`,action:`Ran shell command`},exec:{glyph:`🖥`,action:`Ran shell command`},command:{glyph:`🖥`,action:`Ran shell command`},bashsession:{glyph:`🖥`,action:`Managed shell session`},sessions_send:{glyph:`🖥`,action:`Managed shell session`},read:{glyph:`📖`,action:`Read file`},write:{glyph:`📝`,action:`Wrote file`},edit:{glyph:`✏`,action:`Edited file`},apply_patch:{glyph:`🧩`,action:`Applied patch`},applypatch:{glyph:`🧩`,action:`Applied patch`},browsercontrol:{glyph:`🌐`,action:`Controlled browser`},websearch:{glyph:`🔍`,action:`Searched the web`},webfetch:{glyph:`🔗`,action:`Fetched a page`},image:{glyph:`🖼`,action:`Analyzed image`},imagecreate:{glyph:`🎨`,action:`Generated image`},scheduler:{glyph:`⏰`,action:`Scheduled a job`},sendmessage:{glyph:`📤`,action:`Sent a message`},message:{glyph:`📤`,action:`Sent a message`},systemctl:{glyph:`⚙`,action:`Controlled the system`},process:{glyph:`⚙`,action:`Managed a process`},devicecontrol:{glyph:`📱`,action:`Controlled a device`},pdfparse:{glyph:`📄`,action:`Parsed a PDF`},statuscheck:{glyph:`📊`,action:`Checked status`}},H=[{test:e=>e.includes(`search`),glyph:`🔍`,action:`Searched`},{test:e=>e.includes(`fetch`),glyph:`🔗`,action:`Fetched`},{test:e=>e.includes(`browser`),glyph:`🌐`,action:`Controlled browser`},{test:e=>e.includes(`patch`),glyph:`🧩`,action:`Applied patch`},{test:e=>e.includes(`write`),glyph:`📝`,action:`Wrote file`},{test:e=>e.includes(`edit`),glyph:`✏`,action:`Edited file`},{test:e=>e.includes(`read`),glyph:`📖`,action:`Read file`},{test:e=>e.includes(`session`),glyph:`🖥`,action:`Managed shell session`},{test:e=>e.includes(`bash`)||e.includes(`shell`)||e.includes(`exec`),glyph:`🖥`,action:`Ran command`},{test:e=>e.includes(`image`),glyph:`🖼`,action:`Worked with image`},{test:e=>e.includes(`message`)||e.includes(`send`),glyph:`📤`,action:`Sent a message`},{test:e=>e.includes(`agent`)||e.includes(`subagent`),glyph:`🤖`,action:`Ran a sub-agent`},{test:e=>e.includes(`schedul`)||e.includes(`cron`),glyph:`⏰`,action:`Scheduled a job`},{test:e=>e.includes(`device`),glyph:`📱`,action:`Controlled a device`},{test:e=>e.includes(`file`)||e.includes(`dir`),glyph:`📁`,action:`Worked with files`}];function U(e,t){let n=String(e||``).trim(),r=n.toLowerCase().replace(/[^a-z0-9_]/g,``),i=String(t||``).trim()||void 0,a=V[r];if(a)return{name:n,glyph:a.glyph,action:a.action,detail:i};for(let e of H)if(e.test(r))return{name:n,glyph:e.glyph,action:e.action,detail:i};return{name:n||`tool`,glyph:`🔧`,action:`Used tool`,detail:i}}var we=a(`
`),Te=a(` `),W=a(` `),Ee=a(`
`),De=a(`
`),G=a(`
`),Oe=a(`
`),ke=a(`
`),K=a(`
`);function Ae(a,u){r(u,!0);let p=h(u,`mentionPeople`,19,()=>[]),m=b(!0),w=b(void 0);g(()=>{(o(w)===void 0||u.block.final!==o(w))&&(x(w,u.block.final,!0),x(m,!u.block.final))});let ee=O({});function T(e){ee[e]=!ee[e]}function te(e){let t=e.match(/^\*\*([^]*?)\*\*\s*\n*([^]*)$/);if(!t)return{text:e};let n=t[1].trim(),r=t[2].trim();return{head:n||void 0,text:r}}let k=j(()=>u.block.items.map(e=>e.type===`tool`?{item:e,tool:U(e.name,e.detail)}:{item:e,tool:null})),ne=j(()=>u.block.final?o(m)?`expanded`:`collapsed`:`live`),M=j(()=>o(m)?`Hide preamble`:`Show preamble`);var N=K();let P;var F=E(N),ie=E(F);let ae;var oe=y(ie,2);let se;var ce=v(oe,!0),le=y(oe,2),ue=v(le,!0);e(F);var de=y(F,2),fe=r=>{var a=ke();c(a,21,()=>o(k),e=>e.item.id,(r,a)=>{var c=i(),f=A(c),m=t=>{var r=we();n(r,()=>I(o(a).item.body),!0),e(r),d(r,e=>re?.(e)),d(r,(e,t)=>ve?.(e,t),()=>({people:p(),attentionUserID:u.mentionAttentionUserID})),l(t,r)},h=r=>{let i=j(()=>ee[o(a).item.id]===!0);var c=Oe();let f;var m=E(c),h=E(m);let g;var b=y(h,2),x=v(b,!0),w=y(b,2),O=v(w,!0),k=y(w,2),A=e=>{var t=Te(),n=v(t,!0);S(()=>s(n,o(a).tool.name)),l(e,t)};C(k,e=>{o(a).tool.name&&o(a).tool.name!==`tool`&&e(A)});var ne=y(k,2),M=e=>{var t=W(),n=v(t,!0);S(()=>{D(t,`title`,o(a).tool.detail),s(n,o(a).tool.detail)}),l(e,t)};C(ne,e=>{!o(i)&&o(a).tool.detail&&e(M)}),e(m);var N=y(m,2),P=t=>{let r=j(()=>te(o(a).item.full));var i=G(),c=E(i),f=e=>{var t=Ee(),n=v(t,!0);S(()=>s(n,o(r).head)),l(e,t)};C(c,e=>{o(r).head&&e(f)});var m=y(c,2),h=t=>{var i=De();n(i,()=>I(o(r).text),!0),e(i),d(i,e=>re?.(e)),d(i,(e,t)=>ve?.(e,t),()=>({people:p(),attentionUserID:u.mentionAttentionUserID})),l(t,i)};C(m,e=>{o(r).text&&e(h)}),e(i),l(t,i)};C(N,e=>{o(i)&&e(P)}),e(c),S(()=>{f=_(c,1,`preamble-tool`,null,f,{expanded:o(i)}),D(m,`aria-expanded`,o(i)),g=_(h,1,`tool-line-chevron`,null,g,{open:o(i)}),s(x,o(a).tool.glyph),s(O,o(a).tool.action)}),t(`click`,m,()=>T(o(a).item.id)),l(r,c)};C(f,e=>{o(a).item.type===`commentary`?e(m):o(a).tool&&e(h,1)}),l(r,c)}),e(a),l(r,a)};C(de,e=>{o(m)&&e(fe)}),e(N),S(()=>{P=_(N,1,`preamble-contract`,null,P,{"is-final":u.block.final}),D(F,`aria-expanded`,o(m)),ae=_(ie,1,`preamble-chevron`,null,ae,{open:o(m)}),se=_(oe,1,`preamble-state`,null,se,{"is-live":!u.block.final}),s(ce,o(ne)),s(ue,o(M))}),t(`click`,F,()=>x(m,!o(m))),l(a,N),f()}M([`click`]);var je=a(``),Me=a(` `);function Ne(e,n){r(n,!0);var a=i(),o=A(a),c=e=>{var r=i(),a=A(r),o=e=>{var r=je(),i=v(r,!0);S(()=>{D(r,`aria-label`,`Filter by topic ${n.topic.name}`),s(i,n.topic.name)}),t(`click`,r,e=>{e.stopPropagation(),n.onSelect(n.topic.id)}),l(e,r)},c=e=>{var t=Me(),r=v(t,!0);S(()=>s(r,n.topic.name)),l(e,t)};C(a,e=>{n.onSelect?e(o):e(c,-1)}),l(e,r)};C(o,e=>{n.topic&&e(c)}),l(e,a),f()}M([`click`]);var Pe=a(`
This message was deleted.
`),Fe=a(`(edited)`),Ie=a(`
`),Le=a(``),Re=a(``),ze=a(``),Be=a(`
`,1),Ve=a(``),He=a(` `,1),Ue=a(``),q=a(` `),We=a(``),Ge=a(`Couldn't create link`),Ke=a(` `,1),qe=a(` `),Je=a(` `,1),Ye=a(` `,1),Xe=a(` `,1),Ze=a(`
`),Qe=a(`
`),$e=a(`
`);function et(a,u){r(u,!0);let w=h(u,`mentionPeople`,19,()=>[]),T=h(u,`reactionsDisabled`,3,!1),ne=h(u,`canDeleteAnyMessage`,3,!1),M=h(u,`deleting`,3,!1),P=h(u,`editScope`,3,``),oe=h(u,`topics`,19,()=>[]),ue=h(u,`onSelectTopic`,3,()=>{}),pe=h(u,`channelID`,3,``),ye=h(u,`pinned`,3,!1),z=j(()=>u.editController?.session(P())),be=j(()=>o(z)?.surface===`timeline`&&o(z).messageID===u.message.id);async function B(){await m(),o(Z)?.focus()}function xe(){u.editController?.start(P(),u.message,`timeline`)===`cancelled`&&B()}function Se(){u.editController?.cancel(P(),`timeline`)&&B()}async function Ce(){if(!u.editController)return;let e=await u.editController.save(P(),u.message,e=>u.onMessageEdited?.(e));(e===`saved`||e===`cancelled`)&&await B()}let V=j(()=>u.message.status===`pending`),H=j(()=>u.message.status===`failed`),U=j(()=>!!u.message.deleted_at),we=j(()=>ne()||!!u.currentUserID&&(u.message.author?.id||u.message.author_id)===u.currentUserID),Te=j(()=>!!u.currentUserID&&(u.message.author?.id||u.message.author_id)===u.currentUserID),W=j(()=>u.message.preamble_block),Ee=j(()=>!!u.previousMessage?.preamble_block&&!o(W)),De=j(()=>!!o(W)&&!!u.nextMessage&&!u.nextMessage?.preamble_block),G=j(()=>u.message.thread_state?.reply_count||0),Oe=j(()=>o(G)>0),ke=j(()=>ae(u.message)),K=j(()=>u.selectedThreadID===u.message.id),je=j(()=>!o(W)&&!o(V)&&!o(H)&&(!o(U)||o(Oe)||o(K))),Me=j(()=>oe().find(e=>e.id===u.message.topic_id));function et(e){if(qt||o(Ht)){qt=!1,e.preventDefault(),e.stopPropagation();return}o(je)&&(window.getSelection()?.toString()||e.target?.closest(zt)||u.onOpenThread(u.message))}function tt(e){return e.addEventListener(`click`,et),{destroy(){e.removeEventListener(`click`,et)}}}let J=b(!1),Y=b(!1),nt=b(``),X=b(``),rt=b(``),it=b(void 0),at=b(!1),ot=b(``),st=b(!1),ct=b(!1),lt=b(void 0),ut=b(!1),dt=b(!1),ft=j(()=>o(ut)||o(dt)||u.selected),pt=b(!1);function mt(){let e=o(lt)?.closest(`.messages-scroll`);if(!o(lt)||!e){x(pt,!1);return}let t=o(lt).getBoundingClientRect().top-e.getBoundingClientRect().top;x(pt,t<26)}let ht=b(void 0),gt=b(void 0),_t=b(void 0),Z=b(void 0),vt,yt,bt=!1,xt=j(()=>`toolbar-reaction-picker-${u.message.id}`),St=j(()=>u.reactionController.pending(u.message.id)),Q=j(()=>T()||!u.currentUserID||o(V)||o(H)||o(St));function Ct(e){o(Q)||u.reactionController.toggle(u.message,e)}function wt(){o(Q)||(o(J)||x(st,fe(o(ht),130),!0),x(J,!o(J)))}function Tt(e){o(Q)||(u.reactionController.toggle(u.message,e),x(J,!1))}function Et(){x(J,!1),o(_t)?.focus()}async function Dt(){o(Y)||x(ct,fe(o(gt),160),!0),x(Y,!o(Y)),o(Y)&&(await m(),At()[0]?.focus())}function Ot(){if(o(Vt)){Qt(o(Z));return}Dt()}function kt(e=!0){x(Y,!1),e&&o(Z)?.focus()}function At(){return[...o(gt)?.querySelectorAll(`[role="menuitem"]:not(:disabled)`)??[]].filter(e=>e.getClientRects().length>0)}function jt(e){if(e.key===`Escape`){e.preventDefault(),kt();return}if(e.key===`Tab`){kt(!1);return}let t=At();if(t.length===0)return;let n=t.indexOf(document.activeElement),r;e.key===`ArrowDown`?r=n<0?0:(n+1)%t.length:e.key===`ArrowUp`?r=n<=0?t.length-1:n-1:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==void 0&&(e.preventDefault(),t[r]?.focus())}function Mt(e){bt||(x(nt,e,!0),vt&&window.clearTimeout(vt),vt=window.setTimeout(()=>{x(nt,``),vt=void 0},1800))}async function Nt(){kt(),await Pt()}async function Pt(){try{if(!navigator.clipboard)throw Error(`Clipboard unavailable`);return await navigator.clipboard.writeText(u.message.body??``),Mt(`copied`),!0}catch{return Mt(`failed`),!1}}async function Ft(){if(!u.onCopyLink||o(X)===`pending`)return{copied:!1};x(X,`pending`);let e;try{e=await u.onCopyLink(u.message)}catch{return x(X,`failed`),{copied:!1}}try{if(!navigator.clipboard)throw Error(`Clipboard unavailable`);return await navigator.clipboard.writeText(e),x(X,``),Mt(`copied`),{copied:!0}}catch{return x(X,``),{copied:!1,fallback:e}}}async function It(){let e=await Ft();!e.copied&&!e.fallback||(kt(!1),e.fallback?(x(it,o(Z),!0),x(rt,e.fallback,!0)):o(Z)?.focus())}function Lt(){kt(!1),xe()}function Rt(){kt(!1),u.onDeleteMessage?.(u.message)}let zt=`a, button, input, textarea, select, .attachment-grid, .media-tile, .markdown img, .gif-player, .markdown-table-scroll, .message-actions, .message-failed`,Bt=typeof window<`u`?window.matchMedia(`(hover: none), (pointer: coarse)`):null,Vt=b(O(Bt?.matches??!1)),Ht=b(!1),Ut,Wt,Gt=0,Kt=b(void 0),qt=!1,Jt=j(()=>`message-action-sheet-${u.message.id}`);g(()=>{if(!Bt)return;let e=()=>{x(Vt,Bt.matches,!0)};return Bt.addEventListener(`change`,e),()=>Bt.removeEventListener(`change`,e)});function Yt(){Ut!==void 0&&(window.clearTimeout(Ut),Ut=void 0)}function Xt(){Wt?.(),Wt=void 0}function Zt(){yt!==void 0&&(window.clearTimeout(yt),yt=void 0)}function Qt(e){Zt(),Gt+=1,x(Kt,e,!0),x(Y,!1),x(J,!1),x(Ht,!0)}function $t(e){if(e.pointerType!==`touch`||!e.isPrimary||e.button!==0||o(W)||o(U)||o(V)||o(H)||o(be)||e.target?.closest(zt))return;Xt();let t=e.pointerId,n=e.clientX,r=e.clientY;Ut=window.setTimeout(()=>{Ut=void 0,qt=!0,Qt()},450);let i=e=>{e.pointerId===t&&(Math.abs(e.clientX-n)>10||Math.abs(e.clientY-r)>10)&&s()},a=e=>{e.pointerId===t&&s()},s=()=>{Yt(),window.removeEventListener(`pointermove`,i),window.removeEventListener(`pointerup`,a),window.removeEventListener(`pointercancel`,a),Wt===s&&(Wt=void 0)};Wt=s,window.addEventListener(`pointermove`,i),window.addEventListener(`pointerup`,a),window.addEventListener(`pointercancel`,a)}function en(e){(o(Ht)||Ut!==void 0)&&e.preventDefault()}function tn(){Zt(),Gt+=1,x(Ht,!1),qt=!1}function nn(e){tn(),!o(Q)&&u.reactionController.toggle(u.message,e)}function rn(){tn(),u.onOpenThread(u.message)}function an(){tn(),u.onReply(u.message,u.replyContext)}async function on(){Zt();let e=Gt;!await Pt()||!o(Ht)||e!==Gt||(yt=window.setTimeout(()=>{yt=void 0,!bt&&e===Gt&&tn()},900))}async function sn(){let e=await Ft();if(!e.copied&&!e.fallback)return;let t=o(Kt);tn(),e.fallback&&(await m(),x(it,t,!0),x(rt,e.fallback,!0))}function cn(){tn(),xe()}function ln(){tn(),u.onDeleteMessage?.(u.message)}async function un(){if(!(!pe()||!u.onTogglePin||o(at))){x(at,!0),x(ot,``);try{await u.onTogglePin(u.message,ye()),kt()}catch(e){x(ot,N(e,`Could not update pin`),!0)}finally{x(at,!1)}}}async function dn(){await un(),o(ot)||tn()}g(()=>{if(!o(J)&&!o(Y))return;let e=e=>{let t=e.target;o(J)&&o(ht)&&!o(ht).contains(t)&&x(J,!1),o(Y)&&o(gt)&&!o(gt).contains(t)&&x(Y,!1)};return document.addEventListener(`click`,e),()=>document.removeEventListener(`click`,e)}),g(()=>{o(Q)&&x(J,!1)}),te(()=>{bt=!0,vt&&window.clearTimeout(vt),Zt(),Xt()}),g(()=>{if(!(o(Y)||o(J)||o(ft))||!o(lt))return;let e=o(lt).parentElement;for(;e&&e.style.position!==`absolute`;)e=e.parentElement;if(!e)return;let t=e.style.zIndex;return e.style.zIndex=`10`,()=>{e.style.zIndex=t}});var $=$e();let fn;var pn=E($),mn=v(pn,!0),hn=y(pn,2),gn=E(hn),_n=e=>{Ae(e,{get block(){return o(W)},get mentionPeople(){return w()},get mentionAttentionUserID(){return u.mentionAttentionUserID}})},vn=e=>{var t=Pe();l(e,t)},yn=e=>{var t=i(),n=A(t),r=e=>{L(e,{get body(){return o(z).draft},get errorMessage(){return o(z).error},get saving(){return o(z).saving},onBody:e=>u.editController?.updateDraft(P(),e),onCancel:Se,onSave:Ce})};C(n,e=>{o(z)&&e(r)}),l(e,t)},bn=r=>{var i=Be(),a=A(i);Ne(a,{get topic(){return o(Me)},get onSelect(){return ue()}});var s=y(a,2);_e(s,{get message(){return u.message},get onJump(){return u.onJumpToQuote}});var f=y(s,2);n(f,()=>I(u.message.body),!0),e(f),d(f,e=>re?.(e)),d(f,(e,t)=>ve?.(e,t),()=>({people:w(),attentionUserID:u.mentionAttentionUserID}));var p=y(f,2),m=e=>{var t=Fe();S(e=>D(t,`title`,`Edited ${e??``}`),[()=>de(u.message.edited_at)]),l(e,t)};C(p,e=>{u.message.edited_at&&e(m)});var h=y(p,2),g=e=>{{let t=j(()=>u.reactionController.reactionsFor(u.message)),n=j(()=>u.reactionController.pending(u.message.id)),r=j(()=>u.reactionController.error(u.message.id)),i=j(()=>T()||!u.currentUserID);ge(e,{get messageId(){return u.message.id},get reactions(){return o(t)},get pending(){return o(n)},get error(){return o(r)},get disabled(){return o(i)},onToggle:e=>void u.reactionController.toggle(u.message,e)})}};C(h,e=>{!o(V)&&!o(H)&&e(g)});var _=y(h,2),v=t=>{var n=Ie();c(n,21,()=>u.message.attachments,e=>e.id,(e,t)=>{{let n=j(()=>F(o(t)));R(e,{get upload(){return o(t)},get url(){return o(n)},get onOpenImage(){return u.onOpenImage},get onOpenArtifact(){return u.onOpenArtifact}})}}),e(n),l(t,n)};C(_,e=>{u.message.attachments?.length&&e(v)});var b=y(_,2),x=n=>{var r=ze(),i=y(E(r),2),a=e=>{var n=Le();t(`click`,n,()=>u.onRetry?.(u.message)),l(e,n)};C(i,e=>{u.onRetry&&e(a)});var o=y(i,2),s=e=>{var n=Re();t(`click`,n,()=>u.onDiscard?.(u.message)),l(e,n)};C(o,e=>{u.onDiscard&&e(s)}),e(r),l(n,r)};C(b,e=>{o(H)&&e(x)}),l(r,i)};C(gn,e=>{o(W)?e(_n):o(U)?e(vn,1):o(be)?e(yn,2):e(bn,-1)});var xn=y(gn,2),Sn=n=>{var r=Ue();let i;var a=y(E(r),2),c=e=>{var t=He(),n=A(t),r=v(n,!0),i=y(n,2),a=e=>{var t=Ve(),n=v(t,!0);S(()=>{D(t,`datetime`,u.message.thread_state?.last_reply_at),s(n,o(ke))}),l(e,t)};C(i,e=>{o(ke)&&e(a)}),S(e=>s(r,e),[()=>ie(u.message)]),l(e,t)};C(a,e=>{(o(Oe)||o(K))&&e(c)}),e(r),S((e,t)=>{i=_(r,1,`thread-hint tooltip`,null,i,{"has-replies":o(Oe),"is-open":o(K)}),D(r,`data-tooltip`,e),D(r,`aria-label`,t)},[()=>se(u.message,u.selectedThreadID),()=>se(u.message,u.selectedThreadID)]),t(`click`,r,()=>u.onOpenThread(u.message)),l(n,r)};C(xn,e=>{o(je)&&e(Sn)}),e(hn);var Cn=y(hn,2),wn=n=>{var r=Qe(),i=E(r),a=e=>{var t=q();let n;var r=v(t,!0);S(()=>{n=_(t,1,`message-copy-status`,null,n,{"is-error":o(nt)===`failed`}),s(r,o(nt)===`copied`?`Copied`:`Couldn't copy`)}),l(e,t)};C(i,e=>{o(nt)&&e(a)});var d=y(i,2);c(d,17,()=>me,ee,(e,n)=>{var r=We(),i=v(r,!0);S(()=>{D(r,`aria-label`,`React with ${o(n)}`),D(r,`data-tooltip`,`React with ${o(n)}`),r.disabled=o(Q),s(i,o(n))}),t(`click`,r,()=>Ct(o(n))),l(e,r)});var f=y(d,2),p=E(f);k(p,e=>x(_t,e),()=>o(_t));var m=y(p,2),h=e=>{{let t=j(()=>o(st)?`above-right`:`below`);le(e,{get id(){return o(xt)},get placement(){return o(t)},get disabled(){return o(Q)},onPick:Tt,onEscape:Et})}};C(m,e=>{o(J)&&e(h)}),e(f),k(f,e=>x(ht,e),()=>o(ht));var g=y(f,4),b=y(g,2),w=y(b,4),T=E(w);let te;k(T,e=>x(Z,e),()=>o(Z));var O=y(T,2),ne=n=>{var r=Ze();let i;var a=E(r),c=y(a,2),d=n=>{var r=Ke(),i=A(r),a=y(E(i));e(i);var c=y(i,2),u=e=>{var t=Ge();l(e,t)};C(c,e=>{o(X)===`failed`&&e(u)}),S(()=>{i.disabled=o(X)===`pending`,s(a,` ${o(X)===`pending`?`Creating link…`:`Copy link`}`)}),t(`click`,i,()=>void It()),l(n,r)};C(c,e=>{pe()&&u.onCopyLink&&e(d)});var f=y(c,2),p=n=>{var r=Je(),i=A(r),a=y(E(i));e(i);var c=y(i,2),u=e=>{var t=qe(),n=v(t,!0);S(()=>s(n,o(ot))),l(e,t)};C(c,e=>{o(ot)&&e(u)}),S(()=>{i.disabled=o(at),s(a,` ${ye()?`Unpin message`:`Pin message`}`)}),t(`click`,i,un),l(n,r)};C(f,e=>{pe()&&u.onTogglePin&&e(p)});var m=y(f,2),h=e=>{var n=Ye(),r=y(A(n),2);t(`click`,r,Lt),l(e,n)};C(m,e=>{o(Te)&&u.editController&&P()&&!o(be)&&e(h)});var g=y(m,2),b=e=>{var n=Xe(),r=y(A(n),2);S(()=>r.disabled=M()),t(`click`,r,Rt),l(e,n)};C(g,e=>{o(we)&&u.onDeleteMessage&&e(b)}),e(r),S(()=>i=_(r,1,`message-menu`,null,i,{above:o(ct)})),t(`keydown`,r,jt),t(`click`,a,Nt),l(n,r)};C(O,e=>{o(Y)&&e(ne)}),e(w),k(w,e=>x(gt,e),()=>o(gt)),e(r),S(e=>{D(p,`aria-controls`,o(xt)),D(p,`aria-expanded`,o(J)),p.disabled=o(Q),D(g,`data-tooltip`,e),g.disabled=o(V)||o(H),b.disabled=o(V)||o(H),te=_(T,1,`message-actions-trigger`,null,te,{tooltip:!o(Vt),"tooltip-align-end":!o(Vt)}),D(T,`data-tooltip`,o(Vt)?void 0:`More actions`),D(T,`aria-haspopup`,o(Vt)?`dialog`:`menu`),D(T,`aria-controls`,o(Vt)?o(Jt):void 0),D(T,`aria-expanded`,o(Vt)?o(Ht):o(Y)),T.disabled=o(V)||o(H)},[()=>se(u.message,u.selectedThreadID)]),t(`click`,p,wt),t(`click`,g,()=>u.onOpenThread(u.message)),t(`click`,b,()=>u.onReply(u.message,u.replyContext)),t(`click`,T,Ot),l(n,r)};C(Cn,e=>{!o(W)&&!o(U)&&e(wn)});var Tn=y(Cn,2),En=e=>{{let t=j(()=>!o(Q)),n=j(()=>!o(V)&&!o(H)),r=j(()=>o(Te)&&!!u.editController&&!!P()&&!o(be)),i=j(()=>!!(pe()&&u.onTogglePin)),a=j(()=>o(we)&&!!u.onDeleteMessage),s=j(()=>!!(pe()&&u.onCopyLink));he(e,{get id(){return o(Jt)},get canReact(){return o(t)},get canReply(){return o(n)},get canOpenThread(){return o(je)},get canEdit(){return o(r)},get canPin(){return o(i)},get pinned(){return ye()},get pinning(){return o(at)},get pinError(){return o(ot)},get canDelete(){return o(a)},get deleting(){return M()},get copyStatus(){return o(nt)},get canCopyLink(){return o(s)},get copyLinkStatus(){return o(X)},onReact:nn,onOpenThread:rn,onReply:an,onCopy:on,onCopyLink:sn,onEdit:cn,onTogglePin:dn,onDelete:ln,onClose:tn,get returnFocus(){return o(Kt)}})}};C(Tn,e=>{o(Ht)&&e(En)});var Dn=y(Tn,2),On=e=>{ce(e,{get url(){return o(rt)},onClose:()=>x(rt,``),get returnFocus(){return o(it)}})};C(Dn,e=>{o(rt)&&e(On)}),e($),k($,e=>x(lt,e),()=>o(lt)),d($,e=>tt?.(e)),S((e,t)=>{fn=_($,1,`message-row`,null,fn,{selected:u.selected,"is-pending":o(V),"is-failed":o(H),"is-deleted":o(U),"is-preamble":e,"is-preamble-collapsed":o(W)?.final===!0,"is-preamble-live":o(W)?.final===!1,"before-final-message":o(De),"after-preamble":o(Ee),"can-open-thread":o(je),editing:o(be),"menu-open":o(Y)||o(J),"actions-flip":o(pt)}),D($,`data-message-id`,u.message.id),s(mn,t)},[()=>!!o(W),()=>u.index===0?``:de(u.message.created_at)]),t(`pointerdown`,$,$t),t(`contextmenu`,$,en),p(`mouseenter`,$,()=>{!o(ut)&&!o(dt)&&mt(),x(ut,!0)}),p(`mouseleave`,$,()=>x(ut,!1)),t(`focusin`,$,()=>{!o(ut)&&!o(dt)&&mt(),x(dt,!0)}),t(`focusout`,$,e=>{o(lt)?.contains(e.relatedTarget)||x(dt,!1)}),l(a,$),f()}M([`pointerdown`,`contextmenu`,`focusin`,`focusout`,`click`,`keydown`]);var tt=a(` deleted bot`,1),J=a(`bot`),Y=a(` `,1),nt=a(` `),X=a(`
`);function rt(n,i){r(i,!0);let a=h(i,`reactionsDisabled`,3,!1),u=h(i,`mentionPeople`,19,()=>[]),d=h(i,`canDeleteAnyMessage`,3,!1),p=h(i,`deletingMessageIDs`,19,()=>new Set),m=h(i,`channelID`,3,``),g=h(i,`pinnedMessageIDs`,19,()=>new Set),b=h(i,`editScope`,3,``),x=h(i,`topics`,19,()=>[]),w=h(i,`onSelectTopic`,3,()=>{}),ee=j(()=>i.group.messages[0]?.author),te=j(()=>o(ee)?.kind===`bot`),D=j(()=>!o(te)&&!!i.currentUserID&&i.group.authorID===i.currentUserID);var O=X();let k;var ne=E(O);{let e=j(()=>i.group.authorDeleted?`avatar`:`avatar avatar-button`),t=j(()=>i.group.authorDeleted?void 0:`View profile for ${i.group.authorName}`);B(ne,{get class(){return o(e)},get id(){return i.group.authorID},get name(){return i.group.authorName},get src(){return i.group.authorAvatarURL},size:38,get buttonLabel(){return o(t)},onclick:()=>i.onOpenProfile(i.group.messages[0]?.author)})}var M=y(ne,2),N=E(M),P=E(N),F=e=>{var t=tt(),n=A(t),r=v(n,!0);T(2),S(()=>s(r,i.group.authorName)),l(e,t)},re=e=>{var n=Y(),r=A(n),a=v(r,!0),c=y(r,2),u=e=>{var t=J();l(e,t)};C(c,e=>{o(te)&&e(u)}),S(()=>s(a,i.group.authorName)),t(`click`,r,()=>i.onOpenProfile(i.group.messages[0]?.author)),l(e,n)};C(P,e=>{i.group.authorDeleted?e(F):e(re,-1)});var ie=y(P,2),ae=e=>{var t=nt(),n=v(t,!0);S(e=>s(n,e),[()=>z(i.group.authorHandle)]),l(e,t)};C(ie,e=>{i.group.authorHandle&&e(ae)});var oe=y(ie,2),se=v(oe,!0);e(N);var ce=y(N,2);c(ce,19,()=>i.group.messages,e=>e.id,(e,t,n)=>{{let r=j(()=>i.selectedThreadID===o(t).id),s=j(()=>p().has(o(t).id)),c=j(()=>g().has(o(t).id));et(e,{get message(){return o(t)},get index(){return o(n)},get previousMessage(){return i.group.messages[o(n)-1]},get nextMessage(){return i.group.messages[o(n)+1]},get selected(){return o(r)},get replyContext(){return i.replyContext},get selectedThreadID(){return i.selectedThreadID},get mentionPeople(){return u()},get mentionAttentionUserID(){return i.mentionAttentionUserID},get currentUserID(){return i.currentUserID},get reactionController(){return i.reactionController},get reactionsDisabled(){return a()},get canDeleteAnyMessage(){return d()},get deleting(){return o(s)},get editController(){return i.editController},get editScope(){return b()},get onMessageEdited(){return i.onMessageEdited},get onReply(){return i.onReply},get onOpenThread(){return i.onOpenThread},get onJumpToQuote(){return i.onJumpToQuote},get onOpenImage(){return i.onOpenImage},get onOpenArtifact(){return i.onOpenArtifact},get onRetry(){return i.onRetry},get onDiscard(){return i.onDiscard},get onDeleteMessage(){return i.onDeleteMessage},get topics(){return x()},get onSelectTopic(){return w()},get channelID(){return m()},get pinned(){return o(c)},get onTogglePin(){return i.onTogglePin},get onCopyLink(){return i.onCopyLink}})}}),e(M),e(O),S(e=>{k=_(O,1,`message-group`,null,k,{"is-agent":o(te),"is-self":o(D)}),s(se,e)},[()=>de(i.group.timestamp)]),l(n,O),f()}M([`click`]);var it=a(`
Send a message in Markdown — code fences, lists, links all work. Threads open from any message.
`),at=a(`
`),ot=a(`
`),st=a(`
New
`),ct=a(`
`),lt=a(`
`),ut=a(`
`);function dt(n,a){r(a,!0);let c=h(a,`loading`,3,!1),d=h(a,`unreadCount`,3,0),p=h(a,`unreadBoundarySeq`,3,0),ee=h(a,`unreadBoundaryLoaded`,3,!1),O=h(a,`unreadSince`,3,``),ne=h(a,`hasOlder`,3,!1),M=h(a,`hasNewer`,3,!1),N=h(a,`loadingOlder`,3,!1),F=h(a,`loadingNewer`,3,!1),re=h(a,`prepending`,3,!1),ie=h(a,`mentionPeople`,19,()=>[]),ae=h(a,`reactionsDisabled`,3,!1),oe=h(a,`canDeleteAnyMessage`,3,!1),se=h(a,`deletingMessageIDs`,19,()=>new Set),ce=h(a,`channelID`,3,``),le=h(a,`pinnedMessageIDs`,19,()=>new Set),de=h(a,`editScope`,3,``),fe=h(a,`topics`,19,()=>[]),pe=h(a,`onSelectTopic`,3,()=>{}),me=1.5,I=b(void 0),L=b(void 0),he=b(void 0),R=b(0),ge=b(0),_e=j(()=>a.selectedDirect?`dm`:`channel`),ve=b(``),z=b(-1),be=b(0),B=j(()=>o(ve)===a.viewKey&&o(z)===p()&&d()<=o(be)?0:d()),Ce=b(``),V=b(0),H=b(!1),U,we=j(()=>o(B)>0?o(B):o(V));function Te(){U&&=(window.clearTimeout(U),void 0)}g(()=>{if(o(Ce)&&o(Ce)!==a.viewKey){Te(),x(V,0),x(Ce,``),x(H,!1);return}if(o(B)>0){Te(),x(Ce,a.viewKey,!0),x(V,o(B),!0),x(H,!1);return}o(V)>0&&!o(H)&&(x(H,!0),U=window.setTimeout(()=>{U=void 0,!(o(B)>0)&&(x(V,0),x(Ce,``),x(H,!1))},180))}),te(Te);let W=j(()=>{let e=p()+1;if(o(we)<=0||e<=0)return!1;let t=1/0,n=0;for(let e of a.messages){if(e.parent_message_id)continue;let r=e.channel_seq||0;r<=0||(t=Math.min(t,r),n=Math.max(n,r))}return t<=e&&n>=e}),Ee=j(()=>ee()&&o(W)),De=j(()=>{let e=[],t=!1,n=e=>!o(Ee)||e.parent_message_id||e.author?.id===a.currentUserID||e.author_id===a.currentUserID?!1:o(we)>0&&(e.channel_seq||0)>p();for(let r of P(a.messages)){let i=-1;if(!t){for(let e=0;ea.messages.map(e=>{let t=e.preamble_block;if(!t)return``;let n=t.items.map(e=>e.type===`commentary`?`${e.id}\u0000${e.body}`:`${e.id}\u0000${e.name}\u0000${e.detail||``}\u0000${e.full}`).join(``);return`${e.id}\u0000${t.final?`final`:`live`}\u0000${n}`}).filter(Boolean).join(``)),ke=b(!0),K=b(!1),Ae,je=0,Me=``,Ne=``,Pe,Fe=b(void 0),Ie=0,Le=!1,Re=!1,ze=!1,Be=!1,Ve=0,He=0;function Ue(e=!0){return e&&(Le=!1,x(K,!0)),He+=1,He}function q(e,t){return dt(e)&&t===He}function We(e=2){let t=++Ve;Re=!0;let n=e=>{requestAnimationFrame(()=>{if(t===Ve){if(e<=1){Re=!1;return}n(e-1)}})};n(e)}function Ge(){if(!o(I))return 0;let e=o(I).getScrollSize()+o(R);return Math.max(0,e-o(I).getScrollOffset()-o(I).getViewportSize())}function Ke(){return!o(I)||Ge()<=me}function qe(e=me){return!o(I)||Ge()<=e}function Je(){if(!o(I))return{atBottom:!0,nearOlder:!1,nearNewer:!1};let e=Ge();return{atBottom:Ke(),nearOlder:o(I).getScrollOffset()-o(R)<=160,nearNewer:e<=260}}function Ye(){a.onHistorySettled?.(Je())}function Xe(e=!1){M()||!e&&o(B)>0||a.onReachedBottom?.()}g(()=>{if(F()){Be=!0;return}Be&&(Be=!1,ze=!1)});async function Ze(){!o(I)||o(De).length===0||(G=!M(),await Qe(Ue()))}async function Qe(e=Ue()){if(!o(I)||!o(L)||o(De).length===0)return;let t=a.viewKey;document.activeElement===o(L)&&o(L).blur();let n=-1;for(let r=0;r<6;r+=1){if(await m(),!o(I)||!o(L)||!q(t,e)||(G=!M(),We(2),o(L).scrollTop=o(L).scrollHeight,await X(),!o(I)||!q(t,e)))return;let r=o(I).getScrollSize(),i=n>=0&&Math.abs(r-n)<=me;if(n=r,i&&Ke())break}x(K,!0),G=!M(),Ke()&&(x(ke,!0),Xe(!0)),Ye()}g(()=>{if(!o(L))return;let e=o(L),t=()=>{let e=Ue();Re=!1,Z(a.viewKey,e)},n=e=>{e.defaultPrevented||e.ctrlKey||e.deltaY===0||(t(),e.deltaY>0&&M()&&Ke()&&(ze=!0,a.onLoadNewer?.(`wheel`)))},r=e=>{let n=e.target;e.defaultPrevented||!(n instanceof HTMLElement)||n.isContentEditable||n.closest(`input, textarea, select`)||e.key===` `&&n.closest(`button, [role=button]`)||[`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)&&t()},i=e=>{!e.defaultPrevented&&e.touches.length===1&&t()},s=n=>{n.target===e&&n.button===0&&t()};return e.addEventListener(`wheel`,n,{passive:!0}),e.addEventListener(`keydown`,r),e.addEventListener(`touchmove`,i,{passive:!0}),e.addEventListener(`pointerdown`,s),()=>{e.removeEventListener(`wheel`,n),e.removeEventListener(`keydown`,r),e.removeEventListener(`touchmove`,i),e.removeEventListener(`pointerdown`,s)}});function $e(e){return o(De).findIndex(t=>t.kind===`group`&&t.group.messages.some(t=>t.id===e))}let et=j(()=>{if(!ne()||c()||!re())return 0;let e=Math.max(o(ge),480);return Math.max(4,Math.ceil(e/52))});g(()=>{if(!o(L))return;let e=()=>{o(L)&&x(ge,o(L).clientHeight,!0)};e();let t=new ResizeObserver(e);return t.observe(o(L)),()=>t.disconnect()});let tt=0;g(()=>{if(!o(he)||!o(L)){x(R,0),tt=0;return}let e=o(he),t=()=>{let t=e.offsetHeight,n=tt;if(x(R,t,!0),tt=t,n>0&&t!==n){let e=t-n;o(L)&&o(L).scrollTop>0&&(o(L).scrollTop+=e)}};t();let n=new ResizeObserver(t);return n.observe(e),()=>{n.disconnect(),x(R,0),tt=0}});function J(){return o(De).findIndex(e=>e.kind===`divider`)}function Y(){let e=0;for(let t of a.messages)e=Math.max(e,t.channel_seq||0);return e}function nt(){x(ve,a.viewKey,!0),x(z,p()),x(be,d()),a.onMarkRead?.(Y())}function X(){return new Promise(e=>requestAnimationFrame(()=>e()))}function dt(e){return e===a.viewKey&&e===Ae}async function ft(e,t,n,r,i=0){We(3);for(let a=0;a<24;a++){if(!q(e,t)||!o(I)||!o(L))return!1;let a=o(L).querySelector(r);if(a){let e=a.getBoundingClientRect().top-o(L).getBoundingClientRect().top-i;if(Math.abs(e)<=me)return!0;o(L).scrollTop+=e}else{let e=n();if(e<0)return!1;o(L).scrollTop=o(R)+o(I).getItemOffset(e)}await X()}return!1}function pt(e,t,n){if(!o(I)||e()<0)return!1;G=!1;let r=a.viewKey,i=Ue();return ft(r,i,e,t).then(async a=>{q(r,i)&&(Ye(),await m(),q(r,i)&&(a&&=await ft(r,i,e,t),!a&&q(r,i)&&n?.()))}),!0}function mt(e){return pt(()=>$e(e),`[data-message-id="${CSS.escape(e)}"]`)}function ht(e=!0){return pt(J,`[data-unread-divider='true']`,e?a.onJumpToUnread:void 0)}function gt(){if(!(o(Ee)&&ht(!1))&&a.onJumpToUnread){a.onJumpToUnread();return}}function _t(){if(!o(I)||!o(L))return null;if(x(Fe,{atBottom:Ke()},!0),Ie=He,!o(Fe).atBottom){let e=o(L).getBoundingClientRect().top;for(let t of o(L).querySelectorAll(`[data-message-id]`)){let n=t.getBoundingClientRect();if(!(n.bottom<=e)){o(Fe).anchorMessageID=t.dataset.messageId,o(Fe).anchorPixelOffset=n.top-e;break}}}return o(Fe)}g(()=>(a.onListRef({scrollToBottom:Ze,scrollToMessage:mt,scrollToDivider:ht,captureState:_t,isFollowing:()=>G,isNearBottom:e=>qe(e)}),()=>a.onListRef(null))),g(()=>{let e=a.viewKey,t=o(De).length,n=o(Oe),r=a.messages.at(-1)?.id||``,i=r!==Me;if(Me=r,e!==Ae){Ae=e,je=t,Ne=n,Pe=a.restoreState,x(Fe,void 0),G=!0,x(ke,!0),x(K,!1),ze=!1,Le=!0,vt(e,a.restoreState,!0);return}let s=a.restoreState,c=s&&s!==Pe;if(c){let r=s===o(Fe)&&Ie!==He;if(x(Fe,void 0),Pe=s,!r&&(s.atBottom||s.anchorMessageID)){je=t,Ne=n,Le=!0,vt(e,s,s.atBottom);return}r&&!G&&o(I)&&yt(o(I).getScrollOffset())}let l=c||t!==je||i||n!==Ne;l&&G&&!M()&&!Le?Qe():l&&!Le&&Z(e),je=t,Ne=n});async function Z(e,t=He){await m(),await X(),q(e,t)&&Ye()}async function vt(e,t,n){let r=Ue(!1),i=t&&!t.atBottom?t.anchorMessageID:void 0,a=i?()=>ft(e,r,()=>$e(i),`[data-message-id="${CSS.escape(i)}"]`,t?.anchorPixelOffset??0):void 0,s=!1;if(await m(),await X(),q(e,r)){if(a){let t=await a();if(!q(e,r))return;!t&&n?await Qe(r):G=!1}else o(De).findIndex(e=>e.kind===`divider`)>=0&&o(I)?(s=!0,await ft(e,r,()=>J(),`[data-unread-divider='true']`),G=!1):await Qe(r);await X(),q(e,r)&&(Le=!1,x(K,!0),x(ke,Ke(),!0),G=o(ke)&&!M(),s||(o(ke)&&Xe(),o(I)&&yt(o(I).getScrollOffset())),Ye(),a&&(await m(),q(e,r)&&await a()))}}function yt(e){if(!o(I)||Le&&!o(K))return;let t=Ge(),n=Ke(),r=n||t<=260;G=n&&!M(),x(ke,n,!0),M()||(ze=!1),!n&&ne()&&e-o(R)<=160&&a.onLoadOlder?.(),!Re&&M()&&r&&!ze&&(ze=!0,a.onLoadNewer?.(`scroll`)),n&&!Re&&Xe()}var bt=ut();let xt;var St=E(bt),Q=t=>{var n=it(),r=E(n),i=E(r),o=e=>{var t=u(`@`);l(e,t)},c=e=>{var t=u(`#`);l(e,t)};C(i,e=>{a.selectedDirect?e(o):e(c,-1)}),e(r);var d=y(r,2),f=E(d),p=e=>{var t=u();S(e=>s(t,`This is the start of your conversation with ${e??``}.`),[()=>ye(a.selectedDirect,a.currentUserID)]),l(e,t)},m=e=>{var t=u();S(e=>s(t,`Welcome to #${e??``}!`),[()=>xe(a.selectedChannel)]),l(e,t)},h=e=>{var t=u(`Pick a channel to get started.`);l(e,t)};C(f,e=>{a.selectedDirect?e(p):a.selectedChannel?e(m,1):e(h,-1)}),e(d),T(2),e(n),l(t,n)},Ct=t=>{var n=ct(),r=y(E(n),2),u=t=>{var n=at(),r=E(n);ue(r,{direction:`older`,get rows(){return o(et)}}),e(n),k(n,e=>x(he,e),()=>o(he)),S(()=>D(n,`aria-hidden`,N()?`false`:`true`)),l(t,n)};C(r,e=>{o(et)>0&&e(u)});var d=y(r,2);k(Se(d,{get data(){return o(De)},getKey:e=>e.id,itemProps:()=>c()||!o(K)?void 0:{style:{"pointer-events":`auto`}},get scrollRef(){return o(L)},get shift(){return re()},get startMargin(){return o(R)},onscroll:yt,children:(t,n=w,r=w)=>{var c=i(),u=A(c),d=e=>{ue(e,{get direction(){return n().direction},get rows(){return n().rows}})},f=t=>{var r=ot(),i=E(r),a=v(i,!0);e(r),S(()=>s(a,n().label)),l(t,r)},p=e=>{var t=st();let n;S(()=>n=_(t,1,`new-messages-divider`,null,n,{"is-clearing":o(H)})),l(e,t)},m=e=>{rt(e,{get group(){return n().group},get currentUserID(){return a.currentUserID},get reactionController(){return a.reactionController},get reactionsDisabled(){return ae()},get selectedThreadID(){return a.selectedThreadID},get mentionPeople(){return ie()},get mentionAttentionUserID(){return a.mentionAttentionUserID},get replyContext(){return o(_e)},get canDeleteAnyMessage(){return oe()},get deletingMessageIDs(){return se()},get editController(){return a.editController},get editScope(){return de()},get onMessageEdited(){return a.onMessageEdited},get onOpenProfile(){return a.onOpenProfile},get onReply(){return a.onReply},get onOpenThread(){return a.onOpenThread},get onJumpToQuote(){return a.onJumpToQuote},get onOpenImage(){return a.onOpenImage},get onOpenArtifact(){return a.onOpenArtifact},get onRetry(){return a.onRetry},get onDiscard(){return a.onDiscard},get onDeleteMessage(){return a.onDeleteMessage},get topics(){return fe()},get onSelectTopic(){return pe()},get channelID(){return ce()},get pinnedMessageIDs(){return le()},get onTogglePin(){return a.onTogglePin},get onCopyLink(){return a.onCopyLink}})};C(u,e=>{n().kind===`loader`?e(d):n().kind===`day`?e(f,1):n().kind===`divider`?e(p,2):n().kind===`group`&&e(m,3)}),l(t,c)},$$slots:{default:!0}}),e=>x(I,e,!0),()=>o(I)),e(n),k(n,e=>x(L,e),()=>o(L)),l(t,n)};C(St,e=>{!c()&&a.messages.length===0?e(Q):a.messages.length>0&&e(Ct,1)});var wt=y(St,2),Tt=n=>{var r=lt();let i;var a=E(r),c=E(a),u=v(c);e(a);var d=y(a,2);e(r),S(e=>{i=_(r,1,`unread-bar`,null,i,{"is-clearing":o(H)}),D(r,`aria-hidden`,o(H)?`true`:void 0),a.disabled=o(H),D(a,`aria-label`,e),s(u,`${(o(V)>99?`99+`:o(V))??``} new message${o(V)===1?``:`s`}${O()?` since ${O()}`:``}`),d.disabled=o(H)},[()=>`Jump to ${o(V)>0?o(V):``} new message${o(V)===1?``:`s`}`.replace(/ +/g,` `)]),t(`click`,a,gt),t(`click`,d,nt),l(n,r)};C(wt,e=>{!c()&&a.messages.length>0&&o(V)>0&&e(Tt)}),e(bt),S(()=>xt=_(bt,1,`messages`,null,xt,{"is-revealing":c()||!o(K)&&a.messages.length>0})),t(`pointerdown`,bt,function(...e){a.onActivateMessageComposer?.apply(this,e)}),t(`pointerup`,bt,function(...e){a.onInlineImagePointerUp?.apply(this,e)}),l(n,bt),f()}M([`pointerdown`,`pointerup`,`click`]);var ft=a(` `),pt=a(` `),mt=a(``),ht=a(`
`),gt=a(``),_t=a(`
User kind
`),Z=a(`

`),vt=a(`

Blocked.

`),yt=a(``),bt=a(``),xt=a(``),St=a(``),Q=a(`
Moderation
`),Ct=a(`

Profile

Active
Contact information
Handle
User ID
About

`,1);function wt(n,i){r(i,!0);let a=h(i,`messagePending`,3,!1),c=h(i,`messageError`,3,``),u=j(()=>i.profile.kind===`bot`?i.profile.owner_user_id?`Bot of ${i.profile.owner_user_id}`:`Service bot`:``),d=j(()=>i.moderation?.role||`member`),p=j(()=>!!i.moderation&&o(d)!==`owner`&&(i.currentUserRole===`owner`||i.currentUserRole===`moderator`&&(o(d)===`member`||o(d)===`guest`))),m=j(()=>i.currentUser?.id!==i.profile.id&&o(p)),g=j(()=>!!i.moderation?.blocked_at),_=j(()=>o(d));var b=Ct(),x=A(b),w=E(x),ee=y(E(w),2),T=v(ee,!0);e(w);var te=y(w,2);e(x);var D=y(x,2),O=E(D),k=E(O);B(k,{class:`profile-avatar`,get id(){return i.profile.id},get name(){return i.profile.display_name},get src(){return i.profile.avatar_url},size:240,loading:`eager`,fetchPriority:`auto`}),e(O);var M=y(O,2),N=E(M),P=E(N),F=E(P),re=v(F,!0),ie=y(F,2),ae=e=>{var t=ft(),n=v(t,!0);S(()=>s(n,o(u))),l(e,t)};C(ie,e=>{o(u)&&e(ae)});var oe=y(ie,2),se=e=>{var t=pt(),n=v(t,!0);S(e=>s(n,e),[()=>z(i.profile.handle)]),l(e,t)};C(oe,e=>{i.profile.handle&&e(se)}),e(P);var ce=y(P,2),le=e=>{var n=mt();t(`click`,n,function(...e){i.onEdit?.apply(this,e)}),l(e,n)};C(ce,e=>{i.currentUser?.id===i.profile.id&&i.onEdit&&e(le)}),e(N);var ue=y(N,4),de=n=>{var r=ht(),o=E(r),c=v(o,!0);e(r),S(()=>{o.disabled=a(),s(c,a()?`Starting…`:`Message`)}),t(`click`,o,()=>i.onMessage?.(i.profile.id)),l(n,r)};C(ue,e=>{i.currentUser?.id!==i.profile.id&&i.onMessage&&e(de)});var fe=y(ue,2),pe=e=>{var t=gt(),n=v(t,!0);S(()=>s(n,c())),l(e,t)};C(fe,e=>{c()&&e(pe)});var me=y(fe,2),I=E(me),L=y(E(I),2),he=e=>{var n=mt();t(`click`,n,function(...e){i.onEdit?.apply(this,e)}),l(e,n)};C(L,e=>{i.currentUser?.id===i.profile.id&&i.onEdit&&e(he)}),e(I);var R=y(I,2),ge=y(E(R),2),_e=y(E(ge),2),ve=v(_e,!0);e(ge),e(R);var ye=y(R,2),xe=y(E(ye),2),Se=y(E(xe),2),Ce=v(Se,!0);e(xe),e(ye);var V=y(ye,2),H=t=>{var n=_t(),r=y(E(n),2),i=y(E(r),2),a=v(i,!0);e(r),e(n),S(()=>s(a,o(u))),l(t,n)};C(V,e=>{i.profile.kind===`bot`&&e(H)}),e(me);var U=y(me,2),we=y(E(U),2),Te=v(we);e(U);var W=y(U,2),Ee=n=>{var r=Q(),a=E(r),c=y(E(a),2),u=v(c,!0);e(a);var d=y(a,2),f=e=>{var t=Z(),n=v(t);S(()=>s(n,`${i.moderation.posts_remaining??``} of ${i.moderation.post_limit??``} waiting-room posts left today.`)),l(e,t)};C(d,e=>{i.moderation.role===`guest`&&i.moderation.post_limit>0&&e(f)});var p=y(d,2),m=e=>{var t=Z(),n=v(t);S(e=>s(n,`Timed out until ${e??``}.`),[()=>new Date(i.moderation.timeout_until).toLocaleString()]),l(e,t)};C(p,e=>{i.moderation.timeout_until&&e(m)});var h=y(p,2),b=e=>{var t=vt();l(e,t)};C(h,e=>{i.moderation.blocked_at&&e(b)});var x=y(h,2),w=E(x),ee=e=>{var n=yt();t(`click`,n,()=>i.onApprove?.(i.profile.id)),l(e,n)};C(w,e=>{i.moderation.role===`guest`&&i.onApprove&&e(ee)});var T=y(w,2),te=e=>{var n=bt();t(`click`,n,()=>i.onTimeout?.(i.profile.id)),l(e,n)};C(T,e=>{i.onTimeout&&e(te)});var D=y(T,2),O=e=>{var n=xt();t(`click`,n,()=>i.onUnblock?.(i.profile.id)),l(e,n)},k=e=>{var n=St();t(`click`,n,()=>i.onBlock?.(i.profile.id)),l(e,n)};C(D,e=>{o(g)&&i.onUnblock?e(O):!o(g)&&i.onBlock&&e(k,1)}),e(x),e(r),S(()=>s(u,o(_))),l(n,r)};C(W,e=>{o(m)&&i.moderation&&e(Ee)}),e(M),e(D),S((e,t)=>{s(T,i.profile.display_name),ne(O,`--hue: ${e??``}deg`),s(re,i.profile.display_name),s(ve,t),s(Ce,i.profile.id),s(Te,`Member of ${(i.workspaceName||`this workspace`)??``}.`)},[()=>be(i.profile.id),()=>i.profile.handle?z(i.profile.handle):`No handle set`]),t(`click`,te,function(...e){i.onClose?.apply(this,e)}),l(n,b),f()}M([`click`]);export{Ce as i,dt as n,Ne as r,wt as t}; \ No newline at end of file diff --git a/apps/api/internal/webassets/dist/_app/immutable/chunks/bE-mhUF5.js b/apps/api/internal/webassets/dist/_app/immutable/chunks/Bi80bmu0.js similarity index 99% rename from apps/api/internal/webassets/dist/_app/immutable/chunks/bE-mhUF5.js rename to apps/api/internal/webassets/dist/_app/immutable/chunks/Bi80bmu0.js index dcd325f72..d7becc1a3 100644 --- a/apps/api/internal/webassets/dist/_app/immutable/chunks/bE-mhUF5.js +++ b/apps/api/internal/webassets/dist/_app/immutable/chunks/Bi80bmu0.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./BB6meo0l.js","./HclGiUj8.js"])))=>i.map(i=>d[i]); -import{t as e}from"./DK3Fl9T5.js";import{At as t,B as n,C as r,D as i,E as a,Et as o,F as s,G as c,I as l,K as u,N as d,O as f,P as p,R as m,S as h,St as g,Tt as _,V as v,X as y,Z as b,_ as x,a as S,at as C,b as w,c as T,ct as E,dt as D,f as O,ft as k,gt as A,h as j,ht as M,it as N,j as P,jt as F,k as I,kt as ee,lt as L,m as R,mt as z,n as te,nt as ne,o as re,p as B,pt as ie,r as ae,s as oe,tt as V,u as se,ut as ce,v as le,vt as H,xt as ue,yt as U,z as W}from"./CxKeDCcw.js";import{c as de,n as fe,t as pe}from"./ChC1oWd7.js";import{t as me}from"./HclGiUj8.js";import"./xihTtKlq.js";import"./qQG-ipvL.js";import{a as he,c as ge,i as _e,l as ve,n as G,s as ye,t as be,u as xe}from"./Dsl_OP1c.js";import{c as Se,d as Ce,f as we,h as Te,i as Ee,l as De,m as Oe,n as ke,p as Ae,r as je,s as Me,t as Ne,u as Pe}from"./Y2iPPnRJ.js";import{a as Fe,i as Ie,n as Le,t as Re}from"./Qo16U5GS.js";import{t as ze}from"./OQjxVT6U.js";import"./CYM1xkwL.js";import{C as Be,D as Ve,E as He,I as Ue,L as We,R as Ge,S as Ke,T as qe,_ as Je,b as Ye,f as Xe,g as K,h as Ze,j as Qe,k as $e,m as et,p as tt,r as nt,u as q,v as rt,w as it,x as at,y as ot}from"./HlY492D_.js";import{a as st,c as ct,f as lt,i as ut,l as dt,o as ft,p as J,s as pt,t as Y,u as X}from"./ZgTSXUg-.js";import{i as mt,n as ht,r as Z,t as gt}from"./CS_f1eMF.js";import{n as Q,t as _t}from"./DlGnnCJo.js";import{n as vt,r as yt,t as bt}from"./j7YOEK28.js";import{p as xt,r as St}from"./DNWg-bnz.js";import{r as Ct,t as wt}from"./CQTKCwo-.js";var Tt={url:`/`,label:`cc`};function Et(e){if(e.startsWith(`//`))return!1;try{if(e.startsWith(`/`)){let t=`https://clickclack.invalid`;return new URL(e,t).origin===t}let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&t.host!==``&&!t.username&&!t.password}catch{return!1}}function Dt(e){if(!e||typeof e!=`object`)return Tt;let t=e,n=typeof t.url==`string`?t.url:``,r=n.trim(),i=typeof t.label==`string`?t.label.trim():``,a=/[\u0000-\u001f\u007f\\]/u.test(n);return{url:r&&!a&&Et(r)?r:Tt.url,label:i&&Array.from(i).length<=32?i:Tt.label}}function Ot(e){return e===Tt.label}function kt(e){return Ot(e.label)?`ClickClack home`:`${e.label} home`}async function At(e){try{return Dt(await e(`/api/home-link`))}catch{return Tt}}var jt=typeof window>`u`?void 0:window.clickclackDesktop;function Mt(e,t){let n={width:0,height:0,durationMS:0},r=e.type.startsWith(`image/`);return t.aborted||!r&&!e.type.startsWith(`video/`)?Promise.resolve(n):new Promise(i=>{let a=URL.createObjectURL(e),o=r?new Image:document.createElement(`video`),s=r?`load`:`loadedmetadata`;function c(e=n){o.removeEventListener(s,u),o.removeEventListener(`error`,l),t.removeEventListener(`abort`,l),o.removeAttribute(`src`),o instanceof HTMLVideoElement&&o.load(),URL.revokeObjectURL(a),i(e)}function l(){c()}function u(){c(o instanceof HTMLImageElement?{width:o.naturalWidth,height:o.naturalHeight,durationMS:0}:{width:o.videoWidth,height:o.videoHeight,durationMS:Number.isFinite(o.duration)&&o.duration>0?Math.round(o.duration*1e3):0})}o instanceof HTMLVideoElement&&(o.preload=`metadata`,o.muted=!0),o.addEventListener(s,u),o.addEventListener(`error`,l),t.addEventListener(`abort`,l,{once:!0}),o.src=a})}var Nt=new Set([`agent_commentary`,`agent_tool`]),Pt=18e4;function Ft(e){return e.kind!==void 0&&Nt.has(e.kind)}function It(e){return e.kind===void 0||e.kind===`message`}function Lt(e){return e.author?.id||e.author_id||``}function Rt(e){return`${e.channel_id?`channel:${e.channel_id}`:`direct:${e.direct_conversation_id||``}`}\u0000${Lt(e)}\u0000${e.turn_id||e.id}`}function zt(e){let t=e.trim(),n=``,r=``,i=t.match(/^\*\*([^*]+)\*\*\s*\n+([\s\S]+)$/),a=t.match(/^\*\*([^*]+)\*\*$/);if(i)n=i[1].trim(),r=Vt(i[2]);else if(a)n=a[1].trim();else return Bt(t.replace(/\*\*/g,``).trim(),``);return Bt(n,r)}function Bt(e,t){let n=Vt(e),r=n.indexOf(` `),i,a;r===-1?(i=n,a=``):(i=n.slice(0,r),a=n.slice(r+1).trim());let o=[a,t].filter(e=>e.length>0).join(` · `);return{name:i,detail:o||void 0}}function Vt(e){return e.replace(/\s+/g,` `).trim()}function Ht(e,t,n,r){let i=[];for(let e of t)if(e.kind===`agent_tool`){if(r.hideToolCalls)continue;let t=zt(e.body);i.push({type:`tool`,id:e.id,name:t.name,detail:t.detail,full:e.body.trim()})}else{if(r.hideCommentary)continue;let t=e.body.trim();t&&i.push({type:`commentary`,id:e.id,body:t})}return i.length===0?null:{turnId:e,items:i,final:n}}function Ut(e,t,n=Date.now()){let r=new Map,i=new Map;for(let t=0;to.firstIndex;if(!r){let e=Date.parse(o.rows[o.rows.length-1].created_at);Number.isFinite(e)&&n-e>Pt&&(r=!0)}a.set(t,r)}let o=[];for(let n=0;n=tn)&&(nn.active=!0,nn.lastPingAt=t,on(e,`typing.started`)),nn.idleTimer&&window.clearTimeout(nn.idleTimer),nn.idleTimer=window.setTimeout(()=>{nn&&=(cn(nn),null)},en)}async function cn(e){e.idleTimer&&window.clearTimeout(e.idleTimer),e.active&&await on(e.scope,`typing.stopped`)}function ln(){nn&&=(cn(nn),null)}var un=2e3,dn=2097152;function fn(e){let t=document.createElement(`span`);return t.textContent=e,t.innerHTML}function pn(e,t,n){return!t||e.length>262144?Promise.resolve(fn(e)):new Promise((r,i)=>{let a=new Worker(new URL(``+new URL(`../workers/highlight.worker-B65U9hWZ.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),o=!1,s=e=>{o||(o=!0,clearTimeout(l),n.removeEventListener(`abort`,c),a.terminate(),e())},c=()=>s(()=>i(new DOMException(`Syntax highlighting was aborted.`,`AbortError`))),l=window.setTimeout(()=>s(()=>r(fn(e))),un);if(a.onmessage=t=>{let n=t.data;`error`in n?s(()=>r(fn(e))):s(()=>r(n.html))},a.onerror=()=>s(()=>r(fn(e))),n.addEventListener(`abort`,c,{once:!0}),n.aborted){c();return}a.postMessage({source:e,language:t,outputLimit:dn})})}var mn=5e3;function hn(e,t,n){return new Promise((r,i)=>{let a=new Worker(new URL(``+new URL(`../workers/office.worker-BdyMEpKK.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),o=!1,s=e=>{o||(o=!0,clearTimeout(l),n.removeEventListener(`abort`,c),a.terminate(),e())},c=()=>s(()=>i(new DOMException(`Office preview was aborted.`,`AbortError`))),l=window.setTimeout(()=>s(()=>i(Error(`Office preview took too long and was stopped.`))),mn);if(a.onmessage=t=>{let n=t.data;if(`error`in n){s(()=>i(Error(n.error)));return}if(n.kind!==e){s(()=>i(Error(`Office preview returned an unexpected result.`)));return}s(()=>r(n.preview))},a.onerror=()=>s(()=>i(Error(`Could not parse this Office file safely.`))),n.addEventListener(`abort`,c,{once:!0}),n.aborted){c();return}let u=t.byteOffset===0&&t.buffer instanceof ArrayBuffer&&t.byteLength===t.buffer.byteLength?t:t.slice(),d={kind:e,bytes:u};a.postMessage(d,[u.buffer])})}var gn=16777216,_n=1e4,vn=1e4,yn=`This PDF page is too large to preview safely. Download the original to open it locally.`;function bn(e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<1||t<1||e>8192||t>8192||e*t>16777216)throw Error(yn)}var xn=``+new URL(`../assets/pdf.worker.CLesOks4.mjs`,import.meta.url).href,Sn=l(`
`),Cn=l(`

Preparing a safe preview.

`),wn=l(``),Tn=l(`
No preview for this file type

You can still download the original file.

Download original
`),En=l(`
`,1),Dn=l(` `),On=l(` `),kn=l(` `),An=l(` `),jn=l(`

Preview is limited to 10,000 cells, the first 1,000 rows, and the first 100 columns. Download the original to inspect omitted cells.

`),Mn=l(``),Nn=l(`
Raw cached values; number and date formatting omitted
`,1),Pn=l(`

`),Fn=l(`

`),In=l(`

`),Ln=l(`

Some slide content was omitted by preview limits.

`),Rn=l(`

Text outline only. Visuals, layout, animations, and speaker notes are omitted.

`,1),zn=l(`
`),Bn=l(`
`),Vn=l(`
`),Hn=l(`
 
`),Un=l(`
`,1);function Wn(e,r){o(r,!0);let a=A(null),c=U(()=>ot(r.upload)),l=A(`preview`),m=A(`idle`),h=A(``),g=A(``),v=A(``),y=A(!1),b=A(``),x=A(null),S=A(1),T=A(1),E=A(!1),O=A(``),j=null,F=!1,R=A(null),z=A(0),ne=A(null),re=A(0),ie=1e4,ae=65536,V=5e3;class se extends Error{}let le=U(()=>K(u(c))),H=U(()=>Be(r.upload)),ue=U(()=>(u(c)===`markdown`||u(c)===`html`)&&u(m)===`ready`&&u(y));function W(e){return`This ${u(le).toLowerCase()} is ${Ke(r.upload.byte_size)}. Preview is limited to ${Ke(e)}.`}function de(e){pe(e);let t=document.createElement(`template`);t.innerHTML=e;let n=Ye.sanitize(t.content,{RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0},FORBID_TAGS:[`base`,`embed`,`form`,`iframe`,`link`,`meta`,`object`,`script`,`style`],FORBID_ATTR:[`action`,`formaction`,`srcset`,`style`,`xlink:href`]});for(let e of n.querySelectorAll(`*`))for(let t of Array.from(e.attributes))e.removeAttribute(t.name);let r=document.createElement(`div`);r.append(n);let i=r.innerHTML;return he(i),`${i}`}function fe(e){pe(e);let t=et(e);return he(t),Ye.sanitize(t,{ALLOWED_TAGS:[`blockquote`,`br`,`code`,`del`,`em`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`hr`,`li`,`ol`,`p`,`pre`,`strong`,`table`,`tbody`,`td`,`th`,`thead`,`tr`,`ul`],ALLOWED_ATTR:[]})}function pe(e){if(e.length>65536)throw new se(`Structured preview exceeded the safe source limit.`);let t=0;for(let n of e)if("<[]>*_`-+.!#>|~".includes(n)&&(t+=1,t>ie))throw new se(`Structured preview exceeded the safe complexity limit.`)}function he(e){if(e.length>4194304)throw new se(`Rendered preview exceeded the safe output limit.`);let t=0;for(let n of e)if(n===`<`&&++t>ie*2)throw new se(`Rendered preview exceeded the safe element limit.`)}function ge(e){return`Preview data exceeded the ${Ke(e)} safety limit.`}async function _e(e,t){let n=await fetch(u(H),{credentials:`include`,signal:e});if(!n.ok)throw n.status===401||n.status===403?Error(`You no longer have access to this artifact.`):n.status===404?Error(`This artifact is no longer available.`):Error(`Could not load this artifact (${n.status}).`);let r=Number(n.headers.get(`Content-Length`));if(Number.isFinite(r)&&r>t)throw Error(ge(t));if(!n.body){let e=new Uint8Array(await n.arrayBuffer());if(e.byteLength>t)throw Error(ge(t));return e}let i=n.body.getReader(),a=[],o=0;try{for(;;){let{done:e,value:n}=await i.read();if(e)break;if(o+=n.byteLength,o>t)throw await i.cancel(),Error(ge(t));a.push(n)}}finally{i.releaseLock()}let s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.byteLength;return s}async function ve(e,t){return new TextDecoder(`utf-8`,{fatal:!1}).decode(await _e(e,t))}async function G(e){j?.(),j=null,M(x,null),M(g,``),M(v,``),M(y,!1),M(b,``),M(S,1),M(T,1),M(O,``),F=!1,M(R,null),M(z,0),M(ne,null),M(re,0),M(l,`preview`),M(h,``);let t=rt(u(c));if(t!==void 0&&r.upload.byte_size>t){M(m,`error`),M(h,W(t),!0);return}if(u(c)===`unsupported`){M(m,`ready`);return}M(m,`loading`);try{if(u(c)===`pdf`){let n=await me(()=>import(`./BB6meo0l.js`),__vite__mapDeps([0,1]),import.meta.url);if(e.aborted)return;n.GlobalWorkerOptions.workerSrc=xn;let r=new AbortController,i=()=>r.abort();e.addEventListener(`abort`,i,{once:!0});let a=null,o=0,s=new Promise((e,t)=>{o=window.setTimeout(()=>{r.abort(),a?.destroy(),t(Error(`PDF preview took too long and was stopped.`))},_n)}),c;try{if(c=await Promise.race([_e(r.signal,t),s]),e.aborted)throw new DOMException(`Aborted`,`AbortError`);a=new n.PDFWorker,await Promise.race([a.promise,s])}catch(t){throw clearTimeout(o),e.removeEventListener(`abort`,i),t}if(e.aborted||!a){clearTimeout(o),e.removeEventListener(`abort`,i),a?.destroy();return}let l=a.port,u=e=>{let t=e.data;typeof t==`object`&&t&&`reason`in t&&typeof t.reason==`object`&&t.reason!==null&&`message`in t.reason&&t.reason.message===`Image exceeded maximum allowed size and was removed.`&&(F=!0,j?.(),M(m,`error`),M(h,`PDF page content could not be rendered completely within safety limits.`))};l.addEventListener(`message`,u);let d=null,f=!1;j=()=>{f||(f=!0,l.removeEventListener(`message`,u),d&&d.destroy(),a.destroy(),M(x,null))};let p=n.getDocument({data:c,maxImageSize:gn,canvasMaxAreaInBytes:gn*4,stopAtErrors:!0,worker:a});d=p;try{M(x,await Promise.race([p.promise,s]),!0)}finally{clearTimeout(o),e.removeEventListener(`abort`,i)}}else if(u(c)===`spreadsheet`||u(c)===`presentation`){let n=await _e(e,t);if(e.aborted)return;if(u(c)===`spreadsheet`){let t=await hn(u(c),n,e);if(e.aborted)return;M(R,t,!0)}else{let t=await hn(u(c),n,e);if(e.aborted)return;M(ne,t,!0)}}else{if(M(g,await ve(e,t),!0),e.aborted)return;u(c)===`code`&&M(b,await pn(u(g),Je(r.upload),e),!0);try{u(c)===`markdown`&&(M(v,fe(u(g)),!0),M(y,!0)),u(c)===`html`&&(M(v,de(u(g)),!0),M(y,!0))}catch(e){if(!(e instanceof se))throw e;M(v,``),M(l,`source`)}}e.aborted||M(m,`ready`)}catch(t){if(e.aborted||t instanceof Error&&t.name===`AbortError`)return;j?.(),j=null,M(m,`error`),M(h,t instanceof Error?t.message:`Could not preview this artifact.`,!0)}}C(()=>{let e=new AbortController;return G(e.signal),()=>e.abort()}),C(()=>{if(u(c)!==`pdf`||!u(x)||!u(a)||u(m)!==`ready`)return;let e=u(x),t=u(S),n=u(T),r=!1,i=null,o=null,s=null,l=0;return M(E,!0),M(O,``),(async()=>{try{if(l=window.setTimeout(()=>{r||(i?.cancel(),s?.cancel(),j?.(),M(m,`error`),M(h,`PDF page rendering took too long and was stopped.`))},vn),o=await e.getPage(t),r||!u(a))return;let c=``,d=0;s=o.streamTextContent().getReader();try{for(;!r;){let{done:e,value:t}=await s.read();if(e)break;for(let e of t.items){if(d+=1,d>V){await s.cancel(),c=`${c}…`;break}if(!(`str`in e)||!e.str)continue;let t=`${c}${c?` `:``}${e.str}`;if(t.length>ae){await s.cancel(),c=`${t.slice(0,ae)}…`;break}c=t}if(d>V||c.endsWith(`…`))break}}finally{s.releaseLock(),s=null}if(r)return;M(O,c||`This page has no extractable text.`,!0);let f=o.getViewport({scale:n}),p=Math.min(window.devicePixelRatio||1,2),g=Math.max(1,Math.floor(f.width*p)),_=Math.max(1,Math.floor(f.height*p));bn(g,_);let v=u(a).getContext(`2d`);if(!v)throw Error(`PDF canvas is unavailable.`);if(u(a).width=g,u(a).height=_,u(a).style.width=`${f.width}px`,u(a).style.height=`${f.height}px`,v.setTransform(p,0,0,p,0,0),i=o.render({canvasContext:v,viewport:f}),await i.promise,F)throw Error(`PDF page content could not be rendered completely within safety limits.`)}catch(e){!r&&!(e instanceof Error&&e.name===`RenderingCancelledException`)&&(j?.(),M(m,`error`),M(h,e instanceof Error?e.message:`Could not render this PDF page.`,!0))}finally{clearTimeout(l),o?.cleanup(),o=null,r||M(E,!1)}})(),()=>{r=!0,clearTimeout(l),i?.cancel(),s?.cancel()}}),te(()=>j?.());function ye(e){let t=e.match(/^[A-Z]+/i)?.[0]?.toUpperCase()||`A`,n=0;for(let e of t)n=n*26+e.charCodeAt(0)-64;return n}function be(e){return Number(e.match(/\d+$/)?.[0]||1)}function xe(e){let t=``;for(let n=e;n>0;n=Math.floor((n-1)/26))t=String.fromCharCode(65+(n-1)%26)+t;return t}let Se=U(()=>{let e=u(R)?.sheets[u(z)];if(!e)return{columns:[],rows:[],clipped:!1};let t=Math.max(1,...e.cells.map(e=>ye(e.reference))),n=Math.max(1,...e.cells.map(e=>be(e.reference))),r=Math.min(100,t),i=Math.min(1e3,Math.floor(1e4/r),n),a=new Map(e.cells.map(e=>[e.reference.toUpperCase(),e.value])),o=Array.from({length:r},(e,t)=>xe(t+1));return{columns:o,rows:Array.from({length:i},(e,t)=>({number:t+1,values:o.map(e=>a.get(`${e}${t+1}`)||``)})),clipped:t>r||n>i}});var Ce=Un(),we=ce(Ce),Te=L(we),Ee=L(Te),De=D(Ee,!0),Oe=k(Ee,2),ke=D(Oe,!0),Ae=k(Oe,2),je=D(Ae,!0);t(Te);var Me=k(Te,2),Ne=L(Me),Pe=e=>{var r=Sn(),i=L(r);let a;var o=k(i,2);let s;t(r),N(()=>{B(r,`aria-label`,`${u(le)} view`),B(i,`aria-pressed`,u(l)===`preview`),a=w(i,1,``,null,a,{active:u(l)===`preview`}),B(o,`aria-pressed`,u(l)===`source`),s=w(o,1,``,null,s,{active:u(l)===`source`})}),n(`click`,i,()=>M(l,`preview`)),n(`click`,o,()=>M(l,`source`)),p(e,r)};P(Ne,e=>{u(ue)&&e(Pe)});var Fe=k(Ne,2),Ie=k(Fe,2);t(Me),t(we);var Le=k(we,2);let Re;var ze=L(Le),Ve=e=>{var n=Cn(),r=k(L(n),2),i=D(r);ee(2),t(n),N(e=>d(i,`Opening ${e??``}`),[()=>u(le).toLowerCase()]),p(e,n)},He=e=>{var n=wn(),i=k(L(n),4),a=D(i,!0),o=k(i,2);t(n),N(()=>{d(a,u(h)),B(o,`href`,u(H)),B(o,`download`,r.upload.filename)}),p(e,n)},Ue=e=>{var n=Tn(),i=k(L(n),6);t(n),N(()=>{B(i,`href`,u(H)),B(i,`download`,r.upload.filename)}),p(e,n)},We=e=>{var r=En(),i=ce(r),o=L(i),s=k(o,2),c=D(s),l=k(s,2),f=k(l,4),m=k(f,2),h=D(m),g=k(m,2);t(i);var _=k(i,2);let v;var y=L(_);oe(y,e=>M(a,e),()=>u(a));var b=k(y,2),C=D(b,!0);t(_),N(e=>{o.disabled=u(S)<=1||u(E),d(c,`Page ${u(S)??``} of ${u(x).numPages??``}`),l.disabled=u(S)>=u(x).numPages||u(E),f.disabled=u(T)<=.6||u(E),d(h,`${e??``}%`),g.disabled=u(T)>=2||u(E),v=w(_,1,`artifact-viewer__pdf-stage`,null,v,{"is-rendering":u(E)}),B(_,`aria-label`,`PDF page ${u(S)} visual preview`),B(b,`aria-label`,`PDF page ${u(S)} text`),d(C,u(O))},[()=>Math.round(u(T)*100)]),n(`click`,o,()=>M(S,u(S)-1)),n(`click`,l,()=>M(S,u(S)+1)),n(`click`,f,()=>M(T,Math.max(.6,u(T)-.2),!0)),n(`click`,g,()=>M(T,Math.min(2,u(T)+.2),!0)),p(e,r)},Ge=e=>{var r=Nn(),i=ce(r),a=L(i),o=D(a),s=k(a,4),c=e=>{var t=Dn(),n=D(t);N(()=>d(n,`${u(R).hiddenSheets??``} hidden ${u(R).hiddenSheets===1?`sheet`:`sheets`} omitted`)),p(e,t)};P(s,e=>{u(R).hiddenSheets>0&&e(c)});var l=k(s,2),m=e=>{var t=Dn(),n=D(t);N(()=>d(n,`${u(R).unsupportedSheets??``} non-worksheet ${u(R).unsupportedSheets===1?`sheet`:`sheets`} omitted`)),p(e,t)};P(l,e=>{u(R).unsupportedSheets>0&&e(m)}),t(i);var h=k(i,2),g=L(h),_=L(g),v=L(_),y=k(L(v));f(y,17,()=>u(Se).columns,I,(e,t)=>{var n=On(),r=D(n,!0);N(()=>d(r,u(t))),p(e,n)}),t(v),t(_);var b=k(_);f(b,21,()=>u(Se).rows,I,(e,n)=>{var r=An(),i=L(r),a=D(i,!0),o=k(i);f(o,17,()=>u(n).values,I,(e,t)=>{var n=kn(),r=D(n,!0);N(()=>d(r,u(t))),p(e,n)}),t(r),N(()=>d(a,u(n).number)),p(e,r)}),t(b),t(g);var x=k(g,2),S=e=>{var t=jn();p(e,t)};P(x,e=>{(u(Se).clipped||u(R).sheets[u(z)].truncated)&&e(S)}),t(h);var C=k(h,2);f(C,21,()=>u(R).sheets,I,(e,t,r)=>{var i=Mn();let a;var o=D(i,!0);N(()=>{B(i,`aria-selected`,u(z)===r),a=w(i,1,``,null,a,{active:u(z)===r}),d(o,u(t).name)}),n(`click`,i,()=>M(z,r,!0)),p(e,i)}),t(C),N(()=>{d(o,`${u(R).sheets.length??``} ${u(R).sheets.length===1?`sheet`:`sheets`}`),B(h,`aria-label`,`${u(R).sheets[u(z)].name} worksheet`)}),p(e,r)},qe=e=>{var r=Rn(),i=ce(r),a=L(i),o=k(a,2),c=D(o),l=k(o,2);t(i);var m=k(i,2),h=L(m);f(h,21,()=>u(ne).slides[u(re)].paragraphs,I,(e,t,n)=>{var r=s(),i=ce(r),a=e=>{var n=Pn(),r=D(n,!0);N(()=>d(r,u(t))),p(e,n)},o=e=>{var n=Fn(),r=D(n,!0);N(()=>d(r,u(t))),p(e,n)};P(i,e=>{n===0?e(a):e(o,-1)}),p(e,r)}),t(h);var g=k(h,4),_=e=>{var t=In(),n=D(t);N(()=>d(n,`${u(ne).hiddenSlides??``} hidden ${u(ne).hiddenSlides===1?`slide`:`slides`} omitted.`)),p(e,t)};P(g,e=>{u(ne).hiddenSlides>0&&e(_)});var v=k(g,2),y=e=>{var t=Ln();p(e,t)};P(v,e=>{u(ne).truncated&&e(y)}),t(m),N(()=>{a.disabled=u(re)===0,d(c,`Slide ${u(re)+1} of ${u(ne).slides.length??``}`),l.disabled=u(re)>=u(ne).slides.length-1,B(h,`aria-label`,`Slide ${u(re)+1}: ${u(ne).slides[u(re)].title}`)}),n(`click`,a,()=>M(re,u(re)-1)),n(`click`,l,()=>M(re,u(re)+1)),p(e,r)},Xe=e=>{var n=zn();i(n,()=>u(v),!0),t(n),p(e,n)},Ze=e=>{var n=Bn();i(n,()=>u(v),!0),t(n),p(e,n)},Qe=e=>{var n=Vn(),r=L(n);i(r,()=>u(b),!0),t(r),t(n),p(e,n)},$e=e=>{var n=Hn(),r=L(n),i=D(r,!0);t(n),N(()=>d(i,u(g))),p(e,n)};P(ze,e=>{u(m)===`loading`?e(Ve):u(m)===`error`?e(He,1):u(c)===`unsupported`?e(Ue,2):u(c)===`pdf`&&u(x)?e(We,3):u(c)===`spreadsheet`&&u(R)?e(Ge,4):u(c)===`presentation`&&u(ne)?e(qe,5):u(c)===`html`&&u(l)===`preview`&&u(v)?e(Xe,6):u(c)===`markdown`&&u(l)===`preview`?e(Ze,7):u(c)===`code`?e(Qe,8):e($e,-1)}),t(Le),N(e=>{d(De,u(le)),B(Oe,`title`,r.upload.filename),d(ke,r.upload.filename),d(je,e),B(Fe,`href`,u(H)),B(Fe,`download`,r.upload.filename),B(Fe,`aria-label`,`Download ${r.upload.filename}`),Re=w(Le,1,`artifact-viewer__body`,null,Re,{"is-pdf":u(c)===`pdf`,"is-office":u(c)===`spreadsheet`||u(c)===`presentation`})},[()=>Ke(r.upload.byte_size)]),n(`click`,Ie,function(...e){r.onClose?.apply(this,e)}),p(e,Ce),_()}W([`click`]);var Gn=l(``),Kn=l(``);function qn(e,r){o(r,!0);let i=S(r,`deleting`,3,!1),a=S(r,`error`,3,``),s=U(()=>r.message.author?.display_name||`Local User`);function c(){i()||r.onClose()}var l=Kn(),f=L(l),m=k(f,2),h=L(m),g=k(L(h),2);t(h);var v=k(h,2),y=k(L(v),2),b=L(y);{let e=U(()=>r.message.author?.id||r.message.author_id),t=U(()=>r.message.author?.avatar_url);Y(b,{class:`avatar`,get id(){return u(e)},get name(){return u(s)},get src(){return u(t)},size:36,loading:`eager`,fetchPriority:`auto`})}var x=k(b,2),C=L(x),w=L(C),T=D(w,!0),E=k(w,2),O=D(E,!0);t(C);var A=k(C,2),j=D(A,!0);t(x),t(y);var M=k(y,2),F=e=>{var t=Gn(),n=D(t,!0);N(()=>d(n,a())),p(e,t)};P(M,e=>{a()&&e(F)});var I=k(M,2),ee=L(I),R=k(ee,2),z=D(R,!0);t(I),t(v),t(m),t(l),N(e=>{f.disabled=i(),g.disabled=i(),d(T,u(s)),B(E,`datetime`,r.message.created_at),d(O,e),d(j,r.message.body),ee.disabled=i(),R.disabled=i(),d(z,i()?`Deleting...`:`Delete`)},[()=>Ze(r.message.created_at)]),n(`click`,f,c),n(`click`,g,c),n(`click`,ee,c),n(`click`,R,function(...e){r.onConfirm?.apply(this,e)}),p(e,l),_()}W([`click`]);var Jn=6500,Yn=l(`
`);function Xn(e,n){o(n,!0);let r=U(()=>n.entries.filter(e=>e.userID!==n.currentUserID));function i(e,t=`Someone`){return e?.display_name?.trim()||(e?.handle?`@${e.handle}`:t)}let a=U(()=>u(r).length===0?``:u(r).length===1?`${i(u(r)[0].user)} is typing…`:u(r).length===2?`${i(u(r)[0].user)} and ${i(u(r)[1].user)} are typing…`:u(r).length===3?`${i(u(r)[0].user)}, ${i(u(r)[1].user)}, and ${i(u(r)[2].user)} are typing…`:`Several people are typing…`);var s=Yn();let c;var l=k(L(s),2),f=D(l,!0);t(s),N(()=>{c=w(s,1,`typing-indicator`,null,c,{visible:u(r).length>0}),d(f,u(a))}),p(e,s),_()}var Zn=45e3,Qn=l(`
`),$n=l(`
`),er=l(`
`);function tr(e,n){o(n,!0);function r(e){return e.kind===`tool`&&e.toolName?!e.text||e.text===e.toolName?e.toolName:`${e.toolName}: ${e.text}`:e.text}function i(e){switch(e){case`tool`:return`⚙`;case`thinking`:case`commentary`:return`✦`;case`plan`:return`☰`;case`patch`:return`±`;case`command_output`:return`›`;case`error`:return`✕`;default:return`·`}}var a=s(),c=ce(a),l=e=>{var a=er();f(a,21,()=>n.turns,e=>e.key,(e,n)=>{var a=$n();f(a,21,()=>u(n).lines,e=>e.id,(e,n)=>{var a=Qn();let o;var s=L(a),c=D(s,!0),l=k(s,2),f=D(l,!0);t(a),N((e,t)=>{o=w(a,1,`agent-progress__line svelte-6vwkyv`,null,o,{"agent-progress__line--done":u(n).finalized}),B(a,`data-kind`,u(n).kind),d(c,e),d(f,t)},[()=>i(u(n).kind),()=>r(u(n))]),p(e,a)}),t(a),p(e,a)}),t(a),p(e,a)};P(c,e=>{n.turns.length>0&&e(l)}),p(e,a),_()}var nr=l(``),rr=l(``);function ir(e,r){o(r,!0);var i=rr(),a=L(i),s=k(a,2),c=L(s),l=k(L(c),2);t(c);var u=k(c,2),f=L(u),m=k(L(f),2);O(m),t(f);var h=k(f,2),g=e=>{var t=nr(),n=D(t,!0);N(()=>d(n,r.error)),p(e,t)};P(h,e=>{r.error&&e(g)});var y=k(h,2),b=L(y),x=k(b,2),S=D(x,!0);t(y),t(u),t(s),t(i),N(e=>{j(m,r.channelName),m.disabled=r.pending,x.disabled=e,d(S,r.pending?`Creating…`:`Create channel`)},[()=>r.pending||!r.channelName.trim()]),n(`click`,a,function(...e){r.onClose?.apply(this,e)}),n(`click`,l,function(...e){r.onClose?.apply(this,e)}),v(`submit`,u,e=>{e.preventDefault(),r.onCreate()}),n(`input`,m,e=>r.onChannelName(e.currentTarget.value)),n(`click`,b,function(...e){r.onClose?.apply(this,e)}),p(e,i),_()}W([`click`,`input`]);var ar=l(``),or=l(`
No matching people yet
`),sr=l(`

`),cr=l(``),lr=l(``);function ur(e,r){o(r,!0);let i=U(()=>r.memberID.trim().toLowerCase().replace(/^@/,``)),a=U(()=>r.people.filter(e=>e.id!==r.currentUserID).filter(e=>!u(i)||e.display_name.toLowerCase().includes(u(i))||e.handle?.toLowerCase().includes(u(i))||e.id.toLowerCase().includes(u(i)))),s=U(()=>r.memberID.trim().startsWith(`usr_`)?r.memberID.trim():u(i)&&u(a).length===1?u(a)[0].id:``);function c(e){r.pending||!e||(r.onMemberID(e),r.onStart(e))}var l=lr(),m=L(l),h=k(m,2),g=L(h),y=k(L(g),2);t(g);var b=k(g,2),x=L(b),S=k(L(x),2);O(S),t(x);var C=k(x,2),w=L(C);f(w,17,()=>u(a),e=>e.id,(e,i)=>{var a=ar(),o=L(a);Y(o,{class:`dm-avatar`,get id(){return u(i).id},get name(){return u(i).display_name},get src(){return u(i).avatar_url},size:32});var s=k(o,2),l=L(s),f=D(l,!0),m=k(l,2),h=D(m,!0);t(s),t(a),N(e=>{a.disabled=r.pending,d(f,u(i).display_name),d(h,e)},[()=>dt(u(i).handle)||u(i).id]),n(`click`,a,()=>c(u(i).id)),p(e,a)});var T=k(w,2),E=e=>{var t=or();p(e,t)};P(T,e=>{u(a).length===0&&e(E)}),t(C);var A=k(C,2),M=e=>{var t=sr(),n=D(t,!0);N(()=>d(n,u(a).length>1?`Choose a person from the results.`:`Choose a person or enter a user ID.`)),p(e,t)};P(A,e=>{u(i)&&!u(s)&&e(M)});var F=k(A,2),I=e=>{var t=cr(),n=D(t,!0);N(()=>d(n,r.error)),p(e,t)};P(F,e=>{r.error&&e(I)});var ee=k(F,2),R=L(ee),z=k(R,2),te=D(z,!0);t(ee),t(b),t(h),t(l),N(()=>{j(S,r.memberID),S.disabled=r.pending,z.disabled=r.pending||!u(s),d(te,r.pending?`Starting…`:`Start DM`)}),n(`click`,m,function(...e){r.onClose?.apply(this,e)}),n(`click`,y,function(...e){r.onClose?.apply(this,e)}),v(`submit`,b,e=>{e.preventDefault(),c(u(s))}),n(`input`,S,e=>r.onMemberID(e.currentTarget.value)),n(`click`,R,function(...e){r.onClose?.apply(this,e)}),p(e,l),_()}W([`click`,`input`]);var dr=l(` `),fr=l(``),pr=l(`
`),mr=l(``),hr=l(`

Creating workspace…

`),gr=l(`
`),_r=l(``);function vr(e,r){o(r,!0);let i=S(r,`homeHref`,3,`/`),a=S(r,`homeLabel`,3,`cc`),s=S(r,`homeTitle`,3,`ClickClack home`);function c(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}var l=_r(),m=L(l);let h;var g=L(m),y=e=>{Xe(e,{size:48})},b=U(()=>Ot(a())),x=e=>{var t=dr(),n=D(t,!0);N(()=>d(n,a())),p(e,t)};P(g,e=>{u(b)?e(y):e(x,-1)}),t(m);var C=k(m,4),T=L(C);f(T,17,()=>r.workspaces,e=>e.id,(e,i)=>{var a=pr();let o;var s=L(a),l=L(s),f=e=>{var t=fr();N(e=>B(t,`src`,e),[()=>_e(u(i).icon_url)]),p(e,t)},m=e=>{var t=dr(),n=D(t,!0);N(e=>d(n,e),[()=>J(u(i).name)]),p(e,t)};P(l,e=>{u(i).icon_url?e(f):e(m,-1)}),t(s),t(a),N(e=>{o=w(a,1,`guild-wrap`,null,o,{active:u(i).id===r.selectedWorkspaceID}),B(s,`title`,u(i).name),B(s,`aria-label`,u(i).name),B(s,`href`,e)},[()=>r.hrefForWorkspace(u(i).id)]),n(`click`,s,e=>{c(e)&&(e.preventDefault(),r.onSelectWorkspace(u(i).id))}),p(e,a)});var E=k(T,2);t(C);var A=k(C,2),M=e=>{var i=gr(),a=L(i);O(a);var o=k(a,2),s=e=>{var t=mr(),n=D(t,!0);N(()=>d(n,r.createError)),p(e,t)};P(o,e=>{r.createError&&e(s)});var c=k(o,2),l=e=>{var t=hr();p(e,t)};P(c,e=>{r.createPending&&e(l)}),t(i),N(()=>{j(a,r.workspaceName),a.disabled=r.createPending}),v(`submit`,i,e=>{e.preventDefault(),r.onCreateWorkspace()}),n(`input`,a,e=>r.onWorkspaceName(e.currentTarget.value)),p(e,i)};P(A,e=>{r.showWorkspaceCreate&&e(M)}),t(l),N(e=>{h=w(m,1,`guild home`,null,h,{"home--mark":e}),B(m,`title`,s()),B(m,`aria-label`,s()),B(m,`href`,i())},[()=>Ot(a())]),n(`click`,E,function(...e){r.onToggleWorkspaceCreate?.apply(this,e)}),p(e,l),_()}W([`click`,`input`]);var yr=l(``),br=l(` `,1),xr=l(``),Sr=l(` `),Cr=l(``),wr=l(`
`),Tr=l(``),Er=l(`Drag with a pointer, use Arrow Up and Arrow Down while focused, or open the move menu. Moves stay within the current channel section. `,1),Dr=l(`
`);function Or(e,r){o(r,!0);let i=(e,i=F,a=F,o=F,s=F,c=F)=>{let f=U(()=>i().unread_count||0),_=U(()=>a().findIndex(e=>e.id===i().id));var y=Cr();let b;var C=L(y),T=e=>{var r=br(),s=ce(r),c=k(s,2),l=e=>{var r=yr(),o=L(r),s=k(o,2);t(r),oe(r,e=>M(S,e),()=>u(S)),N(e=>{B(r,`aria-label`,e),o.disabled=u(_)<=0,s.disabled=u(_)<0||u(_)>=a().length-1},[()=>`Move #${_t(i())}`]),n(`keydown`,r,e=>{e.key===`Escape`&&(e.preventDefault(),_e(!0))}),n(`click`,o,()=>ve(i().id,-1,a())),n(`click`,s,()=>ve(i().id,1,a())),p(e,r)};P(c,e=>{u(x)===i().id&&e(l)}),N(e=>{B(s,`aria-label`,e),B(s,`aria-expanded`,u(x)===i().id)},[()=>`Move #${_t(i())}`]),n(`click`,s,e=>void ge(i().id,e.currentTarget)),v(`dragstart`,s,e=>fe(e,i().id,o())),v(`dragend`,s,he),n(`keydown`,s,e=>{e.key===`ArrowUp`||e.key===`ArrowDown`?(e.preventDefault(),M(x,``),de(i().id,e.key===`ArrowUp`?-1:1,a())):e.key===`Escape`&&M(x,``)}),p(e,r)};P(C,e=>{c()&&e(T)});var E=k(C,2);let O;var A=k(L(E),2),j=D(A,!0),I=k(A,2),ee=e=>{var t=xr();p(e,t)};P(I,e=>{i().external_managed&&e(ee)});var R=k(I,2),z=e=>{var t=Sr(),n=D(t,!0);N(()=>{B(t,`aria-label`,`${u(f)} unread`),d(n,u(f)>99?`99+`:u(f))}),p(e,t)};P(R,e=>{u(f)>0&&!(i().id===r.selectedChannelID&&!r.selectedDirectID)&&e(z)}),t(E),t(y),N((e,t)=>{b=w(y,1,`channel-row`,null,b,{reorderable:c(),subdued:s(),dragging:u(l)===i().id,"drop-before":u(h)===i().id&&u(g),"drop-after":u(h)===i().id&&!u(g)}),B(E,`href`,e),O=w(E,1,`nav-item channel`,null,O,{active:i().id===r.selectedChannelID&&!r.selectedDirectID,"has-unread":u(f)>0&&!(i().id===r.selectedChannelID&&!r.selectedDirectID)}),d(j,t)},[()=>r.hrefForChannel(i().id),()=>_t(i())]),v(`dragover`,y,e=>{c()&&pe(e,i().id,o())}),v(`drop`,y,e=>{e.preventDefault(),!(!c()||u(m)!==o())&&(W(u(l),i().id,u(g),a()),he())}),n(`focusout`,y,e=>{e.currentTarget.contains(e.relatedTarget)||M(x,``)}),n(`click`,E,e=>{G(e)&&(e.preventDefault(),r.onSelectChannel(i().id))}),p(e,y)},a=(e,r=F,a=F,o=F)=>{let s=U(()=>V(r().key)),c=U(()=>H(r()));var l=wr();let m;var h=L(l),g=k(L(h),2),_=D(g,!0),v=k(g,2),y=D(v,!0);t(h);var b=k(h,2);f(b,21,()=>u(c),e=>e.id,(e,t)=>{i(e,()=>u(t),()=>r().channels,()=>r().key,o,()=>u(s))}),t(b),t(l),N(()=>{m=w(l,1,`channel-subgroup`,null,m,{"archived-channel-group":o()}),B(h,`aria-expanded`,u(s)),B(h,`aria-controls`,a()),d(_,r().label),d(y,r().channels.length),B(b,`id`,a()),B(b,`hidden`,!u(s)&&u(c).length===0)}),n(`click`,h,()=>se(r().key)),p(e,l)},c=`archived`,l=A(``),m=A(``),h=A(``),g=A(!0),b=A(!1),x=A(``),S=A(void 0),T,O=A(``),j=A(ie({})),I=U(()=>r.channels.filter(e=>!e.archived_at)),ee=U(()=>r.channels.filter(e=>!!e.archived_at)),R=U(()=>u(I).filter(e=>!e.sidebar_section?.trim())),z=U(()=>{let e=new Map;for(let t of u(I)){let n=t.sidebar_section?.trim();if(!n)continue;let r=e.get(n)??[];r.push(t),e.set(n,r)}return[...e.entries()].map(([e,t])=>({key:`section:${e}`,label:e,channels:t})).sort((e,t)=>e.label.localeCompare(t.label,void 0,{sensitivity:`base`}))}),te=U(()=>r.channels.filter(e=>e.id===r.selectedChannelID&&!r.selectedDirectID||(e.unread_count||0)>0));function ne(e){if(!e)return{};try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))return{};let n=Object.entries(t);return n.length>1e3||n.some(([e,t])=>e.length>256||typeof t!=`boolean`)?{}:Object.fromEntries(n)}catch{return{}}}function re(e){return`clickclack:sidebar-channel-groups:v1:${e}`}function ae(e){if(!e)return{};try{return ne(window.localStorage.getItem(re(e)))}catch{return{}}}function V(e){let t=u(j)[e];return typeof t==`boolean`?t:e!==c}function se(e){if(M(j,{...u(j),[e]:!V(e)},!0),r.workspaceID)try{window.localStorage.setItem(re(r.workspaceID),JSON.stringify(u(j)))}catch{}}function le(e){e.key===re(r.workspaceID)&&M(j,ne(e.newValue),!0)}function H(e){return V(e.key)?e.channels:e.channels.filter(e=>e.id===r.selectedChannelID&&!r.selectedDirectID||(e.unread_count||0)>0)}function ue(e){M(O,``),queueMicrotask(()=>{M(O,e,!0)})}function W(e,t,n,i){if(!e||!t||e===t)return;let a=r.channels.map(e=>e.id),o=a.indexOf(e);if(o<0)return;a.splice(o,1);let s=a.indexOf(t);if(s<0)return;a.splice(s+ +!n,0,e),r.onReorder(a);let c=r.channels.find(t=>t.id===e),l=i.map(e=>e.id).filter(t=>t!==e),u=l.indexOf(t);l.splice(u+ +!n,0,e),c&&ue(`Moved #${_t(c)} to position ${l.indexOf(e)+1} of ${l.length}`)}function de(e,t,n){let r=n.findIndex(t=>t.id===e),i=r+t;r<0||i<0||i>=n.length||W(e,n[i].id,t<0,n)}function fe(e,t,n){M(b,!0),M(x,``),M(l,t,!0),M(m,n,!0),e.dataTransfer?.setData(`text/plain`,t),e.dataTransfer&&(e.dataTransfer.effectAllowed=`move`)}function pe(e,t,n){if(!u(l)||u(l)===t||u(m)!==n)return;e.preventDefault();let r=e.currentTarget;M(h,t,!0),M(g,e.clientY{M(b,!1)},0)}async function ge(e,t){if(!u(b)){if(u(x)===e){M(x,``);return}T=t,M(x,e,!0),await y(),u(S)?.querySelector(`button:not(:disabled)`)?.focus()}}async function _e(e=!1){M(x,``),e&&(await y(),T?.focus())}function ve(e,t,n){de(e,t,n),_e(!0)}function G(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}C(()=>{M(j,ae(r.workspaceID),!0)}),C(()=>{r.expanded||(M(x,``),me(),M(b,!1))});var ye=Dr();v(`storage`,E,le);let be;var xe=L(ye),Se=L(xe),Ce=k(Se,2);t(xe);var we=k(xe,2),Te=L(we),Ee=e=>{var t=Er(),n=k(ce(t),2);f(n,17,()=>u(R),e=>e.id,(e,t)=>{i(e,()=>u(t),()=>u(R),()=>`unsectioned`,()=>!1,()=>!0)});var o=k(n,2);f(o,19,()=>u(z),e=>e.key,(e,t,n)=>{a(e,()=>u(t),()=>`sidebar-channel-section-${u(n)}`,()=>!1)});var s=k(o,2),l=e=>{a(e,()=>({key:c,label:`Archived`,channels:u(ee)}),()=>`sidebar-archived-channels`,()=>!0)};P(s,e=>{u(ee).length>0&&e(l)});var d=k(s,2),m=e=>{var t=Tr();p(e,t)};P(d,e=>{r.channels.length===0&&e(m)}),p(e,t)},De=e=>{var t=s(),n=ce(t);f(n,17,()=>u(te),e=>e.id,(e,t)=>{{let n=U(()=>!!u(t).archived_at);i(e,()=>u(t),()=>u(te),()=>`priority`,()=>u(n),()=>!1)}}),p(e,t)};P(Te,e=>{r.expanded?e(Ee):e(De,-1)}),t(we);var Oe=k(we,2),ke=D(Oe,!0);t(ye),N(()=>{be=w(ye,1,`nav-section`,null,be,{collapsed:!r.expanded}),B(Se,`aria-expanded`,r.expanded),B(we,`hidden`,!r.expanded&&u(te).length===0),d(ke,u(O))}),n(`click`,Se,function(...e){r.onToggle?.apply(this,e)}),n(`click`,Ce,function(...e){r.onCreateChannel?.apply(this,e)}),p(e,ye),_()}W([`focusout`,`click`,`keydown`]);var kr=l(` `),Ar=l(``),jr=l(``),Mr=l(`
`),Nr=l(``),Pr=l(`
`),Fr=l(`
`);function Ir(e,r){o(r,!0);let i=A(``),a=U(()=>r.expanded?r.conversations:r.conversations.filter(e=>e.id===r.selectedDirectID||(e.unread_count||0)>0));function s(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}function c(e){M(i,u(i)===e?``:e,!0)}function l(){M(i,``)}var m=Fr();let h;var g=L(m),v=L(g),y=k(v,2);t(g);var b=k(g,2),x=L(b);f(x,17,()=>u(a),e=>e.id,(e,a)=>{let o=U(()=>pt(u(a),r.currentUserID)),f=U(()=>u(a).unread_count||0),m=U(()=>u(a).id===r.selectedDirectID);var h=Mr();let g;var _=L(h);let v;var y=L(_);{let e=U(()=>u(o)?.id||u(a).id),t=U(()=>u(o)?.display_name),n=U(()=>X(u(o))?void 0:u(o)?.avatar_url);Y(y,{class:`dm-avatar`,get id(){return u(e)},get name(){return u(t)},get src(){return u(n)},size:22})}var b=k(y,2),x=D(b,!0),S=k(b,2),C=e=>{var t=kr(),n=D(t,!0);N(()=>{B(t,`aria-label`,`${u(f)} unread`),d(n,u(f)>99?`99+`:u(f))}),p(e,t)},T=e=>{var t=Ar();p(e,t)};P(S,e=>{u(f)>0&&!u(m)?e(C):e(T,-1)}),t(_);var E=k(_,2),O=k(E,2),A=e=>{var t=jr(),i=D(t);n(`click`,i,e=>{e.preventDefault(),e.stopPropagation(),l(),r.onHideDirect(u(a).id)}),p(e,t)};P(O,e=>{u(i)===u(a).id&&e(A)}),t(h),N((e,t,n)=>{g=w(h,1,`dm-row`,null,g,{active:u(m)}),B(_,`href`,e),v=w(_,1,`nav-item dm`,null,v,{active:u(m),"has-unread":u(f)>0&&!u(m)}),d(x,t),B(E,`aria-label`,n),B(E,`aria-expanded`,u(i)===u(a).id)},[()=>r.hrefForDirect(u(a).id),()=>ct(u(a),r.currentUserID),()=>`Direct message actions for ${ct(u(a),r.currentUserID)}`]),n(`click`,_,e=>{s(e)&&(e.preventDefault(),r.onSelectDirect(u(a).id))}),n(`click`,E,e=>{e.preventDefault(),e.stopPropagation(),c(u(a).id)}),n(`keydown`,E,e=>{e.key===`Escape`&&l()}),p(e,h)});var S=k(x,2),C=e=>{var t=Nr();p(e,t)};P(S,e=>{r.expanded&&r.conversations.length===0&&e(C)});var T=k(S,2),E=e=>{var i=Pr(),a=L(i),o=D(a),s=k(a,2);t(i),N(()=>d(o,`Closed ${r.hiddenDirectTitle??``}`)),n(`click`,s,function(...e){r.onUndoHideDirect?.apply(this,e)}),p(e,i)};P(T,e=>{r.expanded&&r.hiddenDirectTitle&&e(E)}),t(b),t(m),N(()=>{h=w(m,1,`nav-section`,null,h,{collapsed:!r.expanded}),B(v,`aria-expanded`,r.expanded),B(b,`hidden`,!r.expanded&&u(a).length===0)}),n(`click`,v,function(...e){r.onToggle?.apply(this,e)}),n(`click`,y,function(...e){r.onCreateDirect?.apply(this,e)}),p(e,m),_()}W([`click`,`keydown`]);var Lr=l(``),Rr=l(`Connecting…`),zr=l(`
`),Br=l(` `),Vr=l(``),Hr=l(``),Ur=l(``);function Wr(e,r){o(r,!0);let i=S(r,`showHeader`,3,!0),a=`clickclack:sidebar-sections:v1:`,s={channels:!0,directMessages:!0,people:!0},c=A(ie({...s}));function l(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.channels==`boolean`&&typeof t.directMessages==`boolean`&&typeof t.people==`boolean`}function m(e){if(!e)return{...s};try{let t=window.localStorage.getItem(`${a}${e}`);if(!t)return{...s};let n=JSON.parse(t);return l(n)?n:{...s}}catch{return{...s}}}function h(e){if(M(c,{...u(c),[e]:!u(c)[e]},!0),r.workspaceID)try{window.localStorage.setItem(`${a}${r.workspaceID}`,JSON.stringify(u(c)))}catch{}}C(()=>{M(c,m(r.workspaceID),!0)});let g=1e6,y=A(ie([]));function b(e,t){return`clickclack:sidebar-channel-order:v1:${t}:${e}`}function x(e){if(!e||e.length>g)return[];try{let t=JSON.parse(e);return Array.isArray(t)&&t.length<=1e4&&t.every(e=>typeof e==`string`&&e.length<=128)?[...new Set(t)]:[]}catch{return[]}}function T(e,t){if(!e||!t)return[];try{return x(window.localStorage.getItem(b(e,t)))}catch{return[]}}function O(e){if(M(y,e,!0),!(!r.workspaceID||!r.currentUser?.id))try{let t=b(r.workspaceID,r.currentUser.id),n=JSON.stringify(e);if(n.length>g){window.localStorage.removeItem(t);return}window.localStorage.setItem(t,n)}catch{}}function j(e){!r.workspaceID||!r.currentUser?.id||e.key===b(r.workspaceID,r.currentUser.id)&&M(y,x(e.newValue),!0)}let F=U(()=>{let e=new Map(r.channels.map(e=>[e.id,e]));return[...u(y).flatMap(t=>{let n=e.get(t);return n?(e.delete(t),[n]):[]}),...e.values()]});C(()=>{M(y,T(r.workspaceID,r.currentUser?.id||``),!0)});function I(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}var R=Ur();v(`storage`,E,j);var z=L(R),te=e=>{var i=zr(),a=L(i),o=L(a),s=e=>{var t=Lr();N(e=>B(t,`src`,e),[()=>_e(r.workspaceIconURL)]),p(e,t)};P(o,e=>{r.workspaceIconURL&&e(s)});var c=k(o,2),l=L(c),u=L(l),f=D(u,!0);ee(2),t(l);var m=k(l,2),h=e=>{var t=Rr();p(e,t)};P(m,e=>{r.connected||e(h)}),t(c),t(a);var g=k(a,2),_=L(g),v=L(_),y=D(v);t(_),t(g),t(i),N(()=>{d(f,r.workspaceName||`Pick a workspace`),B(_,`aria-label`,r.sidebarCollapsed?`Expand sidebar`:`Collapse sidebar`),B(_,`title`,r.sidebarCollapsed?`Expand sidebar`:`Collapse sidebar`),B(y,`d`,r.sidebarCollapsed?`m9 6 6 6-6 6`:`m15 6-6 6 6 6`)}),n(`click`,a,function(...e){r.onOpenWorkspaceSettings?.apply(this,e)}),n(`click`,_,function(...e){r.onToggleCollapse?.apply(this,e)}),p(e,i)};P(z,e=>{i()&&e(te)});var ne=k(z,2),re=L(ne);Or(re,{get workspaceID(){return r.workspaceID},get expanded(){return u(c).channels},get channels(){return u(F)},get selectedChannelID(){return r.selectedChannelID},get selectedDirectID(){return r.selectedDirectID},get hrefForChannel(){return r.hrefForChannel},get onSelectChannel(){return r.onSelectChannel},get onCreateChannel(){return r.onCreateChannel},onToggle:()=>h(`channels`),onReorder:O});var ae=k(re,2);{let e=U(()=>r.currentUser?.id);Ir(ae,{get expanded(){return u(c).directMessages},get conversations(){return r.directConversations},get currentUserID(){return u(e)},get selectedDirectID(){return r.selectedDirectID},get hrefForDirect(){return r.hrefForDirect},get onSelectDirect(){return r.onSelectDirect},get onCreateDirect(){return r.onCreateDirect},get onHideDirect(){return r.onHideDirect},get hiddenDirectTitle(){return r.hiddenDirectTitle},get onUndoHideDirect(){return r.onUndoHideDirect},onToggle:()=>h(`directMessages`)})}var oe=k(ae,2);let V;var se=L(oe),ce=D(se),le=k(se,2),H=L(le);f(H,17,()=>r.recentPeople,e=>e.id,(e,i)=>{let a=U(()=>ft(r.directConversations,u(i).id,r.currentUser?.id));var o=Br();let s;var c=L(o);Y(c,{class:`dm-avatar`,get id(){return u(i).id},get name(){return u(i).display_name},get src(){return u(i).avatar_url},size:22});var l=k(c,2),f=D(l,!0);ee(2),t(o),N(e=>{B(o,`href`,e),s=w(o,1,`nav-item dm`,null,s,{active:u(a)?.id===r.selectedDirectID||r.selectedProfile?.id===u(i).id}),d(f,u(i).display_name)},[()=>u(a)?r.hrefForDirect(u(a).id):`#`]),n(`click`,o,e=>{if(u(a)){if(!I(e))return;e.preventDefault(),r.onSelectDirect(u(a).id)}else e.preventDefault(),r.onOpenProfile(u(i))}),p(e,o)});var ue=k(H,2),W=e=>{var t=Vr();p(e,t)};P(ue,e=>{r.recentPeople.length===0&&e(W)}),t(le),t(oe),t(ne);var de=k(ne,2),fe=e=>{var i=Hr(),a=L(i);Y(a,{class:`dm-avatar`,get id(){return r.currentUser.id},get name(){return r.currentUser.display_name},get src(){return r.currentUser.avatar_url},size:28,loading:`eager`,fetchPriority:`auto`});var o=k(a,2),s=L(o),c=D(s,!0),l=k(s,2),u=D(l,!0);t(o),ee(2),t(i),N((e,t)=>{B(i,`aria-label`,e),d(c,r.currentUser.display_name),d(u,t)},[()=>`Account settings for ${r.currentUser.display_name} ${dt(r.currentUser.handle)}`,()=>r.currentUser.handle?dt(r.currentUser.handle):r.connected?`Active`:`Reconnecting…`]),n(`click`,i,function(...e){r.onOpenSettings?.apply(this,e)}),n(`contextmenu`,i,e=>{e.preventDefault(),r.onOpenSettings()}),p(e,i)};P(de,e=>{r.currentUser&&e(fe)}),t(R),N(()=>{V=w(oe,1,`nav-section`,null,V,{collapsed:!u(c).people}),B(ce,`aria-expanded`,u(c).people),B(le,`hidden`,!u(c).people)}),n(`click`,ce,()=>h(`people`)),p(e,R),_()}W([`click`,`contextmenu`]);var Gr=l(`
Loading...
`),Kr=l(`
`),qr=l(`
`),Jr=l(`

No pinned messages

Pin important messages to keep them easily accessible.

`),Yr=l(`
`),Xr=l(`
`),Zr=l(`
`),Qr=l(` `,1),$r=l(`

Pinned Messages

`);function ei(e,r){o(r,!0);let a=S(r,`loading`,3,!1),s=S(r,`error`,3,``),c=S(r,`topics`,19,()=>[]),l=S(r,`mentionPeople`,19,()=>[]),m=S(r,`maxPins`,3,100),g=A(ie(new Set)),v=A(``);async function y(e){if(!u(g).has(e.id)){M(g,new Set(u(g)).add(e.id),!0),M(v,``);try{await r.onUnpin(e)}catch(e){M(v,e instanceof Error?e.message:`Could not unpin message`,!0)}finally{let t=new Set(u(g));t.delete(e.id),M(g,t,!0)}}}var b=$r(),x=L(b),C=L(x),w=L(C),T=k(L(w),2),E=D(T);t(w);var O=k(w,2),j=D(O);t(C);var F=k(C,2);t(x);var I=k(x,2),ee=L(I),R=e=>{var t=Gr();p(e,t)},z=e=>{var t=Kr(),n=D(t,!0);N(()=>d(n,s())),p(e,t)},te=e=>{var a=Qr(),o=ce(a),s=e=>{var t=qr(),n=D(t,!0);N(()=>d(n,u(v))),p(e,t)};P(o,e=>{u(v)&&e(s)});var m=k(o,2),_=e=>{var t=Jr();p(e,t)},b=e=>{var a=Zr();f(a,21,()=>r.messages,e=>e.id,(e,a)=>{let o=U(()=>c().find(e=>e.id===u(a).topic_id));var s=Xr(),m=L(s),_=L(m),v=D(_,!0),b=k(_,2),x=D(b,!0);t(m);var S=k(m,2);Z(S,{get topic(){return u(o)},get onSelect(){return r.onSelectTopic}});var C=k(S,2);i(C,()=>et(u(a).body),!0),t(C),h(C,e=>We?.(e)),h(C,(e,t)=>q?.(e,t),()=>({people:l(),attentionUserID:r.mentionAttentionUserID}));var w=k(C,2),T=e=>{var n=Yr();f(n,21,()=>u(a).attachments,e=>e.id,(e,t)=>{{let n=U(()=>Be(u(t)));nt(e,{get upload(){return u(t)},get url(){return u(n)},get onOpenImage(){return r.onOpenImage},get onOpenArtifact(){return r.onOpenArtifact}})}}),t(n),p(e,n)};P(w,e=>{u(a).attachments?.length&&e(T)});var E=k(w,2),O=L(E),A=k(O,2);t(E),t(s),N((e,t)=>{B(s,`data-message-id`,u(a).id),d(v,u(a).author?.display_name||`Unknown`),d(x,e),A.disabled=t},[()=>Ze(u(a).created_at),()=>u(g).has(u(a).id)]),n(`click`,O,()=>r.onOpenThread(u(a))),n(`click`,A,()=>y(u(a))),p(e,s)}),t(a),p(e,a)};P(m,e=>{r.messages.length===0?e(_):e(b,-1)}),p(e,a)};P(ee,e=>{a()?e(R):s()?e(z,1):e(te,-1)}),t(I),t(b),N(()=>{d(E,`${r.messages.length??``} / ${m()??``} pinned`),d(j,`Shared across this channel, with a maximum of ${m()??``} messages.`)}),n(`click`,F,function(...e){r.onClose?.apply(this,e)}),p(e,b),_()}W([`click`]);var ti=l(` `,1),ni=l(`
`),ri=l(`
We couldn’t search messages

`),ii=l(`
No messages found

Try another word or phrase.

`),ai=l(`deleted bot`),oi=l(` `),si=l(` `),ci=l(` `),li=l(` Reply in thread`),ui=l(` `),di=l(`
  • `),fi=l(``),pi=l(``),mi=l(``),hi=l(`
      `,1),gi=l(``);function _i(e,r){o(r,!0);let i=S(r,`covered`,3,!1),a=S(r,`inert`,3,!1),c=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`}),l=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`}),h=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`});function g(e,t){let n=Array.from(e),r=[],i=0;for(let e of t){let t=Math.max(i,Math.min(n.length,e.start)),a=Math.max(t,Math.min(n.length,e.end));t>i&&r.push({text:n.slice(i,t).join(``),highlighted:!1}),a>t&&r.push({text:n.slice(t,a).join(``),highlighted:!0}),i=a}return i{var t=m(`Searching messages…`);p(e,t)},R=e=>{var t=ti(),n=ce(t),i=k(n),a=e=>{var t=m();N(()=>d(t,`in ${r.session.scope.label??``}`)),p(e,t)};P(i,e=>{r.session.scope.label&&e(a)}),N(()=>d(n,`${r.session.results.length??``}${r.session.nextCursor?`+`:``} +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CIKVmJ8v.js","./HclGiUj8.js"])))=>i.map(i=>d[i]); +import{t as e}from"./DK3Fl9T5.js";import{At as t,B as n,C as r,D as i,E as a,Et as o,F as s,G as c,I as l,K as u,N as d,O as f,P as p,R as m,S as h,St as g,Tt as _,V as v,X as y,Z as b,_ as x,a as S,at as C,b as w,c as T,ct as E,dt as D,f as O,ft as k,gt as A,h as j,ht as M,it as N,j as P,jt as F,k as I,kt as ee,lt as L,m as R,mt as z,n as te,nt as ne,o as re,p as B,pt as ie,r as ae,s as oe,tt as V,u as se,ut as ce,v as le,vt as H,xt as ue,yt as U,z as W}from"./CxKeDCcw.js";import{c as de,n as fe,t as pe}from"./ChC1oWd7.js";import{t as me}from"./HclGiUj8.js";import"./xihTtKlq.js";import"./qQG-ipvL.js";import{a as he,c as ge,i as _e,l as ve,n as G,s as ye,t as be,u as xe}from"./Dsl_OP1c.js";import{c as Se,d as Ce,f as we,h as Te,i as Ee,l as De,m as Oe,n as ke,p as Ae,r as je,s as Me,t as Ne,u as Pe}from"./Y2iPPnRJ.js";import{a as Fe,i as Ie,n as Le,t as Re}from"./Qo16U5GS.js";import{t as ze}from"./OQjxVT6U.js";import"./CYM1xkwL.js";import{C as Be,D as Ve,E as He,I as Ue,L as We,R as Ge,S as Ke,T as qe,_ as Je,b as Ye,f as Xe,g as K,h as Ze,j as Qe,k as $e,m as et,p as tt,r as nt,u as q,v as rt,w as it,x as at,y as ot}from"./HlY492D_.js";import{a as st,c as ct,f as lt,i as ut,l as dt,o as ft,p as J,s as pt,t as Y,u as X}from"./ZgTSXUg-.js";import{i as mt,n as ht,r as Z,t as gt}from"./BZg3JVyH.js";import{n as Q,t as _t}from"./DlGnnCJo.js";import{n as vt,r as yt,t as bt}from"./j7YOEK28.js";import{p as xt,r as St}from"./DNWg-bnz.js";import{r as Ct,t as wt}from"./CQTKCwo-.js";var Tt={url:`/`,label:`cc`};function Et(e){if(e.startsWith(`//`))return!1;try{if(e.startsWith(`/`)){let t=`https://clickclack.invalid`;return new URL(e,t).origin===t}let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&t.host!==``&&!t.username&&!t.password}catch{return!1}}function Dt(e){if(!e||typeof e!=`object`)return Tt;let t=e,n=typeof t.url==`string`?t.url:``,r=n.trim(),i=typeof t.label==`string`?t.label.trim():``,a=/[\u0000-\u001f\u007f\\]/u.test(n);return{url:r&&!a&&Et(r)?r:Tt.url,label:i&&Array.from(i).length<=32?i:Tt.label}}function Ot(e){return e===Tt.label}function kt(e){return Ot(e.label)?`ClickClack home`:`${e.label} home`}async function At(e){try{return Dt(await e(`/api/home-link`))}catch{return Tt}}var jt=typeof window>`u`?void 0:window.clickclackDesktop;function Mt(e,t){let n={width:0,height:0,durationMS:0},r=e.type.startsWith(`image/`);return t.aborted||!r&&!e.type.startsWith(`video/`)?Promise.resolve(n):new Promise(i=>{let a=URL.createObjectURL(e),o=r?new Image:document.createElement(`video`),s=r?`load`:`loadedmetadata`;function c(e=n){o.removeEventListener(s,u),o.removeEventListener(`error`,l),t.removeEventListener(`abort`,l),o.removeAttribute(`src`),o instanceof HTMLVideoElement&&o.load(),URL.revokeObjectURL(a),i(e)}function l(){c()}function u(){c(o instanceof HTMLImageElement?{width:o.naturalWidth,height:o.naturalHeight,durationMS:0}:{width:o.videoWidth,height:o.videoHeight,durationMS:Number.isFinite(o.duration)&&o.duration>0?Math.round(o.duration*1e3):0})}o instanceof HTMLVideoElement&&(o.preload=`metadata`,o.muted=!0),o.addEventListener(s,u),o.addEventListener(`error`,l),t.addEventListener(`abort`,l,{once:!0}),o.src=a})}var Nt=new Set([`agent_commentary`,`agent_tool`]),Pt=18e4;function Ft(e){return e.kind!==void 0&&Nt.has(e.kind)}function It(e){return e.kind===void 0||e.kind===`message`}function Lt(e){return e.author?.id||e.author_id||``}function Rt(e){return`${e.channel_id?`channel:${e.channel_id}`:`direct:${e.direct_conversation_id||``}`}\u0000${Lt(e)}\u0000${e.turn_id||e.id}`}function zt(e){let t=e.trim(),n=``,r=``,i=t.match(/^\*\*([^*]+)\*\*\s*\n+([\s\S]+)$/),a=t.match(/^\*\*([^*]+)\*\*$/);if(i)n=i[1].trim(),r=Vt(i[2]);else if(a)n=a[1].trim();else return Bt(t.replace(/\*\*/g,``).trim(),``);return Bt(n,r)}function Bt(e,t){let n=Vt(e),r=n.indexOf(` `),i,a;r===-1?(i=n,a=``):(i=n.slice(0,r),a=n.slice(r+1).trim());let o=[a,t].filter(e=>e.length>0).join(` · `);return{name:i,detail:o||void 0}}function Vt(e){return e.replace(/\s+/g,` `).trim()}function Ht(e,t,n,r){let i=[];for(let e of t)if(e.kind===`agent_tool`){if(r.hideToolCalls)continue;let t=zt(e.body);i.push({type:`tool`,id:e.id,name:t.name,detail:t.detail,full:e.body.trim()})}else{if(r.hideCommentary)continue;let t=e.body.trim();t&&i.push({type:`commentary`,id:e.id,body:t})}return i.length===0?null:{turnId:e,items:i,final:n}}function Ut(e,t,n=Date.now()){let r=new Map,i=new Map;for(let t=0;to.firstIndex;if(!r){let e=Date.parse(o.rows[o.rows.length-1].created_at);Number.isFinite(e)&&n-e>Pt&&(r=!0)}a.set(t,r)}let o=[];for(let n=0;n=tn)&&(nn.active=!0,nn.lastPingAt=t,on(e,`typing.started`)),nn.idleTimer&&window.clearTimeout(nn.idleTimer),nn.idleTimer=window.setTimeout(()=>{nn&&=(cn(nn),null)},en)}async function cn(e){e.idleTimer&&window.clearTimeout(e.idleTimer),e.active&&await on(e.scope,`typing.stopped`)}function ln(){nn&&=(cn(nn),null)}var un=2e3,dn=2097152;function fn(e){let t=document.createElement(`span`);return t.textContent=e,t.innerHTML}function pn(e,t,n){return!t||e.length>262144?Promise.resolve(fn(e)):new Promise((r,i)=>{let a=new Worker(new URL(``+new URL(`../workers/highlight.worker-B65U9hWZ.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),o=!1,s=e=>{o||(o=!0,clearTimeout(l),n.removeEventListener(`abort`,c),a.terminate(),e())},c=()=>s(()=>i(new DOMException(`Syntax highlighting was aborted.`,`AbortError`))),l=window.setTimeout(()=>s(()=>r(fn(e))),un);if(a.onmessage=t=>{let n=t.data;`error`in n?s(()=>r(fn(e))):s(()=>r(n.html))},a.onerror=()=>s(()=>r(fn(e))),n.addEventListener(`abort`,c,{once:!0}),n.aborted){c();return}a.postMessage({source:e,language:t,outputLimit:dn})})}var mn=5e3;function hn(e,t,n){return new Promise((r,i)=>{let a=new Worker(new URL(``+new URL(`../workers/office.worker-BdyMEpKK.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),o=!1,s=e=>{o||(o=!0,clearTimeout(l),n.removeEventListener(`abort`,c),a.terminate(),e())},c=()=>s(()=>i(new DOMException(`Office preview was aborted.`,`AbortError`))),l=window.setTimeout(()=>s(()=>i(Error(`Office preview took too long and was stopped.`))),mn);if(a.onmessage=t=>{let n=t.data;if(`error`in n){s(()=>i(Error(n.error)));return}if(n.kind!==e){s(()=>i(Error(`Office preview returned an unexpected result.`)));return}s(()=>r(n.preview))},a.onerror=()=>s(()=>i(Error(`Could not parse this Office file safely.`))),n.addEventListener(`abort`,c,{once:!0}),n.aborted){c();return}let u=t.byteOffset===0&&t.buffer instanceof ArrayBuffer&&t.byteLength===t.buffer.byteLength?t:t.slice(),d={kind:e,bytes:u};a.postMessage(d,[u.buffer])})}var gn=16777216,_n=1e4,vn=1e4,yn=`This PDF page is too large to preview safely. Download the original to open it locally.`;function bn(e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<1||t<1||e>8192||t>8192||e*t>16777216)throw Error(yn)}var xn=``+new URL(`../assets/pdf.worker.TGcf_-kp.mjs`,import.meta.url).href,Sn=l(`
      `),Cn=l(`

      Preparing a safe preview.

      `),wn=l(``),Tn=l(`
      No preview for this file type

      You can still download the original file.

      Download original
      `),En=l(`
      `,1),Dn=l(` `),On=l(` `),kn=l(` `),An=l(` `),jn=l(`

      Preview is limited to 10,000 cells, the first 1,000 rows, and the first 100 columns. Download the original to inspect omitted cells.

      `),Mn=l(``),Nn=l(`
      Raw cached values; number and date formatting omitted
      `,1),Pn=l(`

      `),Fn=l(`

      `),In=l(`

      `),Ln=l(`

      Some slide content was omitted by preview limits.

      `),Rn=l(`

      Text outline only. Visuals, layout, animations, and speaker notes are omitted.

      `,1),zn=l(`
      `),Bn=l(`
      `),Vn=l(`
      `),Hn=l(`
       
      `),Un=l(`
      `,1);function Wn(e,r){o(r,!0);let a=A(null),c=U(()=>ot(r.upload)),l=A(`preview`),m=A(`idle`),h=A(``),g=A(``),v=A(``),y=A(!1),b=A(``),x=A(null),S=A(1),T=A(1),E=A(!1),O=A(``),j=null,F=!1,R=A(null),z=A(0),ne=A(null),re=A(0),ie=1e4,ae=65536,V=5e3;class se extends Error{}let le=U(()=>K(u(c))),H=U(()=>Be(r.upload)),ue=U(()=>(u(c)===`markdown`||u(c)===`html`)&&u(m)===`ready`&&u(y));function W(e){return`This ${u(le).toLowerCase()} is ${Ke(r.upload.byte_size)}. Preview is limited to ${Ke(e)}.`}function de(e){pe(e);let t=document.createElement(`template`);t.innerHTML=e;let n=Ye.sanitize(t.content,{RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0},FORBID_TAGS:[`base`,`embed`,`form`,`iframe`,`link`,`meta`,`object`,`script`,`style`],FORBID_ATTR:[`action`,`formaction`,`srcset`,`style`,`xlink:href`]});for(let e of n.querySelectorAll(`*`))for(let t of Array.from(e.attributes))e.removeAttribute(t.name);let r=document.createElement(`div`);r.append(n);let i=r.innerHTML;return he(i),`${i}`}function fe(e){pe(e);let t=et(e);return he(t),Ye.sanitize(t,{ALLOWED_TAGS:[`blockquote`,`br`,`code`,`del`,`em`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`hr`,`li`,`ol`,`p`,`pre`,`strong`,`table`,`tbody`,`td`,`th`,`thead`,`tr`,`ul`],ALLOWED_ATTR:[]})}function pe(e){if(e.length>65536)throw new se(`Structured preview exceeded the safe source limit.`);let t=0;for(let n of e)if("<[]>*_`-+.!#>|~".includes(n)&&(t+=1,t>ie))throw new se(`Structured preview exceeded the safe complexity limit.`)}function he(e){if(e.length>4194304)throw new se(`Rendered preview exceeded the safe output limit.`);let t=0;for(let n of e)if(n===`<`&&++t>ie*2)throw new se(`Rendered preview exceeded the safe element limit.`)}function ge(e){return`Preview data exceeded the ${Ke(e)} safety limit.`}async function _e(e,t){let n=await fetch(u(H),{credentials:`include`,signal:e});if(!n.ok)throw n.status===401||n.status===403?Error(`You no longer have access to this artifact.`):n.status===404?Error(`This artifact is no longer available.`):Error(`Could not load this artifact (${n.status}).`);let r=Number(n.headers.get(`Content-Length`));if(Number.isFinite(r)&&r>t)throw Error(ge(t));if(!n.body){let e=new Uint8Array(await n.arrayBuffer());if(e.byteLength>t)throw Error(ge(t));return e}let i=n.body.getReader(),a=[],o=0;try{for(;;){let{done:e,value:n}=await i.read();if(e)break;if(o+=n.byteLength,o>t)throw await i.cancel(),Error(ge(t));a.push(n)}}finally{i.releaseLock()}let s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.byteLength;return s}async function ve(e,t){return new TextDecoder(`utf-8`,{fatal:!1}).decode(await _e(e,t))}async function G(e){j?.(),j=null,M(x,null),M(g,``),M(v,``),M(y,!1),M(b,``),M(S,1),M(T,1),M(O,``),F=!1,M(R,null),M(z,0),M(ne,null),M(re,0),M(l,`preview`),M(h,``);let t=rt(u(c));if(t!==void 0&&r.upload.byte_size>t){M(m,`error`),M(h,W(t),!0);return}if(u(c)===`unsupported`){M(m,`ready`);return}M(m,`loading`);try{if(u(c)===`pdf`){let n=await me(()=>import(`./CIKVmJ8v.js`),__vite__mapDeps([0,1]),import.meta.url);if(e.aborted)return;n.GlobalWorkerOptions.workerSrc=xn;let r=new AbortController,i=()=>r.abort();e.addEventListener(`abort`,i,{once:!0});let a=null,o=0,s=new Promise((e,t)=>{o=window.setTimeout(()=>{r.abort(),a?.destroy(),t(Error(`PDF preview took too long and was stopped.`))},_n)}),c;try{if(c=await Promise.race([_e(r.signal,t),s]),e.aborted)throw new DOMException(`Aborted`,`AbortError`);a=new n.PDFWorker,await Promise.race([a.promise,s])}catch(t){throw clearTimeout(o),e.removeEventListener(`abort`,i),t}if(e.aborted||!a){clearTimeout(o),e.removeEventListener(`abort`,i),a?.destroy();return}let l=a.port,u=e=>{let t=e.data;typeof t==`object`&&t&&`reason`in t&&typeof t.reason==`object`&&t.reason!==null&&`message`in t.reason&&t.reason.message===`Image exceeded maximum allowed size and was removed.`&&(F=!0,j?.(),M(m,`error`),M(h,`PDF page content could not be rendered completely within safety limits.`))};l.addEventListener(`message`,u);let d=null,f=!1;j=()=>{f||(f=!0,l.removeEventListener(`message`,u),d&&d.destroy(),a.destroy(),M(x,null))};let p=n.getDocument({data:c,maxImageSize:gn,canvasMaxAreaInBytes:gn*4,stopAtErrors:!0,worker:a});d=p;try{M(x,await Promise.race([p.promise,s]),!0)}finally{clearTimeout(o),e.removeEventListener(`abort`,i)}}else if(u(c)===`spreadsheet`||u(c)===`presentation`){let n=await _e(e,t);if(e.aborted)return;if(u(c)===`spreadsheet`){let t=await hn(u(c),n,e);if(e.aborted)return;M(R,t,!0)}else{let t=await hn(u(c),n,e);if(e.aborted)return;M(ne,t,!0)}}else{if(M(g,await ve(e,t),!0),e.aborted)return;u(c)===`code`&&M(b,await pn(u(g),Je(r.upload),e),!0);try{u(c)===`markdown`&&(M(v,fe(u(g)),!0),M(y,!0)),u(c)===`html`&&(M(v,de(u(g)),!0),M(y,!0))}catch(e){if(!(e instanceof se))throw e;M(v,``),M(l,`source`)}}e.aborted||M(m,`ready`)}catch(t){if(e.aborted||t instanceof Error&&t.name===`AbortError`)return;j?.(),j=null,M(m,`error`),M(h,t instanceof Error?t.message:`Could not preview this artifact.`,!0)}}C(()=>{let e=new AbortController;return G(e.signal),()=>e.abort()}),C(()=>{if(u(c)!==`pdf`||!u(x)||!u(a)||u(m)!==`ready`)return;let e=u(x),t=u(S),n=u(T),r=!1,i=null,o=null,s=null,l=0;return M(E,!0),M(O,``),(async()=>{try{if(l=window.setTimeout(()=>{r||(i?.cancel(),s?.cancel(),j?.(),M(m,`error`),M(h,`PDF page rendering took too long and was stopped.`))},vn),o=await e.getPage(t),r||!u(a))return;let c=``,d=0;s=o.streamTextContent().getReader();try{for(;!r;){let{done:e,value:t}=await s.read();if(e)break;for(let e of t.items){if(d+=1,d>V){await s.cancel(),c=`${c}…`;break}if(!(`str`in e)||!e.str)continue;let t=`${c}${c?` `:``}${e.str}`;if(t.length>ae){await s.cancel(),c=`${t.slice(0,ae)}…`;break}c=t}if(d>V||c.endsWith(`…`))break}}finally{s.releaseLock(),s=null}if(r)return;M(O,c||`This page has no extractable text.`,!0);let f=o.getViewport({scale:n}),p=Math.min(window.devicePixelRatio||1,2),g=Math.max(1,Math.floor(f.width*p)),_=Math.max(1,Math.floor(f.height*p));bn(g,_);let v=u(a).getContext(`2d`);if(!v)throw Error(`PDF canvas is unavailable.`);if(u(a).width=g,u(a).height=_,u(a).style.width=`${f.width}px`,u(a).style.height=`${f.height}px`,v.setTransform(p,0,0,p,0,0),i=o.render({canvasContext:v,viewport:f}),await i.promise,F)throw Error(`PDF page content could not be rendered completely within safety limits.`)}catch(e){!r&&!(e instanceof Error&&e.name===`RenderingCancelledException`)&&(j?.(),M(m,`error`),M(h,e instanceof Error?e.message:`Could not render this PDF page.`,!0))}finally{clearTimeout(l),o?.cleanup(),o=null,r||M(E,!1)}})(),()=>{r=!0,clearTimeout(l),i?.cancel(),s?.cancel()}}),te(()=>j?.());function ye(e){let t=e.match(/^[A-Z]+/i)?.[0]?.toUpperCase()||`A`,n=0;for(let e of t)n=n*26+e.charCodeAt(0)-64;return n}function be(e){return Number(e.match(/\d+$/)?.[0]||1)}function xe(e){let t=``;for(let n=e;n>0;n=Math.floor((n-1)/26))t=String.fromCharCode(65+(n-1)%26)+t;return t}let Se=U(()=>{let e=u(R)?.sheets[u(z)];if(!e)return{columns:[],rows:[],clipped:!1};let t=Math.max(1,...e.cells.map(e=>ye(e.reference))),n=Math.max(1,...e.cells.map(e=>be(e.reference))),r=Math.min(100,t),i=Math.min(1e3,Math.floor(1e4/r),n),a=new Map(e.cells.map(e=>[e.reference.toUpperCase(),e.value])),o=Array.from({length:r},(e,t)=>xe(t+1));return{columns:o,rows:Array.from({length:i},(e,t)=>({number:t+1,values:o.map(e=>a.get(`${e}${t+1}`)||``)})),clipped:t>r||n>i}});var Ce=Un(),we=ce(Ce),Te=L(we),Ee=L(Te),De=D(Ee,!0),Oe=k(Ee,2),ke=D(Oe,!0),Ae=k(Oe,2),je=D(Ae,!0);t(Te);var Me=k(Te,2),Ne=L(Me),Pe=e=>{var r=Sn(),i=L(r);let a;var o=k(i,2);let s;t(r),N(()=>{B(r,`aria-label`,`${u(le)} view`),B(i,`aria-pressed`,u(l)===`preview`),a=w(i,1,``,null,a,{active:u(l)===`preview`}),B(o,`aria-pressed`,u(l)===`source`),s=w(o,1,``,null,s,{active:u(l)===`source`})}),n(`click`,i,()=>M(l,`preview`)),n(`click`,o,()=>M(l,`source`)),p(e,r)};P(Ne,e=>{u(ue)&&e(Pe)});var Fe=k(Ne,2),Ie=k(Fe,2);t(Me),t(we);var Le=k(we,2);let Re;var ze=L(Le),Ve=e=>{var n=Cn(),r=k(L(n),2),i=D(r);ee(2),t(n),N(e=>d(i,`Opening ${e??``}`),[()=>u(le).toLowerCase()]),p(e,n)},He=e=>{var n=wn(),i=k(L(n),4),a=D(i,!0),o=k(i,2);t(n),N(()=>{d(a,u(h)),B(o,`href`,u(H)),B(o,`download`,r.upload.filename)}),p(e,n)},Ue=e=>{var n=Tn(),i=k(L(n),6);t(n),N(()=>{B(i,`href`,u(H)),B(i,`download`,r.upload.filename)}),p(e,n)},We=e=>{var r=En(),i=ce(r),o=L(i),s=k(o,2),c=D(s),l=k(s,2),f=k(l,4),m=k(f,2),h=D(m),g=k(m,2);t(i);var _=k(i,2);let v;var y=L(_);oe(y,e=>M(a,e),()=>u(a));var b=k(y,2),C=D(b,!0);t(_),N(e=>{o.disabled=u(S)<=1||u(E),d(c,`Page ${u(S)??``} of ${u(x).numPages??``}`),l.disabled=u(S)>=u(x).numPages||u(E),f.disabled=u(T)<=.6||u(E),d(h,`${e??``}%`),g.disabled=u(T)>=2||u(E),v=w(_,1,`artifact-viewer__pdf-stage`,null,v,{"is-rendering":u(E)}),B(_,`aria-label`,`PDF page ${u(S)} visual preview`),B(b,`aria-label`,`PDF page ${u(S)} text`),d(C,u(O))},[()=>Math.round(u(T)*100)]),n(`click`,o,()=>M(S,u(S)-1)),n(`click`,l,()=>M(S,u(S)+1)),n(`click`,f,()=>M(T,Math.max(.6,u(T)-.2),!0)),n(`click`,g,()=>M(T,Math.min(2,u(T)+.2),!0)),p(e,r)},Ge=e=>{var r=Nn(),i=ce(r),a=L(i),o=D(a),s=k(a,4),c=e=>{var t=Dn(),n=D(t);N(()=>d(n,`${u(R).hiddenSheets??``} hidden ${u(R).hiddenSheets===1?`sheet`:`sheets`} omitted`)),p(e,t)};P(s,e=>{u(R).hiddenSheets>0&&e(c)});var l=k(s,2),m=e=>{var t=Dn(),n=D(t);N(()=>d(n,`${u(R).unsupportedSheets??``} non-worksheet ${u(R).unsupportedSheets===1?`sheet`:`sheets`} omitted`)),p(e,t)};P(l,e=>{u(R).unsupportedSheets>0&&e(m)}),t(i);var h=k(i,2),g=L(h),_=L(g),v=L(_),y=k(L(v));f(y,17,()=>u(Se).columns,I,(e,t)=>{var n=On(),r=D(n,!0);N(()=>d(r,u(t))),p(e,n)}),t(v),t(_);var b=k(_);f(b,21,()=>u(Se).rows,I,(e,n)=>{var r=An(),i=L(r),a=D(i,!0),o=k(i);f(o,17,()=>u(n).values,I,(e,t)=>{var n=kn(),r=D(n,!0);N(()=>d(r,u(t))),p(e,n)}),t(r),N(()=>d(a,u(n).number)),p(e,r)}),t(b),t(g);var x=k(g,2),S=e=>{var t=jn();p(e,t)};P(x,e=>{(u(Se).clipped||u(R).sheets[u(z)].truncated)&&e(S)}),t(h);var C=k(h,2);f(C,21,()=>u(R).sheets,I,(e,t,r)=>{var i=Mn();let a;var o=D(i,!0);N(()=>{B(i,`aria-selected`,u(z)===r),a=w(i,1,``,null,a,{active:u(z)===r}),d(o,u(t).name)}),n(`click`,i,()=>M(z,r,!0)),p(e,i)}),t(C),N(()=>{d(o,`${u(R).sheets.length??``} ${u(R).sheets.length===1?`sheet`:`sheets`}`),B(h,`aria-label`,`${u(R).sheets[u(z)].name} worksheet`)}),p(e,r)},qe=e=>{var r=Rn(),i=ce(r),a=L(i),o=k(a,2),c=D(o),l=k(o,2);t(i);var m=k(i,2),h=L(m);f(h,21,()=>u(ne).slides[u(re)].paragraphs,I,(e,t,n)=>{var r=s(),i=ce(r),a=e=>{var n=Pn(),r=D(n,!0);N(()=>d(r,u(t))),p(e,n)},o=e=>{var n=Fn(),r=D(n,!0);N(()=>d(r,u(t))),p(e,n)};P(i,e=>{n===0?e(a):e(o,-1)}),p(e,r)}),t(h);var g=k(h,4),_=e=>{var t=In(),n=D(t);N(()=>d(n,`${u(ne).hiddenSlides??``} hidden ${u(ne).hiddenSlides===1?`slide`:`slides`} omitted.`)),p(e,t)};P(g,e=>{u(ne).hiddenSlides>0&&e(_)});var v=k(g,2),y=e=>{var t=Ln();p(e,t)};P(v,e=>{u(ne).truncated&&e(y)}),t(m),N(()=>{a.disabled=u(re)===0,d(c,`Slide ${u(re)+1} of ${u(ne).slides.length??``}`),l.disabled=u(re)>=u(ne).slides.length-1,B(h,`aria-label`,`Slide ${u(re)+1}: ${u(ne).slides[u(re)].title}`)}),n(`click`,a,()=>M(re,u(re)-1)),n(`click`,l,()=>M(re,u(re)+1)),p(e,r)},Xe=e=>{var n=zn();i(n,()=>u(v),!0),t(n),p(e,n)},Ze=e=>{var n=Bn();i(n,()=>u(v),!0),t(n),p(e,n)},Qe=e=>{var n=Vn(),r=L(n);i(r,()=>u(b),!0),t(r),t(n),p(e,n)},$e=e=>{var n=Hn(),r=L(n),i=D(r,!0);t(n),N(()=>d(i,u(g))),p(e,n)};P(ze,e=>{u(m)===`loading`?e(Ve):u(m)===`error`?e(He,1):u(c)===`unsupported`?e(Ue,2):u(c)===`pdf`&&u(x)?e(We,3):u(c)===`spreadsheet`&&u(R)?e(Ge,4):u(c)===`presentation`&&u(ne)?e(qe,5):u(c)===`html`&&u(l)===`preview`&&u(v)?e(Xe,6):u(c)===`markdown`&&u(l)===`preview`?e(Ze,7):u(c)===`code`?e(Qe,8):e($e,-1)}),t(Le),N(e=>{d(De,u(le)),B(Oe,`title`,r.upload.filename),d(ke,r.upload.filename),d(je,e),B(Fe,`href`,u(H)),B(Fe,`download`,r.upload.filename),B(Fe,`aria-label`,`Download ${r.upload.filename}`),Re=w(Le,1,`artifact-viewer__body`,null,Re,{"is-pdf":u(c)===`pdf`,"is-office":u(c)===`spreadsheet`||u(c)===`presentation`})},[()=>Ke(r.upload.byte_size)]),n(`click`,Ie,function(...e){r.onClose?.apply(this,e)}),p(e,Ce),_()}W([`click`]);var Gn=l(``),Kn=l(``);function qn(e,r){o(r,!0);let i=S(r,`deleting`,3,!1),a=S(r,`error`,3,``),s=U(()=>r.message.author?.display_name||`Local User`);function c(){i()||r.onClose()}var l=Kn(),f=L(l),m=k(f,2),h=L(m),g=k(L(h),2);t(h);var v=k(h,2),y=k(L(v),2),b=L(y);{let e=U(()=>r.message.author?.id||r.message.author_id),t=U(()=>r.message.author?.avatar_url);Y(b,{class:`avatar`,get id(){return u(e)},get name(){return u(s)},get src(){return u(t)},size:36,loading:`eager`,fetchPriority:`auto`})}var x=k(b,2),C=L(x),w=L(C),T=D(w,!0),E=k(w,2),O=D(E,!0);t(C);var A=k(C,2),j=D(A,!0);t(x),t(y);var M=k(y,2),F=e=>{var t=Gn(),n=D(t,!0);N(()=>d(n,a())),p(e,t)};P(M,e=>{a()&&e(F)});var I=k(M,2),ee=L(I),R=k(ee,2),z=D(R,!0);t(I),t(v),t(m),t(l),N(e=>{f.disabled=i(),g.disabled=i(),d(T,u(s)),B(E,`datetime`,r.message.created_at),d(O,e),d(j,r.message.body),ee.disabled=i(),R.disabled=i(),d(z,i()?`Deleting...`:`Delete`)},[()=>Ze(r.message.created_at)]),n(`click`,f,c),n(`click`,g,c),n(`click`,ee,c),n(`click`,R,function(...e){r.onConfirm?.apply(this,e)}),p(e,l),_()}W([`click`]);var Jn=6500,Yn=l(`
      `);function Xn(e,n){o(n,!0);let r=U(()=>n.entries.filter(e=>e.userID!==n.currentUserID));function i(e,t=`Someone`){return e?.display_name?.trim()||(e?.handle?`@${e.handle}`:t)}let a=U(()=>u(r).length===0?``:u(r).length===1?`${i(u(r)[0].user)} is typing…`:u(r).length===2?`${i(u(r)[0].user)} and ${i(u(r)[1].user)} are typing…`:u(r).length===3?`${i(u(r)[0].user)}, ${i(u(r)[1].user)}, and ${i(u(r)[2].user)} are typing…`:`Several people are typing…`);var s=Yn();let c;var l=k(L(s),2),f=D(l,!0);t(s),N(()=>{c=w(s,1,`typing-indicator`,null,c,{visible:u(r).length>0}),d(f,u(a))}),p(e,s),_()}var Zn=45e3,Qn=l(`
      `),$n=l(`
      `),er=l(`
      `);function tr(e,n){o(n,!0);function r(e){return e.kind===`tool`&&e.toolName?!e.text||e.text===e.toolName?e.toolName:`${e.toolName}: ${e.text}`:e.text}function i(e){switch(e){case`tool`:return`⚙`;case`thinking`:case`commentary`:return`✦`;case`plan`:return`☰`;case`patch`:return`±`;case`command_output`:return`›`;case`error`:return`✕`;default:return`·`}}var a=s(),c=ce(a),l=e=>{var a=er();f(a,21,()=>n.turns,e=>e.key,(e,n)=>{var a=$n();f(a,21,()=>u(n).lines,e=>e.id,(e,n)=>{var a=Qn();let o;var s=L(a),c=D(s,!0),l=k(s,2),f=D(l,!0);t(a),N((e,t)=>{o=w(a,1,`agent-progress__line svelte-6vwkyv`,null,o,{"agent-progress__line--done":u(n).finalized}),B(a,`data-kind`,u(n).kind),d(c,e),d(f,t)},[()=>i(u(n).kind),()=>r(u(n))]),p(e,a)}),t(a),p(e,a)}),t(a),p(e,a)};P(c,e=>{n.turns.length>0&&e(l)}),p(e,a),_()}var nr=l(``),rr=l(``);function ir(e,r){o(r,!0);var i=rr(),a=L(i),s=k(a,2),c=L(s),l=k(L(c),2);t(c);var u=k(c,2),f=L(u),m=k(L(f),2);O(m),t(f);var h=k(f,2),g=e=>{var t=nr(),n=D(t,!0);N(()=>d(n,r.error)),p(e,t)};P(h,e=>{r.error&&e(g)});var y=k(h,2),b=L(y),x=k(b,2),S=D(x,!0);t(y),t(u),t(s),t(i),N(e=>{j(m,r.channelName),m.disabled=r.pending,x.disabled=e,d(S,r.pending?`Creating…`:`Create channel`)},[()=>r.pending||!r.channelName.trim()]),n(`click`,a,function(...e){r.onClose?.apply(this,e)}),n(`click`,l,function(...e){r.onClose?.apply(this,e)}),v(`submit`,u,e=>{e.preventDefault(),r.onCreate()}),n(`input`,m,e=>r.onChannelName(e.currentTarget.value)),n(`click`,b,function(...e){r.onClose?.apply(this,e)}),p(e,i),_()}W([`click`,`input`]);var ar=l(``),or=l(`
      No matching people yet
      `),sr=l(`

      `),cr=l(``),lr=l(``);function ur(e,r){o(r,!0);let i=U(()=>r.memberID.trim().toLowerCase().replace(/^@/,``)),a=U(()=>r.people.filter(e=>e.id!==r.currentUserID).filter(e=>!u(i)||e.display_name.toLowerCase().includes(u(i))||e.handle?.toLowerCase().includes(u(i))||e.id.toLowerCase().includes(u(i)))),s=U(()=>r.memberID.trim().startsWith(`usr_`)?r.memberID.trim():u(i)&&u(a).length===1?u(a)[0].id:``);function c(e){r.pending||!e||(r.onMemberID(e),r.onStart(e))}var l=lr(),m=L(l),h=k(m,2),g=L(h),y=k(L(g),2);t(g);var b=k(g,2),x=L(b),S=k(L(x),2);O(S),t(x);var C=k(x,2),w=L(C);f(w,17,()=>u(a),e=>e.id,(e,i)=>{var a=ar(),o=L(a);Y(o,{class:`dm-avatar`,get id(){return u(i).id},get name(){return u(i).display_name},get src(){return u(i).avatar_url},size:32});var s=k(o,2),l=L(s),f=D(l,!0),m=k(l,2),h=D(m,!0);t(s),t(a),N(e=>{a.disabled=r.pending,d(f,u(i).display_name),d(h,e)},[()=>dt(u(i).handle)||u(i).id]),n(`click`,a,()=>c(u(i).id)),p(e,a)});var T=k(w,2),E=e=>{var t=or();p(e,t)};P(T,e=>{u(a).length===0&&e(E)}),t(C);var A=k(C,2),M=e=>{var t=sr(),n=D(t,!0);N(()=>d(n,u(a).length>1?`Choose a person from the results.`:`Choose a person or enter a user ID.`)),p(e,t)};P(A,e=>{u(i)&&!u(s)&&e(M)});var F=k(A,2),I=e=>{var t=cr(),n=D(t,!0);N(()=>d(n,r.error)),p(e,t)};P(F,e=>{r.error&&e(I)});var ee=k(F,2),R=L(ee),z=k(R,2),te=D(z,!0);t(ee),t(b),t(h),t(l),N(()=>{j(S,r.memberID),S.disabled=r.pending,z.disabled=r.pending||!u(s),d(te,r.pending?`Starting…`:`Start DM`)}),n(`click`,m,function(...e){r.onClose?.apply(this,e)}),n(`click`,y,function(...e){r.onClose?.apply(this,e)}),v(`submit`,b,e=>{e.preventDefault(),c(u(s))}),n(`input`,S,e=>r.onMemberID(e.currentTarget.value)),n(`click`,R,function(...e){r.onClose?.apply(this,e)}),p(e,l),_()}W([`click`,`input`]);var dr=l(` `),fr=l(``),pr=l(`
      `),mr=l(``),hr=l(`

      Creating workspace…

      `),gr=l(`
      `),_r=l(``);function vr(e,r){o(r,!0);let i=S(r,`homeHref`,3,`/`),a=S(r,`homeLabel`,3,`cc`),s=S(r,`homeTitle`,3,`ClickClack home`);function c(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}var l=_r(),m=L(l);let h;var g=L(m),y=e=>{Xe(e,{size:48})},b=U(()=>Ot(a())),x=e=>{var t=dr(),n=D(t,!0);N(()=>d(n,a())),p(e,t)};P(g,e=>{u(b)?e(y):e(x,-1)}),t(m);var C=k(m,4),T=L(C);f(T,17,()=>r.workspaces,e=>e.id,(e,i)=>{var a=pr();let o;var s=L(a),l=L(s),f=e=>{var t=fr();N(e=>B(t,`src`,e),[()=>_e(u(i).icon_url)]),p(e,t)},m=e=>{var t=dr(),n=D(t,!0);N(e=>d(n,e),[()=>J(u(i).name)]),p(e,t)};P(l,e=>{u(i).icon_url?e(f):e(m,-1)}),t(s),t(a),N(e=>{o=w(a,1,`guild-wrap`,null,o,{active:u(i).id===r.selectedWorkspaceID}),B(s,`title`,u(i).name),B(s,`aria-label`,u(i).name),B(s,`href`,e)},[()=>r.hrefForWorkspace(u(i).id)]),n(`click`,s,e=>{c(e)&&(e.preventDefault(),r.onSelectWorkspace(u(i).id))}),p(e,a)});var E=k(T,2);t(C);var A=k(C,2),M=e=>{var i=gr(),a=L(i);O(a);var o=k(a,2),s=e=>{var t=mr(),n=D(t,!0);N(()=>d(n,r.createError)),p(e,t)};P(o,e=>{r.createError&&e(s)});var c=k(o,2),l=e=>{var t=hr();p(e,t)};P(c,e=>{r.createPending&&e(l)}),t(i),N(()=>{j(a,r.workspaceName),a.disabled=r.createPending}),v(`submit`,i,e=>{e.preventDefault(),r.onCreateWorkspace()}),n(`input`,a,e=>r.onWorkspaceName(e.currentTarget.value)),p(e,i)};P(A,e=>{r.showWorkspaceCreate&&e(M)}),t(l),N(e=>{h=w(m,1,`guild home`,null,h,{"home--mark":e}),B(m,`title`,s()),B(m,`aria-label`,s()),B(m,`href`,i())},[()=>Ot(a())]),n(`click`,E,function(...e){r.onToggleWorkspaceCreate?.apply(this,e)}),p(e,l),_()}W([`click`,`input`]);var yr=l(``),br=l(` `,1),xr=l(``),Sr=l(` `),Cr=l(``),wr=l(`
      `),Tr=l(``),Er=l(`Drag with a pointer, use Arrow Up and Arrow Down while focused, or open the move menu. Moves stay within the current channel section. `,1),Dr=l(`
      `);function Or(e,r){o(r,!0);let i=(e,i=F,a=F,o=F,s=F,c=F)=>{let f=U(()=>i().unread_count||0),_=U(()=>a().findIndex(e=>e.id===i().id));var y=Cr();let b;var C=L(y),T=e=>{var r=br(),s=ce(r),c=k(s,2),l=e=>{var r=yr(),o=L(r),s=k(o,2);t(r),oe(r,e=>M(S,e),()=>u(S)),N(e=>{B(r,`aria-label`,e),o.disabled=u(_)<=0,s.disabled=u(_)<0||u(_)>=a().length-1},[()=>`Move #${_t(i())}`]),n(`keydown`,r,e=>{e.key===`Escape`&&(e.preventDefault(),_e(!0))}),n(`click`,o,()=>ve(i().id,-1,a())),n(`click`,s,()=>ve(i().id,1,a())),p(e,r)};P(c,e=>{u(x)===i().id&&e(l)}),N(e=>{B(s,`aria-label`,e),B(s,`aria-expanded`,u(x)===i().id)},[()=>`Move #${_t(i())}`]),n(`click`,s,e=>void ge(i().id,e.currentTarget)),v(`dragstart`,s,e=>fe(e,i().id,o())),v(`dragend`,s,he),n(`keydown`,s,e=>{e.key===`ArrowUp`||e.key===`ArrowDown`?(e.preventDefault(),M(x,``),de(i().id,e.key===`ArrowUp`?-1:1,a())):e.key===`Escape`&&M(x,``)}),p(e,r)};P(C,e=>{c()&&e(T)});var E=k(C,2);let O;var A=k(L(E),2),j=D(A,!0),I=k(A,2),ee=e=>{var t=xr();p(e,t)};P(I,e=>{i().external_managed&&e(ee)});var R=k(I,2),z=e=>{var t=Sr(),n=D(t,!0);N(()=>{B(t,`aria-label`,`${u(f)} unread`),d(n,u(f)>99?`99+`:u(f))}),p(e,t)};P(R,e=>{u(f)>0&&!(i().id===r.selectedChannelID&&!r.selectedDirectID)&&e(z)}),t(E),t(y),N((e,t)=>{b=w(y,1,`channel-row`,null,b,{reorderable:c(),subdued:s(),dragging:u(l)===i().id,"drop-before":u(h)===i().id&&u(g),"drop-after":u(h)===i().id&&!u(g)}),B(E,`href`,e),O=w(E,1,`nav-item channel`,null,O,{active:i().id===r.selectedChannelID&&!r.selectedDirectID,"has-unread":u(f)>0&&!(i().id===r.selectedChannelID&&!r.selectedDirectID)}),d(j,t)},[()=>r.hrefForChannel(i().id),()=>_t(i())]),v(`dragover`,y,e=>{c()&&pe(e,i().id,o())}),v(`drop`,y,e=>{e.preventDefault(),!(!c()||u(m)!==o())&&(W(u(l),i().id,u(g),a()),he())}),n(`focusout`,y,e=>{e.currentTarget.contains(e.relatedTarget)||M(x,``)}),n(`click`,E,e=>{G(e)&&(e.preventDefault(),r.onSelectChannel(i().id))}),p(e,y)},a=(e,r=F,a=F,o=F)=>{let s=U(()=>V(r().key)),c=U(()=>H(r()));var l=wr();let m;var h=L(l),g=k(L(h),2),_=D(g,!0),v=k(g,2),y=D(v,!0);t(h);var b=k(h,2);f(b,21,()=>u(c),e=>e.id,(e,t)=>{i(e,()=>u(t),()=>r().channels,()=>r().key,o,()=>u(s))}),t(b),t(l),N(()=>{m=w(l,1,`channel-subgroup`,null,m,{"archived-channel-group":o()}),B(h,`aria-expanded`,u(s)),B(h,`aria-controls`,a()),d(_,r().label),d(y,r().channels.length),B(b,`id`,a()),B(b,`hidden`,!u(s)&&u(c).length===0)}),n(`click`,h,()=>se(r().key)),p(e,l)},c=`archived`,l=A(``),m=A(``),h=A(``),g=A(!0),b=A(!1),x=A(``),S=A(void 0),T,O=A(``),j=A(ie({})),I=U(()=>r.channels.filter(e=>!e.archived_at)),ee=U(()=>r.channels.filter(e=>!!e.archived_at)),R=U(()=>u(I).filter(e=>!e.sidebar_section?.trim())),z=U(()=>{let e=new Map;for(let t of u(I)){let n=t.sidebar_section?.trim();if(!n)continue;let r=e.get(n)??[];r.push(t),e.set(n,r)}return[...e.entries()].map(([e,t])=>({key:`section:${e}`,label:e,channels:t})).sort((e,t)=>e.label.localeCompare(t.label,void 0,{sensitivity:`base`}))}),te=U(()=>r.channels.filter(e=>e.id===r.selectedChannelID&&!r.selectedDirectID||(e.unread_count||0)>0));function ne(e){if(!e)return{};try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))return{};let n=Object.entries(t);return n.length>1e3||n.some(([e,t])=>e.length>256||typeof t!=`boolean`)?{}:Object.fromEntries(n)}catch{return{}}}function re(e){return`clickclack:sidebar-channel-groups:v1:${e}`}function ae(e){if(!e)return{};try{return ne(window.localStorage.getItem(re(e)))}catch{return{}}}function V(e){let t=u(j)[e];return typeof t==`boolean`?t:e!==c}function se(e){if(M(j,{...u(j),[e]:!V(e)},!0),r.workspaceID)try{window.localStorage.setItem(re(r.workspaceID),JSON.stringify(u(j)))}catch{}}function le(e){e.key===re(r.workspaceID)&&M(j,ne(e.newValue),!0)}function H(e){return V(e.key)?e.channels:e.channels.filter(e=>e.id===r.selectedChannelID&&!r.selectedDirectID||(e.unread_count||0)>0)}function ue(e){M(O,``),queueMicrotask(()=>{M(O,e,!0)})}function W(e,t,n,i){if(!e||!t||e===t)return;let a=r.channels.map(e=>e.id),o=a.indexOf(e);if(o<0)return;a.splice(o,1);let s=a.indexOf(t);if(s<0)return;a.splice(s+ +!n,0,e),r.onReorder(a);let c=r.channels.find(t=>t.id===e),l=i.map(e=>e.id).filter(t=>t!==e),u=l.indexOf(t);l.splice(u+ +!n,0,e),c&&ue(`Moved #${_t(c)} to position ${l.indexOf(e)+1} of ${l.length}`)}function de(e,t,n){let r=n.findIndex(t=>t.id===e),i=r+t;r<0||i<0||i>=n.length||W(e,n[i].id,t<0,n)}function fe(e,t,n){M(b,!0),M(x,``),M(l,t,!0),M(m,n,!0),e.dataTransfer?.setData(`text/plain`,t),e.dataTransfer&&(e.dataTransfer.effectAllowed=`move`)}function pe(e,t,n){if(!u(l)||u(l)===t||u(m)!==n)return;e.preventDefault();let r=e.currentTarget;M(h,t,!0),M(g,e.clientY{M(b,!1)},0)}async function ge(e,t){if(!u(b)){if(u(x)===e){M(x,``);return}T=t,M(x,e,!0),await y(),u(S)?.querySelector(`button:not(:disabled)`)?.focus()}}async function _e(e=!1){M(x,``),e&&(await y(),T?.focus())}function ve(e,t,n){de(e,t,n),_e(!0)}function G(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}C(()=>{M(j,ae(r.workspaceID),!0)}),C(()=>{r.expanded||(M(x,``),me(),M(b,!1))});var ye=Dr();v(`storage`,E,le);let be;var xe=L(ye),Se=L(xe),Ce=k(Se,2);t(xe);var we=k(xe,2),Te=L(we),Ee=e=>{var t=Er(),n=k(ce(t),2);f(n,17,()=>u(R),e=>e.id,(e,t)=>{i(e,()=>u(t),()=>u(R),()=>`unsectioned`,()=>!1,()=>!0)});var o=k(n,2);f(o,19,()=>u(z),e=>e.key,(e,t,n)=>{a(e,()=>u(t),()=>`sidebar-channel-section-${u(n)}`,()=>!1)});var s=k(o,2),l=e=>{a(e,()=>({key:c,label:`Archived`,channels:u(ee)}),()=>`sidebar-archived-channels`,()=>!0)};P(s,e=>{u(ee).length>0&&e(l)});var d=k(s,2),m=e=>{var t=Tr();p(e,t)};P(d,e=>{r.channels.length===0&&e(m)}),p(e,t)},De=e=>{var t=s(),n=ce(t);f(n,17,()=>u(te),e=>e.id,(e,t)=>{{let n=U(()=>!!u(t).archived_at);i(e,()=>u(t),()=>u(te),()=>`priority`,()=>u(n),()=>!1)}}),p(e,t)};P(Te,e=>{r.expanded?e(Ee):e(De,-1)}),t(we);var Oe=k(we,2),ke=D(Oe,!0);t(ye),N(()=>{be=w(ye,1,`nav-section`,null,be,{collapsed:!r.expanded}),B(Se,`aria-expanded`,r.expanded),B(we,`hidden`,!r.expanded&&u(te).length===0),d(ke,u(O))}),n(`click`,Se,function(...e){r.onToggle?.apply(this,e)}),n(`click`,Ce,function(...e){r.onCreateChannel?.apply(this,e)}),p(e,ye),_()}W([`focusout`,`click`,`keydown`]);var kr=l(` `),Ar=l(``),jr=l(``),Mr=l(`
      `),Nr=l(``),Pr=l(`
      `),Fr=l(`
      `);function Ir(e,r){o(r,!0);let i=A(``),a=U(()=>r.expanded?r.conversations:r.conversations.filter(e=>e.id===r.selectedDirectID||(e.unread_count||0)>0));function s(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}function c(e){M(i,u(i)===e?``:e,!0)}function l(){M(i,``)}var m=Fr();let h;var g=L(m),v=L(g),y=k(v,2);t(g);var b=k(g,2),x=L(b);f(x,17,()=>u(a),e=>e.id,(e,a)=>{let o=U(()=>pt(u(a),r.currentUserID)),f=U(()=>u(a).unread_count||0),m=U(()=>u(a).id===r.selectedDirectID);var h=Mr();let g;var _=L(h);let v;var y=L(_);{let e=U(()=>u(o)?.id||u(a).id),t=U(()=>u(o)?.display_name),n=U(()=>X(u(o))?void 0:u(o)?.avatar_url);Y(y,{class:`dm-avatar`,get id(){return u(e)},get name(){return u(t)},get src(){return u(n)},size:22})}var b=k(y,2),x=D(b,!0),S=k(b,2),C=e=>{var t=kr(),n=D(t,!0);N(()=>{B(t,`aria-label`,`${u(f)} unread`),d(n,u(f)>99?`99+`:u(f))}),p(e,t)},T=e=>{var t=Ar();p(e,t)};P(S,e=>{u(f)>0&&!u(m)?e(C):e(T,-1)}),t(_);var E=k(_,2),O=k(E,2),A=e=>{var t=jr(),i=D(t);n(`click`,i,e=>{e.preventDefault(),e.stopPropagation(),l(),r.onHideDirect(u(a).id)}),p(e,t)};P(O,e=>{u(i)===u(a).id&&e(A)}),t(h),N((e,t,n)=>{g=w(h,1,`dm-row`,null,g,{active:u(m)}),B(_,`href`,e),v=w(_,1,`nav-item dm`,null,v,{active:u(m),"has-unread":u(f)>0&&!u(m)}),d(x,t),B(E,`aria-label`,n),B(E,`aria-expanded`,u(i)===u(a).id)},[()=>r.hrefForDirect(u(a).id),()=>ct(u(a),r.currentUserID),()=>`Direct message actions for ${ct(u(a),r.currentUserID)}`]),n(`click`,_,e=>{s(e)&&(e.preventDefault(),r.onSelectDirect(u(a).id))}),n(`click`,E,e=>{e.preventDefault(),e.stopPropagation(),c(u(a).id)}),n(`keydown`,E,e=>{e.key===`Escape`&&l()}),p(e,h)});var S=k(x,2),C=e=>{var t=Nr();p(e,t)};P(S,e=>{r.expanded&&r.conversations.length===0&&e(C)});var T=k(S,2),E=e=>{var i=Pr(),a=L(i),o=D(a),s=k(a,2);t(i),N(()=>d(o,`Closed ${r.hiddenDirectTitle??``}`)),n(`click`,s,function(...e){r.onUndoHideDirect?.apply(this,e)}),p(e,i)};P(T,e=>{r.expanded&&r.hiddenDirectTitle&&e(E)}),t(b),t(m),N(()=>{h=w(m,1,`nav-section`,null,h,{collapsed:!r.expanded}),B(v,`aria-expanded`,r.expanded),B(b,`hidden`,!r.expanded&&u(a).length===0)}),n(`click`,v,function(...e){r.onToggle?.apply(this,e)}),n(`click`,y,function(...e){r.onCreateDirect?.apply(this,e)}),p(e,m),_()}W([`click`,`keydown`]);var Lr=l(``),Rr=l(`Connecting…`),zr=l(`
      `),Br=l(` `),Vr=l(``),Hr=l(``),Ur=l(``);function Wr(e,r){o(r,!0);let i=S(r,`showHeader`,3,!0),a=`clickclack:sidebar-sections:v1:`,s={channels:!0,directMessages:!0,people:!0},c=A(ie({...s}));function l(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.channels==`boolean`&&typeof t.directMessages==`boolean`&&typeof t.people==`boolean`}function m(e){if(!e)return{...s};try{let t=window.localStorage.getItem(`${a}${e}`);if(!t)return{...s};let n=JSON.parse(t);return l(n)?n:{...s}}catch{return{...s}}}function h(e){if(M(c,{...u(c),[e]:!u(c)[e]},!0),r.workspaceID)try{window.localStorage.setItem(`${a}${r.workspaceID}`,JSON.stringify(u(c)))}catch{}}C(()=>{M(c,m(r.workspaceID),!0)});let g=1e6,y=A(ie([]));function b(e,t){return`clickclack:sidebar-channel-order:v1:${t}:${e}`}function x(e){if(!e||e.length>g)return[];try{let t=JSON.parse(e);return Array.isArray(t)&&t.length<=1e4&&t.every(e=>typeof e==`string`&&e.length<=128)?[...new Set(t)]:[]}catch{return[]}}function T(e,t){if(!e||!t)return[];try{return x(window.localStorage.getItem(b(e,t)))}catch{return[]}}function O(e){if(M(y,e,!0),!(!r.workspaceID||!r.currentUser?.id))try{let t=b(r.workspaceID,r.currentUser.id),n=JSON.stringify(e);if(n.length>g){window.localStorage.removeItem(t);return}window.localStorage.setItem(t,n)}catch{}}function j(e){!r.workspaceID||!r.currentUser?.id||e.key===b(r.workspaceID,r.currentUser.id)&&M(y,x(e.newValue),!0)}let F=U(()=>{let e=new Map(r.channels.map(e=>[e.id,e]));return[...u(y).flatMap(t=>{let n=e.get(t);return n?(e.delete(t),[n]):[]}),...e.values()]});C(()=>{M(y,T(r.workspaceID,r.currentUser?.id||``),!0)});function I(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}var R=Ur();v(`storage`,E,j);var z=L(R),te=e=>{var i=zr(),a=L(i),o=L(a),s=e=>{var t=Lr();N(e=>B(t,`src`,e),[()=>_e(r.workspaceIconURL)]),p(e,t)};P(o,e=>{r.workspaceIconURL&&e(s)});var c=k(o,2),l=L(c),u=L(l),f=D(u,!0);ee(2),t(l);var m=k(l,2),h=e=>{var t=Rr();p(e,t)};P(m,e=>{r.connected||e(h)}),t(c),t(a);var g=k(a,2),_=L(g),v=L(_),y=D(v);t(_),t(g),t(i),N(()=>{d(f,r.workspaceName||`Pick a workspace`),B(_,`aria-label`,r.sidebarCollapsed?`Expand sidebar`:`Collapse sidebar`),B(_,`title`,r.sidebarCollapsed?`Expand sidebar`:`Collapse sidebar`),B(y,`d`,r.sidebarCollapsed?`m9 6 6 6-6 6`:`m15 6-6 6 6 6`)}),n(`click`,a,function(...e){r.onOpenWorkspaceSettings?.apply(this,e)}),n(`click`,_,function(...e){r.onToggleCollapse?.apply(this,e)}),p(e,i)};P(z,e=>{i()&&e(te)});var ne=k(z,2),re=L(ne);Or(re,{get workspaceID(){return r.workspaceID},get expanded(){return u(c).channels},get channels(){return u(F)},get selectedChannelID(){return r.selectedChannelID},get selectedDirectID(){return r.selectedDirectID},get hrefForChannel(){return r.hrefForChannel},get onSelectChannel(){return r.onSelectChannel},get onCreateChannel(){return r.onCreateChannel},onToggle:()=>h(`channels`),onReorder:O});var ae=k(re,2);{let e=U(()=>r.currentUser?.id);Ir(ae,{get expanded(){return u(c).directMessages},get conversations(){return r.directConversations},get currentUserID(){return u(e)},get selectedDirectID(){return r.selectedDirectID},get hrefForDirect(){return r.hrefForDirect},get onSelectDirect(){return r.onSelectDirect},get onCreateDirect(){return r.onCreateDirect},get onHideDirect(){return r.onHideDirect},get hiddenDirectTitle(){return r.hiddenDirectTitle},get onUndoHideDirect(){return r.onUndoHideDirect},onToggle:()=>h(`directMessages`)})}var oe=k(ae,2);let V;var se=L(oe),ce=D(se),le=k(se,2),H=L(le);f(H,17,()=>r.recentPeople,e=>e.id,(e,i)=>{let a=U(()=>ft(r.directConversations,u(i).id,r.currentUser?.id));var o=Br();let s;var c=L(o);Y(c,{class:`dm-avatar`,get id(){return u(i).id},get name(){return u(i).display_name},get src(){return u(i).avatar_url},size:22});var l=k(c,2),f=D(l,!0);ee(2),t(o),N(e=>{B(o,`href`,e),s=w(o,1,`nav-item dm`,null,s,{active:u(a)?.id===r.selectedDirectID||r.selectedProfile?.id===u(i).id}),d(f,u(i).display_name)},[()=>u(a)?r.hrefForDirect(u(a).id):`#`]),n(`click`,o,e=>{if(u(a)){if(!I(e))return;e.preventDefault(),r.onSelectDirect(u(a).id)}else e.preventDefault(),r.onOpenProfile(u(i))}),p(e,o)});var ue=k(H,2),W=e=>{var t=Vr();p(e,t)};P(ue,e=>{r.recentPeople.length===0&&e(W)}),t(le),t(oe),t(ne);var de=k(ne,2),fe=e=>{var i=Hr(),a=L(i);Y(a,{class:`dm-avatar`,get id(){return r.currentUser.id},get name(){return r.currentUser.display_name},get src(){return r.currentUser.avatar_url},size:28,loading:`eager`,fetchPriority:`auto`});var o=k(a,2),s=L(o),c=D(s,!0),l=k(s,2),u=D(l,!0);t(o),ee(2),t(i),N((e,t)=>{B(i,`aria-label`,e),d(c,r.currentUser.display_name),d(u,t)},[()=>`Account settings for ${r.currentUser.display_name} ${dt(r.currentUser.handle)}`,()=>r.currentUser.handle?dt(r.currentUser.handle):r.connected?`Active`:`Reconnecting…`]),n(`click`,i,function(...e){r.onOpenSettings?.apply(this,e)}),n(`contextmenu`,i,e=>{e.preventDefault(),r.onOpenSettings()}),p(e,i)};P(de,e=>{r.currentUser&&e(fe)}),t(R),N(()=>{V=w(oe,1,`nav-section`,null,V,{collapsed:!u(c).people}),B(ce,`aria-expanded`,u(c).people),B(le,`hidden`,!u(c).people)}),n(`click`,ce,()=>h(`people`)),p(e,R),_()}W([`click`,`contextmenu`]);var Gr=l(`
      Loading...
      `),Kr=l(`
      `),qr=l(`
      `),Jr=l(`

      No pinned messages

      Pin important messages to keep them easily accessible.

      `),Yr=l(`
      `),Xr=l(`
      `),Zr=l(`
      `),Qr=l(` `,1),$r=l(`

      Pinned Messages

      `);function ei(e,r){o(r,!0);let a=S(r,`loading`,3,!1),s=S(r,`error`,3,``),c=S(r,`topics`,19,()=>[]),l=S(r,`mentionPeople`,19,()=>[]),m=S(r,`maxPins`,3,100),g=A(ie(new Set)),v=A(``);async function y(e){if(!u(g).has(e.id)){M(g,new Set(u(g)).add(e.id),!0),M(v,``);try{await r.onUnpin(e)}catch(e){M(v,e instanceof Error?e.message:`Could not unpin message`,!0)}finally{let t=new Set(u(g));t.delete(e.id),M(g,t,!0)}}}var b=$r(),x=L(b),C=L(x),w=L(C),T=k(L(w),2),E=D(T);t(w);var O=k(w,2),j=D(O);t(C);var F=k(C,2);t(x);var I=k(x,2),ee=L(I),R=e=>{var t=Gr();p(e,t)},z=e=>{var t=Kr(),n=D(t,!0);N(()=>d(n,s())),p(e,t)},te=e=>{var a=Qr(),o=ce(a),s=e=>{var t=qr(),n=D(t,!0);N(()=>d(n,u(v))),p(e,t)};P(o,e=>{u(v)&&e(s)});var m=k(o,2),_=e=>{var t=Jr();p(e,t)},b=e=>{var a=Zr();f(a,21,()=>r.messages,e=>e.id,(e,a)=>{let o=U(()=>c().find(e=>e.id===u(a).topic_id));var s=Xr(),m=L(s),_=L(m),v=D(_,!0),b=k(_,2),x=D(b,!0);t(m);var S=k(m,2);Z(S,{get topic(){return u(o)},get onSelect(){return r.onSelectTopic}});var C=k(S,2);i(C,()=>et(u(a).body),!0),t(C),h(C,e=>We?.(e)),h(C,(e,t)=>q?.(e,t),()=>({people:l(),attentionUserID:r.mentionAttentionUserID}));var w=k(C,2),T=e=>{var n=Yr();f(n,21,()=>u(a).attachments,e=>e.id,(e,t)=>{{let n=U(()=>Be(u(t)));nt(e,{get upload(){return u(t)},get url(){return u(n)},get onOpenImage(){return r.onOpenImage},get onOpenArtifact(){return r.onOpenArtifact}})}}),t(n),p(e,n)};P(w,e=>{u(a).attachments?.length&&e(T)});var E=k(w,2),O=L(E),A=k(O,2);t(E),t(s),N((e,t)=>{B(s,`data-message-id`,u(a).id),d(v,u(a).author?.display_name||`Unknown`),d(x,e),A.disabled=t},[()=>Ze(u(a).created_at),()=>u(g).has(u(a).id)]),n(`click`,O,()=>r.onOpenThread(u(a))),n(`click`,A,()=>y(u(a))),p(e,s)}),t(a),p(e,a)};P(m,e=>{r.messages.length===0?e(_):e(b,-1)}),p(e,a)};P(ee,e=>{a()?e(R):s()?e(z,1):e(te,-1)}),t(I),t(b),N(()=>{d(E,`${r.messages.length??``} / ${m()??``} pinned`),d(j,`Shared across this channel, with a maximum of ${m()??``} messages.`)}),n(`click`,F,function(...e){r.onClose?.apply(this,e)}),p(e,b),_()}W([`click`]);var ti=l(` `,1),ni=l(`
      `),ri=l(`
      We couldn’t search messages

      `),ii=l(`
      No messages found

      Try another word or phrase.

      `),ai=l(`deleted bot`),oi=l(` `),si=l(` `),ci=l(` `),li=l(` Reply in thread`),ui=l(` `),di=l(`
    • `),fi=l(``),pi=l(``),mi=l(``),hi=l(`
        `,1),gi=l(``);function _i(e,r){o(r,!0);let i=S(r,`covered`,3,!1),a=S(r,`inert`,3,!1),c=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`}),l=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`}),h=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`});function g(e,t){let n=Array.from(e),r=[],i=0;for(let e of t){let t=Math.max(i,Math.min(n.length,e.start)),a=Math.max(t,Math.min(n.length,e.end));t>i&&r.push({text:n.slice(i,t).join(``),highlighted:!1}),a>t&&r.push({text:n.slice(t,a).join(``),highlighted:!0}),i=a}return i{var t=m(`Searching messages…`);p(e,t)},R=e=>{var t=ti(),n=ce(t),i=k(n),a=e=>{var t=m();N(()=>d(t,`in ${r.session.scope.label??``}`)),p(e,t)};P(i,e=>{r.session.scope.label&&e(a)}),N(()=>d(n,`${r.session.results.length??``}${r.session.nextCursor?`+`:``} ${r.session.results.length===1&&!r.session.nextCursor?`result`:`results`}`)),p(e,t)},z=e=>{var t=m(`Search unavailable`);p(e,t)};P(F,e=>{r.session.state===`loading`?e(ee):r.session.state===`ready`?e(R,1):r.session.state===`error`&&e(z,2)}),t(M);var te=k(M,2),ne=L(te),re=e=>{var t=ni();p(e,t)},ie=e=>{var n=ri(),i=k(L(n),4),a=D(i,!0);t(n),N(()=>d(a,r.session.error)),p(e,n)},ae=e=>{var t=ii();p(e,t)},oe=e=>{var i=hi(),a=ce(i);f(a,21,()=>r.session.results,e=>e.id,(e,i)=>{let a=U(()=>r.contextFor(u(i)));var o=di(),c=L(o);let l;var h=L(c);{let e=U(()=>X(u(i).author)?void 0:u(i).author.avatar_url);Y(h,{class:`dm-avatar`,get id(){return u(i).author.id},get name(){return u(i).author.display_name},get src(){return u(e)},size:30})}var _=k(h,2),y=L(_),b=L(y),x=D(b,!0),S=k(b,2),C=e=>{var t=ai();p(e,t)},T=U(()=>X(u(i).author)),E=e=>{var t=oi(),n=D(t,!0);N(e=>d(n,e),[()=>dt(lt(u(i).author))]),p(e,t)},O=U(()=>lt(u(i).author));P(S,e=>{u(T)?e(C):u(O)&&e(E,1)});var A=k(S,2),j=D(A,!0);t(y);var M=k(y,2);f(M,21,()=>g(u(i).snippet,u(i).highlights),I,(e,t)=>{var n=s(),r=ce(n),i=e=>{var n=si(),r=D(n,!0);N(()=>d(r,u(t).text)),p(e,n)},a=e=>{var n=m();N(()=>d(n,u(t).text)),p(e,n)};P(r,e=>{u(t).highlighted?e(i):e(a,-1)}),p(e,n)}),t(M);var F=k(M,2),ee=L(F),R=e=>{var t=ci(),n=D(t,!0);N(()=>d(n,u(a))),p(e,t)};P(ee,e=>{u(a)&&e(R)});var z=k(ee,2),te=e=>{var t=li();p(e,t)},ne=e=>{var n=ui(),r=k(L(n));t(n),N(()=>d(r,` ${u(i).reply_count??``} ${u(i).reply_count===1?`reply`:`replies`}`)),p(e,n)};P(z,e=>{u(i).parent_message_id?e(te):u(i).reply_count>0&&e(ne,1)}),t(F),t(_),t(c),t(o),N(e=>{l=w(c,1,`search-result`,null,l,{"is-active":r.session.activeResultID===u(i).id}),B(c,`data-result-id`,u(i).id),d(x,u(i).author.display_name||`Local User`),B(A,`datetime`,u(i).created_at),d(j,e)},[()=>v(u(i).created_at)]),n(`click`,c,()=>r.onOpenResult(u(i))),p(e,o)}),t(a);var o=k(a,2),c=e=>{var i=fi(),a=L(i),o=D(a,!0),s=k(a,2);t(i),N(()=>d(o,r.session.moreError)),n(`click`,s,function(...e){r.onLoadMore?.apply(this,e)}),p(e,i)},l=e=>{var t=pi(),i=D(t,!0);N(()=>{t.disabled=r.session.loadingMore,d(i,r.session.loadingMore?`Loading more…`:`Load more results`)}),n(`click`,t,function(...e){r.onLoadMore?.apply(this,e)}),p(e,t)},h=e=>{var t=mi();p(e,t)};P(o,e=>{r.session.moreError?e(c):r.session.nextCursor?e(l,1):e(h,-1)}),p(e,i)};P(ne,e=>{r.session.state===`loading`?e(re):r.session.state===`error`?e(ie,1):r.session.results.length===0?e(ae,2):e(oe,-1)}),t(te),t(y),N(()=>{b=w(y,1,`search-results`,null,b,{covered:i()}),y.inert=a(),B(y,`aria-hidden`,i()?`true`:void 0),d(E,`Search${r.session.scope.label?` in ${r.session.scope.label}`:``}`),d(A,`Results for “${r.session.query??``}”`)}),n(`click`,j,function(...e){r.onClose?.apply(this,e)}),p(e,y),_()}W([`click`]);var vi=l(``),yi=l(`
        `),bi=l(`

        `,1),xi=l(`
        `),Si=l(``);function Ci(e,r){o(r,!0);let i=S(r,`saving`,3,!1),a=S(r,`error`,3,``),s=A(!1),c=U(()=>!!r.channel.archived_at),l=U(()=>`#${_t(r.channel)}`);function f(){i()||r.onClose()}var m=Si(),h=L(m),g=k(h,2),v=L(g),y=k(L(v),2);t(v);var b=k(v,2),x=L(b),C=L(x),w=D(C,!0);ee(2),t(x);var T=k(x,2),E=e=>{var t=vi(),n=D(t,!0);N(()=>d(n,a())),p(e,t)};P(T,e=>{a()&&e(E)});var O=k(T,2),j=e=>{var a=yi(),o=L(a),s=k(o,2),c=D(s,!0);t(a),N(()=>{o.disabled=i(),s.disabled=i(),d(c,i()?`Restoring...`:`Restore channel`)}),n(`click`,o,f),n(`click`,s,()=>r.onArchivedChange(!1)),p(e,a)},F=e=>{var a=bi(),o=ce(a),c=D(o),f=k(o,2),m=L(f),h=k(m,2),g=D(h,!0);t(f),N(()=>{d(c,`Archive ${u(l)??``}? The channel will remain available to workspace members under Archived.`),m.disabled=i(),h.disabled=i(),d(g,i()?`Archiving...`:`Archive channel`)}),n(`click`,m,()=>M(s,!1)),n(`click`,h,()=>r.onArchivedChange(!0)),p(e,a)},I=e=>{var r=xi(),a=L(r),o=k(a,2);t(r),N(()=>{a.disabled=i(),o.disabled=i()}),n(`click`,a,f),n(`click`,o,()=>M(s,!0)),p(e,r)};P(O,e=>{u(c)?e(j):u(s)?e(F,1):e(I,-1)}),t(b),t(g),t(m),N(()=>{h.disabled=i(),y.disabled=i(),d(w,u(l))}),n(`click`,h,f),n(`click`,y,f),p(e,m),_()}W([`click`]);var wi=l(`

        `),Ti=l(``),Ei=l(`
        `);function Di(e,n){o(n,!0);let r=A(!1),i=A(``),s=A(!1),c=new AbortController;te(()=>c.abort());async function l(){if(!u(r)){M(r,!0),M(i,``),M(s,!1);try{let e=await Ce({method:`PATCH`,body:JSON.stringify(n.payload()),signal:c.signal});c.signal.throwIfAborted(),n.onUserUpdated(e.user),M(i,`Saved`),n.onSaved?.()}catch(e){if(c.signal.aborted)return;M(i,xe(e,`Could not save ${n.section}`),!0),M(s,!0)}finally{M(r,!1)}}}var f=Ei(),m=L(f),h=L(m);a(h,()=>n.children),t(m);var g=k(m,2),y=L(g),b=e=>{var t=wi();let n;var r=D(t,!0);N(()=>{n=w(t,1,`settings-status`,null,n,{"is-error":u(s)}),d(r,u(i))}),p(e,t)},x=e=>{var t=Ti();p(e,t)};P(y,e=>{u(i)?e(b):e(x,-1)});var S=k(y,2),C=D(S,!0);t(g),t(f),N(()=>{m.disabled=u(r),S.disabled=u(r),d(C,u(r)?`Saving...`:`Save ${n.section}`)}),v(`submit`,f,e=>{e.preventDefault(),l()}),p(e,f),_()}var Oi=`clickclack:browser-notifications-enabled:v1:`;function ki(e){return`${Oi}${e}`}function Ai(e){if(!e)return!1;try{return window.localStorage.getItem(ki(e))===`enabled`}catch{return!1}}function ji(e,t){if(!e)return!1;try{return t?window.localStorage.setItem(ki(e),`enabled`):window.localStorage.removeItem(ki(e)),!0}catch{return!1}}var Mi=l(`

        Browser notifications are not supported on this device.

        `),Ni=l(`

        Browser notifications are blocked by this browser.

        `),Pi=l(`

        `),Fi=l(`

        Show alerts when ClickClack is in the background.

        `);function Ii(e,r){o(r,!0);let i=S(r,`isDesktop`,3,!1),a=A(!1),s=A(!1),c=A(`default`),l=A(``),f=A(!1);C(()=>{m(r.user.id,i())});function m(e,t){if(t){M(a,!0),M(c,`granted`),M(s,Ai(e),!0),r.onChanged?.(u(s));return}M(a,typeof Notification<`u`),M(c,u(a)?Notification.permission:`unsupported`,!0);let n=Ai(e);M(s,u(c)===`granted`&&n,!0),n&&u(c)!==`granted`&&ji(e,!1),r.onChanged?.(u(s))}async function h(e){if(M(l,``),M(f,!1),!e){ji(r.user.id,!1),M(s,!1),r.onChanged?.(!1),M(l,i()?`Desktop notifications disabled`:`Browser notifications disabled`,!0);return}if(i()){M(s,ji(r.user.id,!0),!0),r.onChanged?.(u(s)),M(l,u(s)?`Desktop notifications enabled`:`Desktop notification preference could not be saved`,!0),M(f,!u(s));return}if(typeof Notification>`u`){M(a,!1),M(c,`unsupported`),M(s,!1),r.onChanged?.(!1),M(l,`Browser notifications are not supported`),M(f,!0);return}if(M(c,Notification.permission==="default"?await Notification.requestPermission():Notification.permission,!0),M(a,!0),u(c)===`granted`){M(s,ji(r.user.id,!0),!0),r.onChanged?.(u(s)),M(l,u(s)?`Browser notifications enabled`:`Browser notification preference could not be saved`,!0),M(f,!u(s));return}ji(r.user.id,!1),M(s,!1),r.onChanged?.(!1),M(l,u(c)===`denied`?`Browser notifications are blocked by this browser`:`Browser notifications were not enabled`,!0),M(f,!0)}var g=Fi(),v=L(g),y=L(v),b=D(y,!0),x=k(y,4),T=e=>{var t=Mi();p(e,t)},E=e=>{var t=Ni();p(e,t)};P(x,e=>{!i()&&!u(a)?e(T):!i()&&u(c)===`denied`&&e(E,1)});var j=k(x,2),F=e=>{var t=Pi();let n;var r=D(t,!0);N(()=>{n=w(t,1,`settings-row2__hint`,null,n,{"is-error":u(f)}),d(r,u(l))}),p(e,t)};P(j,e=>{u(l)&&e(F)}),t(v);var I=k(v,2),ee=L(I);O(ee),t(I),t(g),N(()=>{d(b,i()?`Desktop notifications`:`Browser notifications`),B(ee,`aria-label`,i()?`Desktop notifications`:`Browser notifications`),ee.disabled=!u(a)||u(c)===`denied`,R(ee,u(s))}),n(`change`,ee,e=>void h(e.currentTarget.checked)),p(e,g),_()}W([`change`]);var Li=l(``),Ri=l(`
        Preview

        Shown in messages, mentions, and your profile card.

        Used in mentions and the quick switcher. Must be unique.

        Paste a public image URL. Your initials show when empty.

        Conversation display

        Keep agent reasoning summaries out of the message timeline.

        Hide tool execution details while keeping ordinary messages visible.

        Choose which side of the timeline shows your messages.

        Choose which side of the timeline shows messages from other people and agents.

        Notifications

        `,1);function zi(e,r){o(r,!0);let i=S(r,`isDesktop`,3,!1),a=A(``),s=A(``),c=A(``),l=U(()=>u(a).trim()||r.user.display_name||`Your name`),f=U(()=>u(s).trim().replace(/^@+/,``)||r.user.handle||``);C(()=>{M(a,r.user.display_name,!0),M(s,r.user.handle??``,!0),M(c,r.user.avatar_url,!0)});function m(){M(c,``)}Di(e,{section:`profile`,get onUserUpdated(){return r.onUserUpdated},get onSaved(){return r.onSaved},payload:()=>({display_name:u(a),handle:u(s).trim().replace(/^@+/,``),avatar_url:u(c)}),children:(e,o)=>{var h=Ri(),g=ce(h),_=L(g);Y(_,{get id(){return r.user.id},get name(){return u(l)},get src(){return u(c)},size:52,loading:`eager`,fetchPriority:`auto`});var v=k(_,2),y=L(v),b=D(y,!0),S=k(y,2),C=D(S,!0);t(v),ee(2),t(g);var w=k(g,2),T=L(w),E=k(L(T),2),A=L(E);O(A),t(E),t(T);var j=k(T,2),F=k(L(j),2),I=L(F),z=k(L(I),2);O(z),t(I),t(F),t(j);var te=k(j,2),ne=k(L(te),2),re=L(ne);O(re);var B=k(re,2),ie=e=>{var t=Li();n(`click`,t,m),p(e,t)};P(B,e=>{u(c)&&e(ie)}),t(ne),t(te);var ae=k(te,4),oe=k(L(ae),2),V=L(oe);O(V),t(oe),t(ae);var H=k(ae,2),ue=k(L(H),2),U=L(ue);O(U),t(ue),t(H);var W=k(H,2),de=k(L(W),2),fe=L(de),pe=L(fe);pe.value=pe.__value=`left`;var me=k(pe);me.value=me.__value=`right`,t(fe);var he;x(fe),t(de),t(W);var ge=k(W,2),_e=k(L(ge),2),ve=L(_e),G=L(ve);G.value=G.__value=`left`;var ye=k(G);ye.value=ye.__value=`right`,t(ve);var be;x(ve),t(_e),t(ge),Ii(k(ge,4),{get user(){return r.user},get isDesktop(){return i()},get onChanged(){return r.onBrowserNotificationsChanged}}),t(w),N(()=>{d(b,u(l)),d(C,u(f)?`@${u(f)}`:`No handle set`),R(V,r.hideCommentary),R(U,r.hideToolCalls),he!==(he=r.userAlign)&&(fe.value=(fe.__value=he)??``,le(fe,he)),be!==(be=r.otherAlign)&&(ve.value=(ve.__value=be)??``,le(ve,be))}),se(A,()=>u(a),e=>M(a,e)),se(z,()=>u(s),e=>M(s,e)),se(re,()=>u(c),e=>M(c,e)),n(`change`,V,e=>r.onHideCommentary(e.currentTarget.checked)),n(`change`,U,e=>r.onHideToolCalls(e.currentTarget.checked)),n(`change`,fe,e=>r.onUserAlign(e.currentTarget.value===`right`?`right`:`left`)),n(`change`,ve,e=>r.onOtherAlign(e.currentTarget.value===`right`?`right`:`left`)),p(e,h)},$$slots:{default:!0}}),_()}W([`click`,`change`]);var Bi=l(`

        Desktop

        Mobile push

        Send push notifications to your phone via Pushover.

        Find this in your Pushover dashboard under "Your User Key".

        `);function Vi(e,n){o(n,!0);let r=S(n,`isDesktop`,3,!1),i=A(!1),a=A(``);C(()=>{M(i,n.user.notification_settings?.pushover_enabled??!1,!0),M(a,n.user.notification_settings?.pushover_user_key??``,!0)}),Di(e,{section:`notifications`,get onUserUpdated(){return n.onUserUpdated},payload:()=>({notification_settings:{pushover_enabled:u(i),pushover_user_key:u(a)}}),children:(e,o)=>{var s=Bi(),c=k(L(s),2);Ii(c,{get user(){return n.user},get isDesktop(){return r()},get onChanged(){return n.onBrowserNotificationsChanged}});var l=k(c,4),d=k(L(l),2),f=L(d);O(f),t(d),t(l);var m=k(l,2),h=k(L(m),2),g=L(h);O(g),t(h),t(m),t(s),T(f,()=>u(i),e=>M(i,e)),se(g,()=>u(a),e=>M(a,e)),p(e,s)},$$slots:{default:!0}}),_()}var Hi=l(`

        Loading…

        `),Ui=l(`

        `),Wi=l(`
        You don't own any bots yet. Open a workspace's Bots & agents page to mint one.
        `),Gi=l(``),Ki=l(`
      • `),qi=l(`

          `),Ji=l(`
          `),Yi=l(`

          Account

          My bots

          Bots you own across your workspaces. Tokens live with the workspace where the bot was created.

          `,1);function Xi(e,r){o(r,!0);let i=A(ie([])),a=A(`loading`),s=A(``);ae(()=>{c()});async function c(){M(a,`loading`);try{M(i,await xt(),!0),M(a,`ready`)}catch(e){M(a,`error`),M(s,St(e),!0)}}function l(e){r.onClose(),fe(Fe(e.workspace.route_id||e.workspace.id,`bots`))}function h(e){return e.startsWith(`@`)?e:`@${e}`}function g(e){let t=e.trim().split(/\s+/).filter(Boolean);return t.length>=2?(t[0][0]+t[1][0]).toUpperCase():e.slice(0,2).toUpperCase()}let v=U(()=>{let e=new Map;for(let t of u(i)){let n=t.workspace.id,r=e.get(n);r?r.entries.push(t):e.set(n,{workspace:t.workspace,entries:[t]})}return[...e.values()].sort((e,t)=>e.workspace.name.localeCompare(t.workspace.name))});var y=Yi(),b=k(ce(y),2),x=e=>{var t=Hi();p(e,t)},S=e=>{var t=Ui(),n=D(t,!0);N(()=>d(n,u(s))),p(e,t)},C=e=>{var t=Wi();p(e,t)},w=e=>{var r=Ji();f(r,21,()=>u(v),e=>e.workspace.id,(e,r)=>{var i=qi(),a=L(i),o=L(a),s=D(o,!0),c=k(o,2);t(a);var _=k(a,2);f(_,21,()=>u(r).entries,e=>e.bot.id,(e,r)=>{var i=Ki(),a=L(i),o=L(a),s=e=>{var t=Gi();N(()=>B(t,`src`,u(r).bot.avatar_url)),p(e,t)},c=e=>{var t=m();N(e=>d(t,e),[()=>g(u(r).bot.display_name||u(r).bot.handle||`?`)]),p(e,t)};P(o,e=>{u(r).bot.avatar_url?e(s):e(c,-1)}),t(a);var f=k(a,2),_=L(f),v=D(_,!0),y=k(_,2),b=L(y),x=D(b,!0),S=k(b,4),C=D(S);t(y),t(f);var w=k(f,2);t(i),N(e=>{d(v,u(r).bot.display_name||u(r).bot.handle),d(x,e),d(C,`${u(r).active_token_count??``} active ${u(r).active_token_count===1?`token`:`tokens`}`)},[()=>h(u(r).bot.handle)]),n(`click`,w,()=>l(u(r))),p(e,i)}),t(_),t(i),N(()=>d(s,u(r).workspace.name)),n(`click`,c,()=>l(u(r).entries[0])),p(e,i)}),t(r),p(e,r)};P(b,e=>{u(a)===`loading`?e(x):u(a)===`error`?e(S,1):u(i).length===0?e(C,2):e(w,-1)}),p(e,y),_()}W([`click`]);function Zi(e,t){return t.includes(`password`)&&e.password_enrolled===!0}function Qi(e,t,n){return e?t?[...t].length<8?`New password must be at least 8 characters.`:t===n?``:`New passwords do not match.`:`Enter a new password.`:`Enter your current password.`}var $i=l(`

          `),ea=l(``),ta=l(`
          Change password

          Pick a new password for signing in. Your other devices are signed out.

          The password you signed in with.

          At least 8 characters. Longer is better than clever.

          Type it once more so a typo cannot lock you out.

          `);function na(e,n){o(n,!0);let r=A(``),i=A(``),a=A(``),s=A(``),c=A(!1),l=A(!1);async function f(){if(u(l))return;let e=Qi(u(r),u(i),u(a));if(e){M(s,e,!0),M(c,!0);return}M(l,!0),M(s,``),M(c,!1);try{await G(`/api/auth/password/change`,{method:`POST`,body:JSON.stringify({current_password:u(r),new_password:u(i)})}),M(r,``),M(i,``),M(a,``),M(s,`Password updated. Your other devices were signed out.`)}catch(e){M(s,xe(e,`Could not change your password`),!0),M(c,!0)}finally{M(l,!1)}}var m=ta(),h=k(L(m),2),g=L(h),y=k(L(g),2),b=L(y);O(b),t(y),t(g);var x=k(g,2),S=k(L(x),2),C=L(S);O(C),t(S),t(x);var T=k(x,2),E=k(L(T),2),j=L(E);O(j),t(E),t(T),t(h);var F=k(h,2),I=L(F),ee=e=>{var t=$i();let n;var r=D(t,!0);N(()=>{n=w(t,1,`settings-status`,null,n,{"is-error":u(c)}),d(r,u(s))}),p(e,t)},R=e=>{var t=ea();p(e,t)};P(I,e=>{u(s)?e(ee):e(R,-1)});var z=k(I,2),te=D(z,!0);t(F),t(m),N(()=>{z.disabled=u(l),d(te,u(l)?`Updating...`:`Update password`)}),v(`submit`,m,e=>{e.preventDefault(),f()}),se(b,()=>u(r),e=>M(r,e)),se(C,()=>u(i),e=>M(i,e)),se(j,()=>u(a),e=>M(a,e)),p(e,m),_()}var ra=l(``),ia=l(``),aa=l(`

          Account

          Appearance

          Changes apply instantly and follow your account on every device.

          Live preview — updates as you pick

          Color mode System follows your OS setting
          Board theme Palette for boards, accents, and highlights
          Message layout How agent activity attaches to replies
          Density Compact fits more messages on screen
          `,1);function oa(e,r){o(r,!0);let i=U(()=>r.user.display_name||r.user.handle||`You`),a=U(()=>(u(i)[0]??`Y`).toUpperCase()),s=A(ie(Se())),c=A(ie(Me())),l=A(ie(Pe())),m=A(ie(De()));C(()=>{r.user.appearance_preferences,M(s,Se(),!0),M(c,Me(),!0),M(l,Pe(),!0),M(m,De(),!0)});function h(e){M(s,e,!0),Ae(e)}function g(e){M(c,e,!0),we(e)}function v(e){M(l,e,!0),Te(e)}function y(e){M(m,e,!0),Oe(e)}function b(e,t,n,r){let i;switch(e.key){case`ArrowRight`:case`ArrowDown`:i=(n+1)%t;break;case`ArrowLeft`:case`ArrowUp`:i=(n-1+t)%t;break;case`Home`:i=0;break;case`End`:i=t-1;break;default:return}e.preventDefault(),r(i),(e.currentTarget.parentElement?.querySelectorAll(`[role="radio"]`))?.item(i).focus()}var x=aa(),S=k(ce(x),2),T=L(S),E=k(L(T),2),O=L(E),j=L(O),P=D(j,!0),F=k(j,2),I=L(F),R=L(I),z=D(R,!0);ee(2),t(I),ee(2),t(F),t(O);var te=k(O,4),ne=L(te),re=D(ne,!0),ae=k(ne,2),oe=L(ae),V=L(oe),se=D(V,!0);ee(2),t(oe),ee(2),t(ae),t(te),t(E),t(T);var le=k(T,4),H=L(le),ue=k(L(H),2);f(ue,23,()=>ke,e=>e.id,(e,t,r)=>{var i=ra();let a;var o=D(i,!0);N(()=>{a=w(i,1,`appearance-seg__btn`,null,a,{"is-active":u(s)===u(t).id}),B(i,`aria-checked`,u(s)===u(t).id),B(i,`tabindex`,u(s)===u(t).id?0:-1),d(o,u(t).label)}),n(`click`,i,()=>h(u(t).id)),n(`keydown`,i,e=>b(e,ke.length,u(r),e=>h(ke[e].id))),p(e,i)}),t(ue),t(H);var W=k(H,2),de=k(L(W),2),fe=L(de),pe=D(fe,!0),me=k(fe,2);f(me,23,()=>Ne,e=>e.id,(e,t,r)=>{var i=ia();let a;N(()=>{a=w(i,1,`board-chip`,null,a,{"is-active":u(c)===u(t).id}),B(i,`aria-checked`,u(c)===u(t).id),B(i,`tabindex`,u(c)===u(t).id?0:-1),B(i,`data-board`,u(t).id),B(i,`aria-label`,`${u(t).label} — ${u(t).blurb}`),B(i,`title`,`${u(t).label} — ${u(t).blurb}`)}),n(`click`,i,()=>g(u(t).id)),n(`keydown`,i,e=>b(e,Ne.length,u(r),e=>g(Ne[e].id))),p(e,i)}),t(me),t(de),t(W);var he=k(W,2),ge=k(L(he),2);f(ge,23,()=>Ee,e=>e.id,(e,t,r)=>{var i=ra();let a;var o=D(i,!0);N(()=>{a=w(i,1,`appearance-seg__btn`,null,a,{"is-active":u(l)===u(t).id}),B(i,`aria-checked`,u(l)===u(t).id),B(i,`tabindex`,u(l)===u(t).id?0:-1),B(i,`title`,u(t).blurb),d(o,u(t).label)}),n(`click`,i,()=>v(u(t).id)),n(`keydown`,i,e=>b(e,Ee.length,u(r),e=>v(Ee[e].id))),p(e,i)}),t(ge),t(he);var _e=k(he,2),ve=k(L(_e),2);f(ve,23,()=>je,e=>e.id,(e,t,r)=>{var i=ra();let a;var o=D(i,!0);N(()=>{a=w(i,1,`appearance-seg__btn`,null,a,{"is-active":u(m)===u(t).id}),B(i,`aria-checked`,u(m)===u(t).id),B(i,`tabindex`,u(m)===u(t).id?0:-1),B(i,`title`,u(t).blurb),d(o,u(t).label)}),n(`click`,i,()=>y(u(t).id)),n(`keydown`,i,e=>b(e,je.length,u(r),e=>y(je[e].id))),p(e,i)}),t(ve),t(_e),t(le),t(S),N(e=>{B(T,`data-layout`,u(l)),B(T,`data-density`,u(m)),d(P,u(a)),d(z,u(i)),d(re,u(a)),d(se,u(i)),d(pe,e)},[()=>Ne.find(e=>e.id===u(c))?.label]),p(e,x),_()}W([`click`,`keydown`]);var sa=l(` `,1),ca=l(` `,1),la=l(` `,1),ua=l(` `,1),da=l(`
        • `),fa=l(`
        • `),pa=l(`

            `),ma=l(`

            Loading...

            `),ha=l(`

            `),ga=l(`

            `),_a=l(`

            Account

            Profile settings

            How you appear across ClickClack.

            Sign out

            End this session on this device.

            `,1),va=l(`

            Account

            Notifications

            Decide when and how ClickClack should reach you.

            `,1),ya=l(``);function ba(e,r){o(r,!0);let i=S(r,`workspaces`,19,()=>[]),a=S(r,`initialSection`,3,Le),c=S(r,`isDesktop`,3,!1),l=A(!1),m=A(``),h=A(ie(Le)),g=U(()=>Zi(r.user,ge())),y=A(`loading`),b=A(``);C(()=>{M(h,a(),!0)}),C(()=>{u(h);let e=new AbortController;return T(e.signal),()=>e.abort()});async function x(){if(!u(l)){M(l,!0),M(m,``);try{await G(`/api/auth/logout`,{method:`POST`,body:JSON.stringify({})}),window.location.reload()}catch(e){M(m,xe(e,`Could not sign out. Try again.`),!0),M(l,!1)}}}async function T(e){M(y,`loading`),M(b,``);try{let t=await Ce({signal:e});e.throwIfAborted(),r.onUserUpdated(t.user),M(y,`ready`)}catch(t){if(e.aborted)return;if(t instanceof be&&(t.status===401||t.status===403)){M(y,`error`),M(b,`Sign in to manage your account`);return}M(y,`error`),M(b,t instanceof Error?t.message:`Could not load your account`,!0)}}function O(e){e.target===e.currentTarget&&r.onClose()}function j(e){if(e.key!==`Escape`)return;let t=e.target;t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable)||(e.preventDefault(),r.onClose())}function F(e,t){r.onClose(),fe(Fe(e.route_id||e.id,t))}var I=ya();v(`keydown`,E,j);var ee=L(I),R=L(ee),z=k(R,2),te=L(z),ne=k(L(te),2);f(ne,21,()=>Re,e=>e.id,(e,i)=>{var a=da(),o=L(a);let s;var c=L(o),l=e=>{var t=sa(),n=ce(t);Y(n,{class:`settings-modal__rail-avatar`,get id(){return r.user.id},get name(){return r.user.display_name},get src(){return r.user.avatar_url},size:18});var a=k(n,2),o=D(a,!0);N(()=>d(o,r.user.display_name||u(i).label)),p(e,t)},f=e=>{var t=ca(),n=k(ce(t),2),r=D(n,!0);N(()=>d(r,u(i).label)),p(e,t)},m=e=>{var t=la(),n=k(ce(t),2),r=D(n,!0);N(()=>d(r,u(i).label)),p(e,t)},g=e=>{var t=ua(),n=k(ce(t),2),r=D(n,!0);N(()=>d(r,u(i).label)),p(e,t)};P(c,e=>{u(i).id===`profile`?e(l):u(i).id===`appearance`?e(f,1):u(i).id===`notifications`?e(m,2):u(i).id===`bots`&&e(g,3)}),t(o),t(a),N(()=>{s=w(o,1,`settings-modal__rail-item`,null,s,{"is-active":u(h)===u(i).id}),B(o,`aria-current`,u(h)===u(i).id?`page`:void 0)}),n(`click`,o,()=>M(h,u(i).id,!0)),p(e,a)}),t(ne),t(te);var re=k(te,2);f(re,17,i,e=>e.id,(e,r)=>{var i=pa(),a=L(i),o=D(a),c=k(a,2);f(c,21,()=>Ie,e=>e.id,(e,i)=>{var a=s(),o=ce(a),c=e=>{var a=fa(),o=L(a),s=k(L(o),2),c=D(s,!0);t(o),t(a),N(()=>d(c,u(i).label)),n(`click`,o,()=>F(u(r),u(i).slug)),p(e,a)},l=U(()=>!u(i).managersOnly||ze(u(r).role));P(o,e=>{u(l)&&e(c)}),p(e,a)}),t(c),t(i),N(()=>{B(a,`title`,u(r).name),d(o,`Workspace · ${u(r).name??``}`)}),p(e,i)}),t(z);var ae=k(z,2),oe=L(ae),V=e=>{var t=ma();p(e,t)},se=e=>{var t=ha(),n=D(t,!0);N(()=>d(n,u(b))),p(e,t)},le=e=>{var i=_a(),a=k(ce(i),2);zi(a,{get user(){return r.user},get hideCommentary(){return r.hideCommentary},get hideToolCalls(){return r.hideToolCalls},get userAlign(){return r.userAlign},get otherAlign(){return r.otherAlign},get isDesktop(){return c()},get onUserUpdated(){return r.onUserUpdated},get onSaved(){return r.onClose},get onHideCommentary(){return r.onHideCommentary},get onHideToolCalls(){return r.onHideToolCalls},get onUserAlign(){return r.onUserAlign},get onOtherAlign(){return r.onOtherAlign},get onBrowserNotificationsChanged(){return r.onBrowserNotificationsChanged}});var o=k(a,2),s=e=>{na(e,{})};P(o,e=>{u(g)&&e(s)});var f=k(o,2),h=L(f),_=k(L(h),4),v=e=>{var t=ga(),n=D(t,!0);N(()=>d(n,u(m))),p(e,t)};P(_,e=>{u(m)&&e(v)}),t(h);var y=k(h,2),b=L(y),S=D(b,!0);t(y),t(f),N(()=>{b.disabled=u(l),d(S,u(l)?`Signing out...`:`Sign out`)}),n(`click`,b,x),p(e,i)},H=e=>{oa(e,{get user(){return r.user}})},ue=e=>{var t=va();Vi(k(ce(t),2),{get user(){return r.user},get isDesktop(){return c()},get onUserUpdated(){return r.onUserUpdated},get onBrowserNotificationsChanged(){return r.onBrowserNotificationsChanged}}),p(e,t)},W=e=>{Xi(e,{get onClose(){return r.onClose}})};P(oe,e=>{u(y)===`loading`?e(V):u(y)===`error`?e(se,1):u(h)===`profile`?e(le,2):u(h)===`appearance`?e(H,3):u(h)===`notifications`?e(ue,4):u(h)===`bots`&&e(W,5)}),t(ae),t(ee),t(I),n(`click`,I,O),n(`click`,R,function(...e){r.onClose?.apply(this,e)}),p(e,I),_()}W([`click`]);var xa=l(`
            No thread open Hover any message and tap the bubble to keep side conversations tidy.
            `);function Sa(e){var t=xa();p(e,t)}var Ca=l(``),wa=l(`

            `,1),Ta=l(``),Ea=l(``),Da=l(``),Oa=l(``),ka=l(``),Aa=l(``),ja=l(``),Ma=l(`
            `),Na=l(`Connecting…`),Pa=l(`
            `);function Fa(e,r){o(r,!0);function i(e){return e===`muted`?`Channel muted - click to change`:e===`mentions`?`Notifications for @mentions only - click to change`:`All notifications enabled - click to change`}let a=S(r,`channelNotifPreference`,3,void 0),s=S(r,`channelNotifSaving`,3,!1),c=S(r,`channelSettingsAvailable`,3,!1),l=S(r,`pinsAvailable`,3,!1),f=S(r,`pinnedOpen`,3,!1),m=S(r,`onOpenChannelSettings`,3,()=>{}),h=S(r,`onToggleChannelNotifications`,3,()=>{}),g=U(()=>Q(r.externalURL));var y=Pa(),b=L(y),x=L(b),C=L(x),T=L(C),E=k(L(T),2);t(T),t(C);var A=k(C,2),M=D(A,!0),F=k(A,2),I=e=>{var t=wa(),n=k(ce(t),2),i=D(n,!0),a=k(n,2),o=e=>{var t=Ca();N(()=>B(t,`href`,u(g))),p(e,t)};P(a,e=>{u(g)&&e(o)}),N(()=>{B(n,`title`,r.channelTitle),d(i,r.channelTitle)}),p(e,t)};P(F,e=>{r.channelTitle&&e(I)}),t(x);var R=k(x,2),z=k(L(R),2);O(z);var te=k(z,2),ne=e=>{var t=Ta();n(`click`,t,function(...e){r.onResetSearch?.apply(this,e)}),p(e,t)};P(te,e=>{r.searchQuery&&e(ne)}),ee(2),t(R);var re=k(R,2),ie=e=>{var o=Ma(),u=L(o),d=e=>{var r=ka(),o=L(r),c=e=>{var t=Ea();p(e,t)},l=e=>{var t=Da();p(e,t)},u=e=>{var t=Oa();p(e,t)};P(o,e=>{a()===`muted`?e(c):a()===`mentions`?e(l,1):e(u,-1)}),t(r),N((e,t)=>{B(r,`title`,e),B(r,`aria-label`,t),B(r,`aria-busy`,s()),r.disabled=s()},[()=>i(a()),()=>i(a())]),n(`click`,r,function(...e){h()?.apply(this,e)}),p(e,r)};P(u,e=>{a()&&e(d)});var g=k(u,2),_=e=>{var t=Aa();let i;N(()=>{B(t,`title`,f()?`Close pinned items`:`Pinned items`),B(t,`aria-label`,f()?`Close pinned items`:`Pinned items`),i=w(t,1,``,null,i,{active:f()})}),n(`click`,t,function(...e){r.onPinnedItems?.apply(this,e)}),p(e,t)};P(g,e=>{l()&&e(_)});var v=k(g,2),y=e=>{var t=ja();n(`click`,t,function(...e){m()?.apply(this,e)}),p(e,t)};P(v,e=>{c()&&e(y)}),t(o),p(e,o)};P(re,e=>{(a()||l()||c())&&e(ie)});var ae=k(re,2),oe=e=>{var t=Na();p(e,t)};P(ae,e=>{r.connected||e(oe)}),t(b),t(y),N(()=>{B(y,`data-platform`,r.platform),B(C,`aria-label`,r.mobileNavigation?r.mobileNavOpen?`Close navigation`:`Open navigation`:r.sidebarCollapsed?`Expand sidebar`:`Collapse sidebar`),B(C,`title`,r.mobileNavigation?r.mobileNavOpen?`Close navigation`:`Open navigation`:r.sidebarCollapsed?`Expand sidebar`:`Collapse sidebar`),B(E,`d`,r.mobileNavigation?r.mobileNavOpen?`m15 9-3 3 3 3`:`m9 9 3 3-3 3`:r.sidebarCollapsed?`m13 9 3 3-3 3`:`m16 9-3 3 3 3`),d(M,r.workspaceName||`ClickClack`),j(z,r.searchQuery)}),n(`click`,C,function(...e){r.onToggleSidebar?.apply(this,e)}),n(`click`,A,function(...e){r.onOpenWorkspaceSettings?.apply(this,e)}),v(`submit`,R,e=>{e.preventDefault(),r.onSearch()}),n(`input`,z,e=>r.onSearchQuery(e.currentTarget.value)),p(e,y),_()}W([`click`,`input`]);var Ia=l(`

            `),La=l(``),Ra=l(``),za=l(``),Ba=l(``),Va=l(`

            `,1),Ha=l(`

            ClickClack

            `),Ua=l(``),Wa=l(``),Ga=l(``),Ka=l(``),qa=l(`

            `);function Ja(e,r){o(r,!0);function i(e){return e===`muted`?`Channel muted - click to change`:e===`mentions`?`Notifications for @mentions only - click to change`:`All notifications enabled - click to change`}let a=S(r,`pinnedOpen`,3,!1),s=S(r,`channelNotifPreference`,3,void 0),c=S(r,`channelNotifSaving`,3,!1),l=S(r,`channelSettingsAvailable`,3,!1),f=S(r,`onOpenChannelSettings`,3,()=>{}),m=S(r,`onToggleChannelNotifications`,3,()=>{}),h=U(()=>r.selectedDirect?void 0:Q(r.selectedChannel?.external_url));var g=qa(),y=L(g),b=L(y),x=e=>{var t=Ia(),n=D(t,!0);N(e=>d(n,e),[()=>`@${ct(r.selectedDirect,r.currentUserID)}`]),p(e,t)},C=e=>{var a=Va(),o=ce(a),l=D(o,!0),u=k(o,2),f=e=>{var r=Ba(),a=L(r),o=e=>{var t=La();p(e,t)},l=e=>{var t=Ra();p(e,t)},u=e=>{var t=za();p(e,t)};P(a,e=>{s()===`muted`?e(o):s()===`mentions`?e(l,1):e(u,-1)}),t(r),N((e,t)=>{B(r,`title`,e),B(r,`aria-label`,t),B(r,`aria-busy`,c()),r.disabled=c()},[()=>i(s()),()=>i(s())]),n(`click`,r,function(...e){m()?.apply(this,e)}),p(e,r)};P(u,e=>{s()&&e(f)}),N(e=>d(l,e),[()=>`#${_t(r.selectedChannel)}`]),p(e,a)},T=e=>{var t=Ha();p(e,t)};P(b,e=>{r.selectedDirect?e(x):r.selectedChannel?e(C,1):e(T,-1)});var E=k(b,4),A=D(E,!0);t(y);var M=k(y,2),F=k(L(M),2);O(F);var I=k(F,2),R=e=>{var t=Ua();n(`click`,t,function(...e){r.onResetSearch?.apply(this,e)}),p(e,t)};P(I,e=>{r.searchQuery&&e(R)}),ee(2),t(M);var z=k(M,2),te=L(z),ne=e=>{var t=Wa();N(()=>B(t,`href`,u(h))),p(e,t)};P(te,e=>{u(h)&&e(ne)});var re=k(te,2);let ie;var ae=k(re,2),oe=e=>{var t=Ga();let i;N(()=>{B(t,`title`,a()?`Close pinned items`:`Pinned items`),B(t,`aria-label`,a()?`Close pinned items`:`Pinned items`),i=w(t,1,``,null,i,{active:a()})}),n(`click`,t,function(...e){r.onPinnedItems?.apply(this,e)}),p(e,t)};P(ae,e=>{r.selectedChannel&&e(oe)});var V=k(ae,2),se=e=>{var t=Ka();n(`click`,t,function(...e){f()?.apply(this,e)}),p(e,t)};P(V,e=>{r.selectedChannel&&l()&&e(se)}),t(z),t(g),N(()=>{d(A,r.workspaceName||`no workspace`),j(F,r.searchQuery),B(re,`title`,r.threadOpen?`Close thread`:`Open a message thread`),B(re,`aria-label`,r.threadOpen?`Close thread`:`Open a message thread`),ie=w(re,1,``,null,ie,{active:r.threadOpen})}),v(`submit`,M,e=>{e.preventDefault(),r.onSearch()}),n(`input`,F,e=>r.onSearchQuery(e.currentTarget.value)),n(`click`,re,function(...e){r.onToggleThread?.apply(this,e)}),p(e,g),_()}W([`click`,`input`]);function Ya(e,t){return`${e}\u0000${t}`}function Xa(e,t,n){let r=t.find(t=>t.bot.id===e)?.bot??n(e);return r?.display_name?.trim()||(r?.handle?`@${r.handle}`:``)}function Za(e,t,n){let r=new Set,i=[];for(let a of e){if(!a.lines.some(e=>!e.finalized)||a.userId&&r.has(a.userId))continue;a.userId&&r.add(a.userId);let e=Xa(a.userId,t,n);e&&i.push(e)}return i}async function Qa(e){return(await G(`/api/workspaces/${e}/bot-commands`)).bot_commands??[]}function $a(e){let t=e.trim().toLowerCase();return t?t.startsWith(`/`)?t:`/${t}`:``}function eo(e){let t=/^(\/\S+)\s*([\s\S]*)$/.exec(e);return t?{command:$a(t[1]),text:t[2].trim()}:null}function to(e,t){return e.find(e=>!e.revoked_at&&$a(e.command)===t)}async function no(e,t,n){let r=new URLSearchParams;r.set(`command`,t),r.set(`text`,n);let i=await fetch(he(`/api/hooks/slash/${e}`),ye({method:`POST`,credentials:`include`,headers:{Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`,"X-ClickClack-CSRF":`1`},body:r.toString()})),a=await i.text();if(!i.ok)throw new be(i.status,a);let o=a?JSON.parse(a):{};return{response_type:o.response_type||`in_channel`,text:(o.text||``).trim()}}var ro=e({default:()=>Do}),io=l(``),ao=l(``),oo=l(`
            `),so=l(`

            or

            `),co=l(` `,1),lo=l(``),uo=l(``),fo=l(`

            `),po=l(`
            ClickClack OpenClaw workspace chat

            Welcome.

            Have a sign-in token?
            `,1),mo=l(``),ho=l(``),go=l(`
            Showing topic
            `),_o=l(`

            `),vo=l(`
            `),yo=l(``),bo=l(``),xo=l(``),So=l(` `,1),Co=l(`

            Loading thread…

            `),wo=l(`
            Thread
            `,1),To=l(``),Eo=l(`
            `,1);function Do(e,i){o(i,!1);let a=()=>g(xt,`$threadView`,l),[l,h]=ue(),C=z(),T=z(),A=z(),j=z(),F=z(),I=z(),R=z(),ie=z(),U=z(),W=z(),me=z(),ye=z(),Se=z(),we=z(),Te=z(),Ee=z(),De=z(),Oe=z(),ke=z(),Ae=z(),je=z(),Me=z(),Ne=z(),Pe=z(),Ie=`clickclack:hide-commentary:v1`,Le=`clickclack:hide-tool-calls:v1`,Re=`clickclack:user-align:v1`,ze=`clickclack:other-align:v1`,Be=Date.now(),We=jt?.integratedTitleBar===!0,Ke=z(Tt),Je=S(i,`routeWorkspaceID`,8,``),Ye=S(i,`routeTargetID`,8,``),K=z(null),Ze=new it(()=>u(K)?.id||``),et=new Ve(Ts),nt=z([]),q=z([]),rt=z([]),ot=z(null),lt=new Map,dt=new Map,ft=z(!1),J=z([]),pt=z([]),Y=z(``),X=z(``),Z=z(``),Q=new yt(()=>`${u(Y)}:${$()}`,js),xt=de(()=>({root:Q.root,selection:Q.selection,replies:Q.replies,state:Q.state,draft:Q.draft,error:Q.error})),St=z(``),Et=z(``),Dt=0,Ot=``,Nt=new Map,Pt=z(null),Ft=z(!1),It=z([]),Lt=z(!1),Rt=z(``),zt=z(new Set),Bt=0,Vt=z([]),Ht=z([]),Wt=z([]),Gt=z([]),Kt=z(null),Jt=z([]),Yt=z(``),Xt=z(null),Zt=z(null),Qt=z(``),en=z(null),tn=z(null),nn=z(null),rn=new Set,an=z(``),on=z(``),cn=z(``),un=z(``),dn=z(null),fn=z(``),pn=z(``),mn=z(``),hn=0,gn=z(``),_n=z(null),vn=z(!1),yn=0,bn=0,xn=z(null),Sn=z(``),Cn=null,wn=z(!1),Tn=z(`profile`),En=z(!1),Dn=z(!1),On=z(``),kn=z(!1),An=z(!1),jn=z(!1),Mn=z(!1),Nn=z(!1),Pn=z(`left`),Fn=z(`left`),In=z(!1),Ln=z(!1),Rn=z(``),zn=ge(),Bn=zn.includes(`github`),Vn=zn.includes(`password`),Hn=z(``),Un=z(``),Gn=z(``),Kn=z(!1),Yn=z(``),Qn=Vn?Bn?`Sign in with your ClickClack account, or continue with GitHub.`:`Sign in with your ClickClack account.`:Bn?`Sign in with GitHub to join the guest room.`:`Sign in with a token from your ClickClack administrator.`,$n=Bn&&!Vn?`Any GitHub account can join.`:``,er=z(!1),nr=z(``),rr=``,ar=``,or=null,sr=z(null),cr=new Map,lr=z(new Map),dr=new mt(()=>[u(K)?.id,u(Y),$()].join(`:`)),fr=new Set,pr=z(`idle`),mr=`idle`,hr=!1,gr=!1,_r=z(!1),yr=z(!1),br=z(!1),xr=z(!1),Sr=new Map,Cr=0,wr=z(``),Tr=z(void 0),Er=z(``),Dr=z(!0),Or=z(!1),kr=z(!1),Ar=z(!1),jr=z(!1),Mr=z(null),Nr=z(null),Pr=z(null),Fr=z(null),Ir=z(`message`),Lr=z([]),Rr,zr=z([]),Br,Vr=z(Date.now()),Hr,Ur=``,Gr=0,Kr=0,qr=0,Jr=0,Yr=0,Xr=0,Zr=0,Qr=0,$r=null,ti=z(``),ni=0,ri=0,ii=0,ai=0,oi=0,si=z(null),ci,li=z(new Set),ui=z(null),di=z(``);function fi(e){e!==Ot&&(Ot=e,M(St,``),pi(``))}function pi(e){e!==u(Et)&&(M(Et,e),Dt+=1)}function mi(){return`${u(Y)}:${$()}:${u(Et)}:${Dt}:${Kr}`}function hi(e,t){return t?e.filter(e=>!e.archived_at&&(!e.channel_id||e.channel_id===t)):[]}pe(()=>{jt?.setActiveRoute(`${window.location.pathname}${window.location.search}${window.location.hash}`)}),ae(()=>{Si(),At(e=>G(e)).then(e=>{M(Ke,e)}),Hr=window.setInterval(()=>{M(Vr,Date.now())},3e4),Ii(),ki();let e=window.matchMedia(`(max-width: 820px)`),t=()=>{M(Ar,!1),M(jr,e.matches)};t();let n=jt?.onNavigate(e=>{fe(e,{keepFocus:!0,noScroll:!0})}),r=jt?.onQuickCompose(()=>gi());return e.addEventListener(`change`,t),()=>{e.removeEventListener(`change`,t),n?.(),r?.()}});function gi(){y().then(()=>{(u(Ir)===`thread`?u(Fr):u(Pr))?.focus()})}async function vi(e){if(jt){e.preventDefault(),M(Rn,`Opening GitHub in your browser…`);try{await jt.signInWithGitHub(),M(Rn,`Finish signing in in your browser. ClickClack will complete here automatically.`)}catch{M(Rn,`Could not open your browser. Try again.`)}}}async function yi(e,t){if(!u(Kn)){M(Kn,!0),M(Yn,``);try{await G(e,{method:`POST`,body:JSON.stringify(t)}),window.location.reload()}catch(e){M(Yn,xe(e,`Could not sign in.`)),M(Kn,!1)}}}function bi(e){e.preventDefault(),yi(`/api/auth/password/login`,{identifier:u(Hn),password:u(Un)})}function xi(e){e.preventDefault(),yi(`/api/auth/magic/consume`,{token:u(Gn)})}function Si(){try{let e=window.localStorage.getItem(`clickclack:show-agent-activity:v1`)===`0`;M(Mn,window.localStorage.getItem(Ie)===`1`||e),M(Nn,window.localStorage.getItem(Le)===`1`||e),M(Pn,window.localStorage.getItem(Re)===`right`?`right`:`left`),M(Fn,window.localStorage.getItem(ze)===`right`?`right`:`left`)}catch{M(Mn,!1),M(Nn,!1),M(Pn,`left`),M(Fn,`left`)}wi()}function wi(){try{document.documentElement.setAttribute(`data-user-align`,u(Pn)),document.documentElement.setAttribute(`data-other-align`,u(Fn))}catch{}}function Ti(e){M(Pn,e),wi();try{window.localStorage.setItem(Re,e)}catch{}}function Ei(e){M(Fn,e),wi();try{window.localStorage.setItem(ze,e)}catch{}}function Di(e){M(Mn,e);try{window.localStorage.setItem(Ie,e?`1`:`0`)}catch{}}function Oi(e){M(Nn,e);try{window.localStorage.setItem(Le,e?`1`:`0`)}catch{}}te(()=>{$s(),Q.close(),Gr+=1,Kr+=1,dr.clear(),Qr+=1,$r?.abort(),or?.close(),or=null,M(er,!1),ln(),Rr&&window.clearInterval(Rr),Br&&window.clearInterval(Br),Hr&&window.clearInterval(Hr),ci&&clearTimeout(ci),Oc(!1,null)});async function ki(){try{let e=await Ce();M(K,e.user),Ii(),await Bi(),M(In,!0)}catch(e){Ai(e)}}function Ai(e){if(e instanceof be&&(e.status===401||e.status===403)){or?.close(),or=null,M(wn,!1),M(Ln,!0),M(In,!1);return}M(Kt,{kind:`error`,text:xe(e,`Could not load ClickClack`)})}function ji(){u(K)&&(M(Tn,`profile`),M(wn,!0))}function Mi(){let e=u(T)?.route_id||u(Y)||Je();e&&fe(Fe(e))}function Ni(){u(R)&&(M(On,``),M(En,!0))}async function Pi(e){let t=u(I);if(!(!t||!u(R)||u(Dn))){M(Dn,!0),M(On,``);try{let n=await G(`/api/channels/${t.id}`,{method:`PATCH`,body:JSON.stringify({archived:e})});M(q,u(q).map(e=>e.id===n.channel.id?n.channel:e)),M(En,!1)}catch(t){M(On,xe(t,e?`Could not archive channel`:`Could not restore channel`))}finally{M(Dn,!1)}}}function Fi(e){M(K,e),ls(e),Q.updateAuthor(e)}function Ii(){if(jt){M(jn,Ri());return}let e=Ri();M(jn,typeof Notification<`u`&&Notification.permission===`granted`&&e),e&&!u(jn)&&zi(!1)}function Li(){return u(K)?.id?`clickclack:browser-notifications-enabled:v1:${u(K).id}`:``}function Ri(){let e=Li();if(!e)return!1;try{return window.localStorage.getItem(e)===`enabled`}catch{return!1}}function zi(e){let t=Li();if(!t)return!1;try{return e?window.localStorage.setItem(t,`enabled`):window.localStorage.removeItem(t),!0}catch{return!1}}async function Bi(){let e=++qr,t=await G(`/api/workspaces`);e===qr&&M(nt,t.workspaces)}function Vi(e=``,t=``){return`${e||``}/${t||``}`}function Hi(e=u(Y),t=``){let n=Gi(e);if(!n)return`/app`;let r=`/app/${encodeURIComponent(n)}`,i=Ki(t);return i?`${r}/${encodeURIComponent(i)}`:r}async function Ui(e){if(!e.channel_id||e.parent_message_id)throw Error(`Only channel roots have links`);let t=await G(`/api/messages/${e.id}/route`,{method:`POST`});if(!t.message.route_id)throw Error(`Message route was not allocated`);cs({id:t.message.id,route_id:t.message.route_id});let n=Gi(t.message.workspace_id);if(!n)throw Error(`Workspace route is unavailable`);let r=`/app/${encodeURIComponent(n)}/${encodeURIComponent(t.message.route_id)}`;return new URL(r,`${ve()}/`).toString()}function Wi(e){let t=u(q).find(t=>t.id===e)?.route_id||u(J).find(t=>t.id===e)?.route_id;return t?Hi(u(Y),t):!u(Y)||!e?`/app`:`/app/${encodeURIComponent(u(Y))}/${encodeURIComponent(e)}`}function Gi(e=u(Y)){return e?u(nt).find(t=>t.id===e||t.route_id===e)?.route_id||e:``}function Ki(e=``){return e?u(q).find(t=>t.id===e||t.route_id===e)?.route_id||u(J).find(t=>t.id===e||t.route_id===e)?.route_id||Q.root?.id===e&&Q.root.route_id||u(pt).find(t=>t.id===e)?.route_id||e:``}async function qi(e=u(Y),t=``,n=!1){let r=Hi(e,t);window.location.pathname!==r&&await fe(r,{replaceState:n,noScroll:!0,keepFocus:!0})}function Ji(e,t){Vi(e,t)!==Ur&&ia(e,t)}function Yi(){Gr++,Ur=Vi(Gi(),Ki($())),qi(u(Y),$())}function Xi(){u(vn)&&qs(),Q.close(),M(Pt,null),M(Ft,!1),M(Ir,`message`),M(Ar,!1)}function Zi(e=u(Y)){return ta(e)||u(q).find(e=>e.name.toLowerCase()===`guest`)?.id||u(q)[0]?.id||u(J)[0]?.id||``}function Qi(e=u(Y)){return u(nt).find(t=>t.id===e||t.route_id===e)}function $i(e=u(Y)){let t=Qi(e),n=t?.route_id||t?.id||e;return n?`clickclack:last-channel:v1:${n}`:``}function ea(e){try{let t=JSON.parse(e);return{id:typeof t.id==`string`?t.id:``,routeID:typeof t.routeID==`string`?t.routeID:``}}catch{return{id:e}}}function ta(e=u(Y)){let t=$i(e);if(!t)return``;let n;try{let e=window.localStorage.getItem(t);if(!e)return``;n=ea(e)}catch{return``}let r=u(q).find(e=>e.id===n.id||e.route_id===n.routeID);if(r)return r.id;try{window.localStorage.removeItem(t)}catch{}return``}function na(e,t){if(!e||!t)return;let n=u(q).find(e=>e.id===t);if(!n)return;let r=$i(e);if(r)try{window.localStorage.setItem(r,JSON.stringify({id:n.id,routeID:n.route_id}))}catch{}}function ra(e){ar===e&&(ar=``,lc())}async function ia(e=``,t=``){let n=++Gr;Ur=Vi(e,t),t!==Q.selection?.messageID&&t!==Q.root?.route_id&&Q.close();try{Ze.clear();let r=t.trim()?await oa(e,t):null;if(n!==Gr)return;let i=r?u(nt).find(e=>e.id===r.workspace_id):u(nt).find(t=>t.id===e||t.route_id===e)||u(nt)[0];if(!i){Ra(``,{messages:[],oldest_seq:0,newest_seq:0,has_older:!1,has_newer:!1},`replace`);return}let a=u(Y)!==i.id;if(a&&(os(),et.clear(),dr.clear(),ca(),M(Y,i.id),Yr+=1,ni+=1,ri+=1,Qr+=1,$r?.abort(),M(ti,``),M(Wt,[]),M(Gt,[]),M(rt,[]),M(Ht,[]),M(X,``),M(Z,``),Q.close(),M(Pt,null),M(Ir,`message`),qs(),Ga(),M(Dr,!0),ar=i.id),(a||u(q).length===0)&&await ma(!1,!1),n!==Gr||((a||u(J).length===0)&&await tc(),a&&(await Promise.all([_a(),ya(i.id),xa(i.id),ha(i.id)]),va(i.id)),n!==Gr))return;if(r){let e=await aa(r,n);if(n!==Gr)return;if(!e){Xi(),await qi(i.id,Zi(),!0);return}}if(r?.canonical_path&&window.location.pathname!==r.canonical_path&&(Ur=Vi(r.workspace_route_id,r.target_route_id),await fe(r.canonical_path,{replaceState:!0,noScroll:!0,keepFocus:!0}),n!==Gr))return;if(r?.target_type===`channel`&&u(q).some(e=>e.id===r.target_id)){let e=r.target_id,t=!a&&u(X)===e&&!u(Z)&&u(wr)===e;if(M(X,e),M(Z,``),na(i.id,e),Xi(),t){Ha(e),ra(i.id);return}if(fi(e),await Promise.all([ja(),Nc()]),n!==Gr)return;ra(i.id);return}if(r?.target_type===`direct`&&u(J).some(e=>e.id===r.target_id)){let e=r.target_id,t=!a&&u(Z)===e&&!u(X)&&u(wr)===e;if(M(Z,e),M(X,``),Xi(),t){Ha(e),ra(i.id);return}if(fi(e),await ja(),n!==Gr)return;ra(i.id);return}if(r?.target_type===`thread`){let e=await sa(r,n);if(n!==Gr)return;e&&ra(i.id);return}let o=Zi();if(Xi(),!o){M(X,``),M(Z,``),fi(``),await ja(),(e!==i.route_id||t)&&await qi(i.id,``,!0),ra(i.id);return}await qi(i.id,o,!0)}catch(e){n===Gr&&Ai(e)}}async function aa(e,t){return e.target_type===`channel`?(u(q).some(t=>t.id===e.target_id)||await ma(!1,!1,!1),t===Gr&&u(q).some(t=>t.id===e.target_id)):e.target_type===`direct`?(u(J).some(t=>t.id===e.target_id)||(await tc(),u(J).some(t=>t.id===e.target_id)||nc((await G(`/api/dms/${e.target_id}`)).conversation)),t===Gr&&u(J).some(t=>t.id===e.target_id)):e.parent_type===`channel`&&e.parent_id?(u(q).some(t=>t.id===e.parent_id)||await ma(!1,!1,!1),t===Gr&&u(q).some(t=>t.id===e.parent_id)):e.parent_type===`direct`&&e.parent_id?(u(J).some(t=>t.id===e.parent_id)||(await tc(),u(J).some(t=>t.id===e.parent_id)||nc((await G(`/api/dms/${e.parent_id}`)).conversation)),t===Gr&&u(J).some(t=>t.id===e.parent_id)):!0}async function oa(e,t){try{return(await G(`/api/routes/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)).route}catch(e){if(e instanceof be&&(e.status===403||e.status===404))return null;throw e}}async function sa(e,t){if(e.workspace_id!==u(Y))return!1;let n=e.parent_type===`channel`&&e.parent_id||``,r=e.parent_type===`direct`&&e.parent_id||``;if(n){if(!u(q).some(e=>e.id===n))return!1;M(X,n),M(Z,``),na(e.workspace_id,n)}else if(r){if(!u(J).some(e=>e.id===r))return!1;M(Z,r),M(X,``)}else return!1;dr.prune();let i=Q.root?.id===e.target_id&&u(wr)===$();if(M(Pt,null),M(Ft,!1),M(Ir,`thread`),M(Ar,!1),!await As(e.target_id,void 0,()=>t===Gr))return!1;let a=Q.selection;if(n&&await Nc(),!Q.isCurrent(a)||t!==Gr)return!1;if(!i&&n&&Q.root&&(Q.root.thread_state?.reply_count??0)===0){let e=Q.root;return Q.close(),M(Ir,`message`),await Zs(e),!0}return!i&&Q.root&&await Zs(Q.root),!0}function ca(){hn++,M(dn,null),M(fn,``),M(pn,``),M(mn,``),M(Or,!1),M(kn,!1),M(An,!1)}function la(){let e=!u(Or);ca(),M(Or,e)}function ua(){ca(),M(kn,!0)}function da(){ca(),M(An,!0),va()}async function fa(){if(u(dn)===`workspace`||!u(on).trim())return;let e=u(Y),t=Gr,n=++hn,r=()=>n===hn&&t===Gr&&e===u(Y);M(dn,`workspace`),M(fn,``);try{let e=await G(`/api/workspaces`,{method:`POST`,body:JSON.stringify({name:u(on)})});if(u(nt).some(t=>t.id===e.workspace.id)||M(nt,[...u(nt),e.workspace]),!r())return;M(on,``),M(Or,!1),M(Ar,!1),await qi(e.workspace.id)}catch(e){r()&&M(fn,xe(e,`Could not create workspace`))}finally{n===hn&&M(dn,null)}}async function pa(e){M(Ar,!1),await qi(e)}async function ma(e=!0,t=!0,n=!0){let r=u(Y);if(!r)return;let i=++Jr,a=await G(`/api/workspaces/${r}/channels`);i===Jr&&r===u(Y)&&(M(q,a.channels),t?M(X,u(q).find(e=>e.id===u(X))?.id||u(q).find(e=>!e.archived_at)?.id||u(q)[0]?.id||``):u(X)&&!u(q).some(e=>e.id===u(X))&&M(X,``),n&&(u(vn)&&qs(),Q.close(),M(Pt,null),M(Ir,`message`)),e&&await ja())}async function ha(e=u(Y)){let t=++Yr,n=$(),r=u(X),i=!1;if(!e){M(rt,[]);return}try{let a=await G(`/api/workspaces/${e}/topics`);if(t!==Yr||e!==u(Y)||(M(rt,a.topics),$()!==n||u(X)!==r))return;let o=new Set(hi(a.topics,r).map(e=>e.id));u(St)&&!o.has(u(St))&&M(St,``),u(Et)&&!o.has(u(Et))&&(pi(``),cr.delete($()),u(lr).delete($()),i=!0)}catch{return}if(!(!i||$()!==n))try{await Ma()}catch(e){if($()!==n||u(Et))return;us(),M(Kt,{kind:`error`,text:e instanceof Error?`Topic changed, but messages could not reload: ${e.message}`:`Topic changed, but messages could not reload`})}}function ga(){M(Ir,`message`),u(X)&&ha()}async function _a(e=u(Y)){let t=++Zr;if(!e||e!==u(Y)||u(A)!==`owner`&&u(A)!==`moderator`){t===Zr&&M(Vt,[]);return}try{let n=await G(`/api/workspaces/${e}/moderation/members`);if(t!==Zr||e!==u(Y))return;M(Vt,n.members)}catch{t===Zr&&e===u(Y)&&M(Vt,[])}}async function va(e=u(Y)){let t=++Qr;$r?.abort();let n=new AbortController;if($r=n,M(ti,``),!e){M(Ht,[]);return}try{let r=await wt({workspaceID:e,limit:100,signal:n.signal});if(t!==Qr||e!==u(Y))return;M(Ht,r.map(e=>e.user))}catch(r){!n.signal.aborted&&t===Qr&&e===u(Y)&&(M(Ht,[]),M(ti,Ct(r)))}}async function ya(e=u(Y)){let t=++ni;if(!e){M(Wt,[]);return}try{let n=await G(`/api/workspaces/${e}/slash-commands`);if(t!==ni||e!==u(Y))return;M(Wt,n.slash_commands)}catch{t===ni&&e===u(Y)&&M(Wt,[])}}async function xa(e=u(Y),t=!1){let n=++ri;if(!e){M(Gt,[]);return}try{let t=await Qa(e);if(n!==ri||e!==u(Y))return;M(Gt,t)}catch(r){let i=n===ri&&e===u(Y);if(i&&M(Gt,[]),t&&i)throw r}}function Ca(e){oi+=1,M(Kt,null)}async function wa(e,t){if(!u(Y))return;let n=await G(`/api/workspaces/${u(Y)}/moderation/members/${e}`,{method:`PATCH`,body:JSON.stringify(t)});M(Vt,[...u(Vt).filter(t=>t.user.id!==e),n.member]),await ma(!1,!1,!1)}async function Ta(){if(u(dn)===`channel`||!u(Y)||!u(cn).trim())return;let e=u(Y),t=Gr,n=++hn,r=()=>n===hn&&t===Gr&&e===u(Y);M(dn,`channel`),M(pn,``);try{let t=await G(`/api/workspaces/${e}/channels`,{method:`POST`,body:JSON.stringify({name:u(cn),kind:`public`})});if(e===u(Y)&&!u(q).some(e=>e.id===t.channel.id)&&M(q,[...u(q),t.channel]),!r())return;M(cn,``),M(kn,!1),await qi(e,t.channel.id)}catch(e){r()&&M(pn,xe(e,`Could not create channel`))}finally{n===hn&&M(dn,null)}}async function Ea(e){M(Ar,!1),na(u(Y),e);let t=Hi(u(Y),e);e===u(X)&&!u(Z)&&window.location.pathname===t||await qi(u(Y),e)}async function Da(e,t){let n=++ii;if(M(ot,null),!(!e||t))try{let t=await G(`/api/channels/${e}/notification-settings`);if(n!==ii||e!==u(X)||u(Z))return;Qo(e,t.preference),M(ot,t.preference)}catch{if(n===ii&&e===u(X)&&!u(Z)){let t=Zo(e)||`all`;Qo(e,t),M(ot,t)}}}async function Oa(){let e=u(X);if(!e||u(Z)||u(ft)||!u(ot))return;let t=++ii,n=[`all`,`mentions`,`muted`],r=u(ot),i=n[(n.indexOf(r)+1)%n.length];M(ot,i),Qo(e,i),M(ft,!0);try{await G(`/api/channels/${e}/notification-settings`,{method:`PATCH`,body:JSON.stringify({preference:i})})}catch{lt.get(e)===i&&Qo(e,r),t===ii&&e===u(X)&&!u(Z)&&M(ot,r)}finally{M(ft,!1)}}function ka(e=!1){Ga(),M(Dr,e),Kr+=1,dr.prune();let t=mi();return()=>mi()===t}async function Aa(e,t=`replace`,n=ka()){let r=$();r!==u(wr)&&M(Dr,!0);try{if(!r){n()&&Ra(``,{messages:[],oldest_seq:0,newest_seq:0,has_older:!1,has_newer:!1},t);return}await dr.run(()=>G(Ia(e)),e=>{let n=e,i=u(lr).get(r);!n.has_newer&&i&&i.newest_seq>n.newest_seq&&(n=i.oldest_seq>n.newest_seq?i:{...n,messages:Ka(n.messages,i.messages.filter(e=>ds(e)>n.newest_seq)),newest_seq:i.newest_seq,has_newer:i.has_newer}),Ra(r,n,t)},n)}catch(e){if(n())throw e}finally{n()&&M(Dr,!1)}}async function ja(e=!0){return e&&os(),Aa(Na())}async function Ma(e=ka()){let t=$();if(t)return M(Dr,!0),cr.set(t,{atBottom:!0}),Aa(`limit=100`,`replace`,e)}function Na(){let e=Pa(),t=e.unread_count||0,n=e.last_read_seq||0;return t>0?`around_seq=${encodeURIComponent(String(n+1))}&limit=100`:`limit=100`}function Pa(){return u(Z)?u(J).find(e=>e.id===u(Z))||{}:u(X)&&u(q).find(e=>e.id===u(X))||{}}function Ia(e){let t=u(Z)?`/api/dms/${u(Z)}/messages`:`/api/channels/${u(X)}/messages`,n=new URLSearchParams(e);!u(Z)&&u(Et)&&n.set(`topic_id`,u(Et));let r=n.toString();return r?`${t}?${r}`:t}async function La(e){if(!u(X)||e===u(Et))return;let t=$(),n=u(Et),r=u(St),i=u(lr).get(t),a=cr.get(t);pi(e);let o=Dt;e&&M(St,e),cr.delete(t),u(lr).delete(t);try{await Ma()}catch(s){if($()!==t||Dt!==o)return;pi(n),u(St)===e&&M(St,r),u(lr).delete(t);let c=Dt;try{if(await Ma(),$()!==t||Dt!==c)return;a&&(cr.set(t,a),M(Tr,a))}catch{if($()!==t||Dt!==c)return;i?(za(t,i),ss(t,i.messages),Ha(t,i)):us(),a&&(cr.set(t,a),M(Tr,a))}M(Kt,{kind:`error`,text:s instanceof Error?`Topic could not change: ${s.message}`:`Topic could not change`})}}function Ra(e,t,n){let r=bs(e).flatMap(e=>e.receipt?[e.receipt]:[]).sort((e,t)=>ds(e)-ds(t)),i=ds(t.messages.at(-1));if(!t.has_newer)for(let e of r)ds(e)===i+1&&(t={...t,messages:[...t.messages,e]},i=ds(e));r.some(e=>ds(e)>i)&&(t={...t,has_newer:!0});let a=Xa(e,t.messages,n),o=a[0]?.channel_seq||0,s=a[a.length-1]?.channel_seq||0,c=o>(t.messages[0]?.channel_seq||o),l=s<(t.messages[t.messages.length-1]?.channel_seq||s),d={messages:a,oldest_seq:o,newest_seq:s,has_older:t.has_older||c,has_newer:t.has_newer||l};za(e,d),Ha(e,d),(n!==`append`||e!==u(wr))&&M(Tr,cr.get(e)),ss(e,a)}function za(e,t){e&&(u(lr).delete(e),u(lr).set(e,t),Ba(e),Va(e),M(lr,new Map(u(lr))))}function Ba(e){let t=u(lr).size+1;for(;u(lr).size>8&&t>0;){t--;let n=u(lr).keys().next().value;if(!n)return;if(n===e){let e=u(lr).get(n);u(lr).delete(n),e&&u(lr).set(n,e);continue}u(lr).delete(n)}}function Va(e){let t=cr.size+1;for(;cr.size>16&&t>0;){t--;let n=cr.keys().next().value;if(!n)return;if(n===e){let e=cr.get(n);cr.delete(n),e&&cr.set(n,e);continue}cr.delete(n)}}function Ha(e,t=u(lr).get(e)){e===$()&&(M(_r,t?.has_older||!1),M(yr,t?.has_newer||!1))}function Ua(e){let t=u(lr).get(e);!e||!t||(za(e,{...t,has_newer:!0}),Ha(e))}function Wa(e,t){e===`older`?(M(pr,t),M(br,t===`loading`)):(mr=t,M(xr,t===`loading`))}function Ga(){fr=new Set,M(pr,`idle`),mr=`idle`,hr=!1,gr=!1,M(br,!1),M(xr,!1)}function Ka(e,t){let n=new Map;for(let r of[...e,...t])n.set(r.id,r);return[...n.values()].sort((e,t)=>(e.channel_seq||0)-(t.channel_seq||0))}function qa(e){let t=new Set,n=Ho(e);if(n>=0){let r=Uo(e,u(pt),n);r&&t.add(r.id)}let r=cr.get(e)?.anchorMessageID;r&&t.add(r);let i=et.session(e);i&&t.add(i.messageID),Q.root&&fs(Q.root,e)&&t.add(Q.root.id),u(Mr)&&fs(u(Mr),e)&&t.add(u(Mr).id);for(let n of u(pt))(n.status===`pending`||n.status===`failed`)&&fs(n,e)&&t.add(n.id);return t}function Xa(e,t,n){return Ue(t,n,qa(e))}function $a(){if(u(pr)!==`idle`){hr=!0;return}Do()}function ro(e=!1){if(mr!==`idle`){e&&(gr=!0);return}Oo()}async function Do(){let e=$(),t=mi(),n=u(lr).get(e),r=`${t}:older`;if(u(pr)!==`idle`){hr=!0;return}if(!e||!n?.has_older||n.oldest_seq<=0||fr.has(r))return;fr.add(r),hr=!1,Wa(`older`,`loading`),os();let i=!1;try{await dr.run(()=>G(Ia(`before_seq=${encodeURIComponent(String(n.oldest_seq))}&limit=50`)),t=>{let n=u(lr).get(e);n&&(Ra(e,{...n,messages:Ka(t.messages,n.messages),has_older:t.has_older},`prepend`),i=!0,Wa(`older`,`settling`))},()=>mi()===t)}catch(e){mi()===t&&M(Kt,{kind:`error`,text:xe(e,`Could not load older messages`)})}finally{fr.delete(r),mi()===t&&!i&&Wa(`older`,`idle`)}}async function Oo(){let e=$(),t=mi(),n=u(lr).get(e),r=`${t}:newer`;if(mr!==`idle`){gr=!0;return}if(!e||fr.has(r))return;if(!n||n.newest_seq<=0){await ja();return}fr.add(r),gr=!1,Wa(`newer`,`loading`);let i=!1;try{await dr.run(()=>G(Ia(`after_seq=${encodeURIComponent(String(n.newest_seq))}&limit=50`)),t=>{i=Ao(e,t,n.newest_seq),i&&Wa(`newer`,`settling`)},()=>mi()===t)}catch(e){mi()===t&&M(Kt,{kind:`error`,text:xe(e,`Could not load newer messages`)})}finally{fr.delete(r),mi()===t&&!i&&Wa(`newer`,`idle`)}}async function ko(e){let t=$(),n=mi();if(!u(Y)||!t)return;let r=u(lr).get(t);if(!r||r.newest_seq<=0){await ja();return}await dr.run(()=>G(Ia(`after_seq=${encodeURIComponent(String(r.newest_seq))}&limit=50`)),e=>{Ao(t,e,r.newest_seq)},()=>e()&&mi()===n)}function Ao(e,t,n){let r=u(lr).get(e);if(!r)return!1;let i=t.newest_seq||n,a=i>r.newest_seq?t.has_newer:in&&(n=r.channel_seq));return n}function No(e,t=u(pt)){let n=0;for(let r of t)r.direct_conversation_id===e&&typeof r.channel_seq==`number`&&r.channel_seq>n&&(n=r.channel_seq);return n}function Po(e,t){return e&&t.unread_count||0}async function Fo(e,t){let n=u(q).find(t=>t.id===e);if(n&&!(t<=0||t<=(n.last_read_seq||0))){M(q,u(q).map(n=>n.id===e?(()=>{let e=Math.max(n.last_seq||0,t);return{...n,last_seq:e,unread_count:t>=e?0:n.unread_count||0,last_read_seq:t}})():n));try{await G(`/api/channels/${e}/read`,{method:`POST`,body:JSON.stringify({seq:t})})}catch{}}}async function Io(e,t){let n=u(J).find(t=>t.id===e);if(n&&!(t<=0||t<=(n.last_read_seq||0))){M(J,u(J).map(n=>n.id===e?(()=>{let e=Math.max(n.last_seq||0,t);return{...n,last_seq:e,unread_count:t>=e?0:n.unread_count||0,last_read_seq:t}})():n));try{await G(`/api/dms/${e}/read`,{method:`POST`,body:JSON.stringify({seq:t})})}catch{}}}function Lo(e){let t=u(lr).get(e)?.newest_seq||0,n=u(q).find(t=>t.id===e);if(n)return Math.max(n.last_seq||0,(n.last_read_seq||0)+(n.unread_count||0),Mo(e),t);let r=u(J).find(t=>t.id===e);return r?Math.max(r.last_seq||0,(r.last_read_seq||0)+(r.unread_count||0),No(e),t):0}function Ro(e){let t=u(lr).get(e);return!t||t.has_newer?0:u(q).find(t=>t.id===e)?Mo(e):u(J).find(t=>t.id===e)?No(e):0}function zo(e={}){if(!e.all&&Date.now()e.id===t))return;if(!e.all&&!e.seq){let e=Ho(t);if(e>=0&&!rs(t,e))return}let n=e.all?Math.max(e.seq||0,Lo(t)):e.seq||Ro(t);if(!(n<=0)){if(u(J).some(e=>e.id===t)){Io(t,n),e.all&&Bo(t,n);return}u(q).some(e=>e.id===t)&&(Fo(t,n),e.all&&Bo(t,n))}}function Bo(e,t){Sr.delete(e),Sr=new Map(Sr),M(q,u(q).map(n=>n.id===e?{...n,last_seq:Math.max(n.last_seq||0,t),last_read_seq:Math.max(n.last_read_seq||0,t),unread_count:0}:n)),M(J,u(J).map(n=>n.id===e?{...n,last_seq:Math.max(n.last_seq||0,t),last_read_seq:Math.max(n.last_read_seq||0,t),unread_count:0}:n))}function Vo(e){let t=u(q).find(t=>t.id===e);return t?t.last_read_seq||0:u(J).find(t=>t.id===e)?.last_read_seq||0}function Ho(e){let t=u(q).find(t=>t.id===e);if(t)return Po(e,t)>0?t.last_read_seq||0:-1;let n=u(J).find(t=>t.id===e);return n&&Po(e,n)>0?n.last_read_seq||0:-1}function Uo(e,t,n){for(let r of t){if(!fs(r,e)||r.parent_message_id||r.author?.id===u(K)?.id||r.author_id===u(K)?.id)continue;let t=r.channel_seq;if(typeof t==`number`&&t>n)return r}return null}function Wo(e,t){if(!e)return;let n=ns(e);if(Po(e,n)<=0){Sr.delete(e),Sr=new Map(Sr);return}let r=n.last_read_seq||0,i=Sr.get(e);if(i?.boundarySeq===r&&i.since||!rs(e,r))return;let a=Uo(e,t,r);a&&(Sr=new Map(Sr).set(e,{boundarySeq:r,since:as(a.created_at)}))}function Go(e,t,n){if(!e||!n)return;let r=Sr.get(e);r?.boundarySeq===t&&r.since||(Sr=new Map(Sr).set(e,{boundarySeq:t,since:as(n)}))}function Ko(e){let t=e.payload,n=t.channel_seq??e.seq??t.seq;return typeof n==`number`?n:Number(n)||0}function qo(e){let t=e.payload;return{channelID:e.channel_id||(typeof t.channel_id==`string`?t.channel_id:``),dmID:typeof t.direct_conversation_id==`string`?t.direct_conversation_id:``}}async function Jo(e){try{let t=await G(`/api/channels/${e}/notification-settings`);return Qo(e,t.preference),e===u(X)&&!u(Z)&&!u(ft)&&M(ot,t.preference),t.preference}catch{return Zo(e)||`all`}}function Yo(e){return u(K)?.id&&e?`clickclack:channel-notification:v1:${u(K).id}:${e}`:``}function Xo(e){let t=Yo(e);if(!t)return null;try{let e=window.localStorage.getItem(t);return e===`all`||e===`mentions`||e===`muted`?e:null}catch{return null}}function Zo(e){return lt.get(e)||Xo(e)}function Qo(e,t){lt=new Map(lt).set(e,t);let n=Yo(e);if(n)try{window.localStorage.setItem(n,t)}catch{}}async function $o(e,t){if(e.type!==`message.created`&&e.type!==`thread.reply_created`)return;let{channelID:n,dmID:r}=qo(e),i=Ko(e);if(e.type===`message.created`&&i>0){let e=n||r;if(i<=(dt.get(e)||0))return;dt.set(e,i)}let a=e.payload,o=typeof a.kind==`string`?a.kind:``;if(o===`agent_commentary`||o===`agent_tool`||!u(jn)||document.visibilityState===`visible`&&t)return;if(n){let t=await Jo(n);if(!t||!u(jn))return;let r=n===u(X)&&!u(Z);if(document.visibilityState===`visible`&&r||t===`muted`||t===`mentions`&&!e.mentioned_user_ids?.includes(u(K)?.id||``))return}let s=typeof a.message_id==`string`?a.message_id:`${e.channel_id||``}:${e.seq||Date.now()}`,c=typeof a.author_id==`string`?a.author_id:``,l=typeof a.body==`string`?a.body:`New message`;if(e.type===`thread.reply_created`&&typeof a.message_id==`string`)try{let e=await G(`/api/messages/${a.message_id}`);c=e.message.author_id,l=e.message.body}catch{}if(c&&c===u(K)?.id||!u(jn)||document.visibilityState===`visible`&&(n&&n===u(X)||r&&r===u(Z)))return;let d=u(q).find(e=>e.id===n),f=yc(c)?.display_name||`ClickClack`,p=d?`#${_t(d)}`:`Direct message`;if(jt){jt.notify({body:es(l),route:Wi(n||r),tag:`clickclack:${s}`,title:`${f} in ${p}`});return}if(!(typeof Notification>`u`||Notification.permission!==`granted`))try{let e=new Notification(`${f} in ${p}`,{body:es(l),tag:`clickclack:${s}`,icon:`/favicon.svg`});e.onclick=()=>{window.focus(),e.close(),n?Ea(n):r&&rc(r)}}catch{}}function es(e){let t=e.replace(/!\[[^\]]*]\([^)]+\)/g,`[image]`).replace(/\[[^\]]+]\(([^)]+)\)/g,`$1`).replace(/[`*_>#|]/g,``).replace(/\s+/g,` `).trim();return t?t.length>180?`${t.slice(0,177)}...`:t:`New message`}async function ts(e){let t=e.payload,n=typeof t.direct_conversation_id==`string`?t.direct_conversation_id:``;return!n||u(J).some(e=>e.id===n)?!1:(await tc(),u(J).some(e=>e.id===n))}function ns(e){return u(q).find(t=>t.id===e)||u(J).find(t=>t.id===e)||{}}function rs(e,t,n=u(lr)){if(!e||t<0)return!1;let r=n.get(e);if(!r||r.messages.length===0)return!1;let i=t+1;return r.oldest_seq<=i&&r.newest_seq>=i}function is(e,t,n=u(lr)){let r=Sr.get(e);if(r?.boundarySeq===t)return r.since;if(!rs(e,t,n))return``;let i=Uo(e,u(pt),t);return i?as(i.created_at):``}function as(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}).format(t)}function os(){if(!u(wr)||!u(sr))return;let e=u(sr).captureState();e&&cr.set(u(wr),e)}function ss(e,t){let n=e!==u(wr);for(let[t,n]of Nt)!n.message.status&&(n.draft.viewKey!==e||u(Et)&&n.draft.topicID!==u(Et))&&Nt.delete(t);let r=bs(e).map(e=>e.message),i=new Map(r.map(e=>[e.id,e])),a=new Map(r.filter(e=>e.nonce).map(e=>[e.nonce,e]));Ze.seedMessages(t);let o=t.map(e=>{let t=i.get(e.id)||(e.nonce?a.get(e.nonce):void 0);return t?(!t.status&&(t.attachments||[]).every(t=>e.attachments?.some(e=>e.id===t.id))&&Nt.delete(t.nonce),{...e,nonce:t.nonce,status:t.status,attachments:t.attachments?.length?t.attachments:e.attachments}):e}),s=new Set(o.map(e=>e.id)),c=new Set(o.map(e=>e.nonce).filter(Boolean)),l=r.filter(e=>!s.has(e.id)&&!(e.nonce&&c.has(e.nonce)));M(pt,[...o,...l].sort((e,t)=>(e.channel_seq||1/0)-(t.channel_seq||1/0))),et.reconcile(e,u(pt)),M(wr,e),Wo(e,u(pt)),n&&(M(Lr,[]),M(zr,[]),ln())}function cs(e){us(dr.updateMessage(e))}function ls(e){us(dr.updateAuthor(e))}function us(e){let t=$(),n=t?u(lr).get(t):void 0;if(e)for(let t of Nt.values()){let n=t.message;t.message={...e(n),status:n.status,attachments:n.attachments},t.receipt&&=e(t.receipt)}let r=e?n?.messages.map(e)||[]:n?.messages||[];n?Ra(t,{...n,messages:r},`append`):ss(t,r)}function ds(e){return e?.channel_seq||0}function fs(e,t){return t?e.channel_id===t||e.direct_conversation_id===t:!1}async function ps(e=()=>!0){await y(),e()&&await u(sr)?.scrollToBottom()}function ms(){return u(sr)?.isFollowing()||u(sr)?.isNearBottom(96)!==!1}async function hs(e=!1){let t=u(Dr)||u(yr)||u(we)>0,n=ka();try{if(t&&await Ma(n),await ps(n),!n())return;u(yr)||zo({all:!0}),await ps(n)}catch(t){n()&&(M(Kt,{kind:`error`,text:xe(t,`Could not jump to latest messages`)}),e&&await ps(n))}}function gs(e,t,n=`tmp_${e}`){let r=new Date().toISOString();return{id:n,workspace_id:t.workspaceID,channel_id:t.channelID,direct_conversation_id:t.directConversationID,topic_id:t.topicID,author_id:u(K)?.id||``,thread_root_id:n,body:t.body,body_format:`markdown`,created_at:r,author:u(K)||void 0,attachments:t.upload?[t.upload]:[],quoted_message_id:t.quotedMessageID,nonce:e,status:`pending`}}async function _s(){let e=u(an).trim();if(!e)return;if(u(W)&&!u(me)){M(Kt,{kind:`error`,text:`This conversation has no active recipient`});return}if(!u(X)&&!u(Z)){M(Kt,{kind:`ephemeral`,text:`Pick or create a channel to send a message.`});return}ln(),M(Kt,null);let t=++oi,n=$(),r=u(Z)?`dm`:`channel`,i=u(Mr)&&u(Nr)===r?u(Mr):null;if(u(X)&&!u(Z)&&!u(xn)&&!i){let r=eo(e),i=r?to(u(Wt),r.command):void 0;if(r&&i){M(an,``),$s(),await vs(u(X),r.command,r.text,e,n,t);return}}let a={body:e,quotedMessageID:i?.id,upload:u(xn)||void 0,workspaceID:u(Y),channelID:u(X)||void 0,directConversationID:u(Z)||void 0,topicID:u(X)&&u(St)||void 0,topicFilterID:u(Et),topicFilterGeneration:Dt,viewKey:$()};M(an,``),i&&zs(),$s(),await Ss(a)}async function vs(e,t,n,r,i,a){try{let r=await no(e,t,n);if(a!==oi||$()!==i)return;r.text&&r.response_type!==`in_channel`&&M(Kt,{kind:`ephemeral`,text:r.text})}catch(e){if(console.warn(`slash dispatch failed`,e),a!==oi||$()!==i)return;M(Kt,{kind:`error`,text:e instanceof be&&e.message?ys(e):`${t} failed`}),u(an).trim()||M(an,r)}}function ys(e){try{let t=JSON.parse(e.message);if(t&&typeof t.error==`string`&&t.error)return t.error}catch{}return e.message}function bs(e){return[...Nt.values()].filter(({draft:t})=>t.viewKey===e&&(!u(Et)||t.topicID===u(Et)))}async function xs(e,t,n,r){let{draft:i}=e;if(e.message=t,$()!==i.viewKey)return;let a=!1,o=u(Et)===i.topicFilterID&&Dt===i.topicFilterGeneration;if(r()&&o&&u(Et)&&i.topicID!==u(Et)){pi(``),cr.delete(i.viewKey),u(lr).delete(i.viewKey),r=ka();try{await Ma(r)}catch{a=!0}}if($()===i.viewKey){if(u(Et)&&i.topicID!==u(Et)){u(an).trim()||M(an,i.body),M(Kt,{kind:`error`,text:`${n} Clear the active topic filter to recover the draft.`});return}us(),M(Kt,{kind:`error`,text:a?`${n} The unfiltered timeline could not reload.`:n}),await ps(r)}}async function Ss(e,t,n){let r=Kr,i=()=>Kr===r&&$()===e.viewKey,a=t??Qe(),o=`tmp_${a}`,s=n??o,c=!u(Et)||e.topicID===u(Et),l=!t&&$()===e.viewKey&&c,d=gs(a,e,s),f={draft:e,message:d,receipt:Nt.get(a)?.receipt};Nt.set(a,f),$()===e.viewKey&&c&&(us(),t||ps());let p=e.directConversationID?`/api/dms/${e.directConversationID}/messages`:`/api/channels/${e.channelID}/messages`,m={body:e.body,nonce:a};e.quotedMessageID&&(m.quoted_message_id=e.quotedMessageID),e.topicID&&(m.topic_id=e.topicID),e.upload&&(m.upload_id=e.upload.id);try{let t=f.receipt||(await G(p,{method:`POST`,body:JSON.stringify(m)})).message;if(f.receipt=t,e.upload&&!t.attachments?.some(t=>t.id===e.upload?.id))try{await G(`/api/messages/${t.id}/attachments`,{method:`POST`,body:JSON.stringify({upload_id:e.upload.id})}),t={...t,attachments:[...t.attachments||[],e.upload]}}catch(n){console.warn(`attachment fallback failed`,n),await xs(f,{...t,nonce:a,status:`failed`,attachments:[...t.attachments||[],e.upload]},`The message was sent, but its attachment failed. Retry or discard it below.`,i);return}f.receipt=t,f.message={...t,nonce:a},$()===e.viewKey?us():Nt.delete(a)}catch(t){console.warn(`send failed`,t),await xs(f,{...d,status:`failed`},e.upload?`The attachment failed, so the message was not sent. Retry or discard it below.`:`The message failed to send. Retry or discard it below.`,i);return}i()&&l&&await hs(!0)}function Cs(e){if(!e.nonce)return;let t=Nt.get(e.nonce)?.draft;t&&Ss(t,e.nonce,e.id)}function ws(e){if(!e.nonce)return;let t=Nt.get(e.nonce);t?.receipt?t.message={...t.receipt,nonce:e.nonce}:Nt.delete(e.nonce),us()}async function Ts(e,t){let n=Q.selection,r=()=>e===u(Er)&&et.session(e)?.generation===t.generation&&(t.surface!==`thread`||Q.selection===n);if(r()){if(Gr++,t.surface===`thread`){if(t.threadRootID&&n?.messageID!==t.threadRootID&&(M(Ft,!1),Q.select(t.threadRootID),n=Q.selection,!await As(t.threadRootID,void 0,r))||!await Q.target({messageID:t.messageID,threadSeq:t.threadSeq},r)||!r())return;Q.root?.route_id&&await qi(u(Y),Q.root.id)}else u(sr)?.scrollToMessage(t.messageID),await qi(u(Y),Q.root?.id||$());for(let e=0;e<16;e+=1){if(await y(),await new Promise(e=>requestAnimationFrame(()=>e())),!r())return;let e=document.querySelector(t.surface===`timeline`?`main.timeline`:`[aria-label="Thread pane"]`)?.querySelector(`[data-message-id="${CSS.escape(t.messageID)}"]`)?.querySelector(`textarea[aria-label="Edit message"]`);if(e){e.focus({preventScroll:!0});return}}}}function Es(e){cs(e),Q.updateMessage(e),M(It,u(It).map(t=>t.id===e.id?$e(t,e):t))}function Ds(e){!e.id||e.deleted_at||u(li).has(e.id)||(M(ui,e),M(di,``))}async function Os(){let e=u(ui);if(!(!e||u(li).has(e.id))){M(li,new Set([...u(li),e.id])),M(di,``);try{let t=(await G(`/api/messages/${e.id}`,{method:`DELETE`})).message;et.cancelMessage($(),t.id),cs(t),Q.updateMessage(t),M(It,u(It).filter(e=>e.id!==t.id)),u(Mr)?.id===t.id&&zs(),M(ui,null)}catch(e){M(di,e instanceof Error?e.message:`Could not delete message`)}finally{let t=new Set(u(li));t.delete(e.id),M(li,t)}}}async function ks(e){Gr++,qs(),M(Ft,!1),await As(e.id,e)&&u(Y)&&Q.root?.route_id&&await qi(u(Y),Q.root.id)}async function As(e,t,n=()=>!0){M(Zt,null),M(Qt,``),M(Pt,null),M(Ir,`thread`),Q.select(e,t);try{return await Q.open(n)}catch{return!1}}function js(e=[]){let t=Q.root;t&&(Ze.seedMessages(e),et.reconcile($(),[t,...Q.replies]),cs({id:t.id,thread_state:t.thread_state}))}async function Ms(e){await dr.run(()=>G(`/api/messages/${e}/thread?latest=true&limit=1`),e=>{let t={...e.root,thread_state:e.thread_state};Ze.seedMessages([t]),cs(t)})}async function Ns(e,t){!u(pt).some(t=>t.id===e)&&!dr.pending||await dr.run(()=>G(`/api/messages/${e}`),e=>cs(e.message),t)}function Ps(e,t){let n=u(pt).find(t=>t.id===e);if(!n)return!1;let r=new Date(t.created_at).getTime();if(Number.isFinite(r)&&ra}async function Fs(){u(W)&&!u(me)||await Q.send()}function Is(e,t){t===`thread`?Q.setQuote(e):(M(Mr,e),M(Nr,t)),M(Ir,t===`thread`?`thread`:`message`)}function Ls(){return u(ui)!==null||u(Xt)!==null||u(wn)||u(En)||u(kn)||u(An)}function Rs(){return u(Ir)===`thread`&&Q.root&&u(Fr)?u(Fr):u(Pr)}function zs(){M(Mr,null),M(Nr,null)}async function Bs(e){let t=e.quoted_message_id;if(!t)return;if(e.parent_message_id&&e.thread_root_id===Q.selection?.messageID){await Q.target({messageID:t});return}let n=ka();if(u(sr)?.scrollToMessage(t)??!1){await Us(t,n);return}let r=await G(`/api/messages/${t}`);!n()||!fs(r.message,$())||await Zs(r.message)}async function Vs(){ka(),Cr=Date.now()+1200,!(u(De)&&u(sr)?.scrollToDivider(!1))&&await Hs()}async function Hs(){let e=$();if(!e)return;Cr=Date.now()+1200;let t=Vo(e),n=Sr.get(e),r=(n?.boundarySeq===t?n.boundarySeq:t)+1;r<=0||await Qs(r)}async function Us(e,t){for(let n=0;n<16;n+=1){if(await y(),await new Promise(e=>requestAnimationFrame(()=>e())),!t())return;let n=document.querySelector(`[data-message-id="${CSS.escape(e)}"]`);if(n){n.classList.add(`highlight`),window.setTimeout(()=>n.classList.remove(`highlight`),1500);return}}}async function Ws(){if(!u(Y)||!u(gn).trim()){qs();return}let e=u(gn).trim();u(Zt)&&Dc(),(Q.root||u(Pt))&&jc();let t=++bn,n=u(Z)&&u(W)?{workspaceID:u(Y),channelID:``,directConversationID:u(Z),label:`@${ct(u(W),u(K)?.id)}`}:u(X)&&u(I)?{workspaceID:u(Y),channelID:u(X),directConversationID:``,label:`#${_t(u(I))}`}:{workspaceID:u(Y),channelID:``,directConversationID:``,label:``};M(vn,!1),yn=0;let r={query:e,scope:n,results:[],nextCursor:null,state:`loading`,error:``,loadingMore:!1,moreError:``,activeResultID:``};M(_n,r);try{let e=await G(`/api/search?${Gs(r).toString()}`);if(t!==bn)return;M(_n,{...r,results:e.results,nextCursor:e.next_cursor,state:`ready`})}catch(e){if(t!==bn)return;M(_n,{...r,state:`error`,error:e instanceof be?e.message:`Search is unavailable right now.`})}}function Gs(e,t=``){let n=new URLSearchParams({workspace_id:e.scope.workspaceID,q:e.query});return e.scope.directConversationID?n.set(`direct_conversation_id`,e.scope.directConversationID):e.scope.channelID&&n.set(`channel_id`,e.scope.channelID),t&&n.set(`cursor`,t),n}async function Ks(){let e=u(_n);if(!e||e.state!==`ready`||!e.nextCursor||e.loadingMore)return;let t=bn;M(_n,{...e,loadingMore:!0,moreError:``});try{let n=await G(`/api/search?${Gs(e,e.nextCursor).toString()}`);if(t!==bn||!u(_n))return;let r=new Set(u(_n).results.map(e=>e.id));M(_n,{...u(_n),results:[...u(_n).results,...n.results.filter(e=>!r.has(e.id))],nextCursor:n.next_cursor,loadingMore:!1})}catch(e){if(t!==bn||!u(_n))return;M(_n,{...u(_n),loadingMore:!1,moreError:e instanceof be?e.message:`Couldn’t load more results.`})}}function qs(){bn+=1,M(gn,``),M(_n,null),M(vn,!1),yn=0}function Js(e){if(e.channel_name)return`#${e.channel_name}`;if(e.direct_conversation_id){let t=u(J).find(t=>t.id===e.direct_conversation_id);return t?`@${ct(t,u(K)?.id)}`:`Direct message`}return``}async function Ys(e){let t=u(_n),n=e.channel_id||e.direct_conversation_id||``;if(!(!t||!u(Y)||!n)&&(Gr++,M(_n,{...t,activeResultID:e.id}),$()!==n&&(await qi(u(Y),n),await ia(Gi(u(Y)),Ki(n))),$()===n)){if(e.parent_message_id){yn=document.querySelector(`.search-results-scroll`)?.scrollTop??0;let t=bn;if(M(vn,!0),!await As(e.thread_root_id,void 0,()=>t===bn&&u(vn)&&u(_n)?.activeResultID===e.id))return;let n=()=>t===bn&&u(vn)&&u(_n)?.activeResultID===e.id;if(!await Q.target({messageID:e.id,threadSeq:e.thread_seq},n)||!n())return;Q.root?.route_id&&await qi(u(Y),Q.root.id),await y(),n()&&document.querySelector(`.thread .thread-back`)?.focus({preventScroll:!0});return}if(await qi(u(Y),n),e.channel_seq&&e.channel_seq>0){await Qs(e.channel_seq,e.id);return}await ja()}}async function Xs(){if(Gr++,!u(_n)||!u(vn))return;let e=$();Q.close(),M(Pt,null),M(Ir,`message`),M(vn,!1),u(Y)&&e&&await qi(u(Y),e),await y();let t=document.querySelector(`.search-results-scroll`);t&&(t.scrollTop=yn),(u(_n).activeResultID?document.querySelector(`.search-result[data-result-id="${CSS.escape(u(_n).activeResultID)}"]`):null)?.focus({preventScroll:!0})}async function Zs(e){let t=e.channel_seq||0;if(t<=0){await ja();return}await Qs(t,e.id)}async function Qs(e,t=``){let n=$();if(!n)return;let r=!!u(Et);r&&(pi(``),u(lr).delete(n));let i=ka(r);t&&cr.set(n,{atBottom:!1,anchorMessageID:t,anchorPixelOffset:0}),await Aa(`around_seq=${encodeURIComponent(String(e))}&limit=100`,`around`,i),await y(),i()&&(t?(u(sr)?.scrollToMessage(t),await Us(t,i)):u(sr)?.scrollToDivider(!1))}function $s(){Cn?.abort(),Cn=null,M(Sn,``),M(xn,null)}async function ec(e){let t=e.currentTarget,n=t.files?.[0],r=u(Y);if(!n||!r)return;t.value=``,Cn?.abort();let i=new AbortController;Cn=i,M(Sn,r),M(Kt,null);let a=()=>Cn===i&&!i.signal.aborted&&u(Y)===r;try{let e=await Mt(n,i.signal);if(!a())return;let t=new FormData;t.set(`workspace_id`,r),t.set(`file`,n),e.width>0&&t.set(`width`,String(e.width)),e.height>0&&t.set(`height`,String(e.height)),e.durationMS>0&&t.set(`duration_ms`,String(e.durationMS));let o=await G(`/api/uploads`,{method:`POST`,body:t,signal:i.signal});a()&&M(xn,o.upload)}catch(e){a()&&M(Kt,{kind:`error`,text:xe(e,`Could not upload file`)})}finally{Cn===i&&(Cn=null)}}async function tc(e=u(Y)){let t=++Xr;if(!e){M(J,[]);return}let n=await G(`/api/dms?workspace_id=${e}`);t===Xr&&e===u(Y)&&(M(J,n.conversations),u(Z)&&!u(J).some(e=>e.id===u(Z))&&M(Z,``))}function nc(e){M(J,u(J).some(t=>t.id===e.id)?u(J).map(t=>t.id===e.id?e:t):[...u(J),e])}async function rc(e){M(Ar,!1);let t=Hi(u(Y),e);e===u(Z)&&!u(X)&&window.location.pathname===t||await qi(u(Y),e)}async function ic(e){let t=e.trim();if(u(dn)===`direct`||!u(Y)||!t)return;let n=u(Y),r=Gr,i=++hn,a=()=>i===hn&&r===Gr&&n===u(Y);M(dn,`direct`),M(mn,``);try{let e=await G(`/api/dms`,{method:`POST`,body:JSON.stringify({workspace_id:n,member_ids:[t]})});if(n===u(Y)&&!u(J).some(t=>t.id===e.conversation.id)&&nc(e.conversation),!a())return;M(un,``),M(An,!1),Xi(),await qi(n,e.conversation.id)}catch(e){a()&&M(mn,xe(e,`Could not start direct message`))}finally{i===hn&&M(dn,null)}}function ac(){ci&&clearTimeout(ci),ci=void 0,M(si,null)}function oc(e,t){ac(),M(si,{conversation:e,restoreRoute:t,title:ct(e,u(K)?.id)}),ci=setTimeout(()=>{M(si,null),ci=void 0},8e3)}async function sc(){let e=u(si);if(e){ac();try{let t=await G(`/api/dms/${e.conversation.id}/open`,{method:`POST`});nc(t.conversation),e.restoreRoute&&await qi(e.conversation.workspace_id,t.conversation.id)}catch(e){M(Kt,{kind:`error`,text:xe(e,`Could not restore direct message`)})}}}async function cc(e){if(!e)return;let t=u(J).find(t=>t.id===e),n=u(Z)===e;if(await G(`/api/dms/${e}`,{method:`DELETE`}),M(J,u(J).filter(t=>t.id!==e)),t&&oc(t,n),n){Xi();let e=u(q)[0]?.id||``;M(Z,``),M(X,e),e&&na(u(Y),e),await qi(u(Y),e),await ja()}}function lc(){if(ai+=1,or?.close(),or=null,M(er,!1),!u(Y))return;let e=u(Y);or=He({workspaceID:e,onEvent:dc,onOpen:async(t,n)=>{let r=rr===e;await uc(e,t,r,n),t()&&((!r||n)&&(dt=new Map([...u(q),...u(J)].map(e=>[e.id,e.last_seq||0]))),rr=e,M(nr,``))},onError:t=>{if(e===u(Y)){if(t instanceof qe){if(Je()&&Je()!==e&&Je()!==Gi(e))return;or?.close(),fe(`/app`,{invalidateAll:!0,replaceState:!0}).catch(Ai);return}if(t instanceof be&&t.status===401){Ai(t);return}M(nr,xe(t,`Could not process realtime event`))}},onStatusChange:e=>{M(er,e)}})}async function uc(e,t=()=>!0,n=!0,r=!0){let i=++ai;if(!e||e!==u(Y)||!t())return;let a=Q.root?.id||``,o=u(Pt)?.kind===`bot`?u(Pt).id:``;if(M(Lr,[]),M(zr,[]),!r){await Promise.all([ya(e),xa(e,!0)]);return}if(Ze.clear(),await Promise.all([Bi(),ma(!1,!1,!1),tc(e),_a(e),ya(e),xa(e,!0),ha(e)]),!(i!==ai||e!==u(Y)||!t())){if(u(X)&&!u(q).some(e=>e.id===u(X))&&M(X,``),u(Z)&&!u(J).some(e=>e.id===u(Z))&&M(Z,``),!u(X)&&!u(Z)){let t=Zi(e);if(t){let n=u(J).some(e=>e.id===t);M(Z,n?t:``),M(X,n?``:t),n||na(e,t),await qi(e,t,!0)}}if(!(i!==ai||e!==u(Y)||!t())&&(await ja(n),!(i!==ai||e!==u(Y)||!t())&&(await Nc(),!(i!==ai||e!==u(Y)||!t())&&(a&&Q.root?.id===a&&await Q.refresh(t),o&&u(Pt)?.id===o)))){let e=yc(o);M(Pt,e&&!e.deleted_at?e:null)}}}async function dc(e,t){if((e.type===`pin.added`||e.type===`pin.removed`)&&e.channel_id===u(X)&&!u(Z)){await Nc();return}if(e.type===`typing.started`||e.type===`typing.stopped`){gc(e);return}if(e.type===`agent.progress`){_c(e);return}if(e.type===`channel.read`||e.type===`dm.read`){mc(e);return}if(e.type===`bot_command.updated`){e.workspace_id===u(Y)&&xa(e.workspace_id,!0).catch(t=>{e.workspace_id===u(Y)&&(M(nr,xe(t,`Could not refresh bot commands`)),lc())});return}if(e.type===`bot.deleted`){e.workspace_id===u(Y)&&await fc(e);return}if(e.type===`bot.membership_removed`){e.workspace_id===u(Y)&&await pc(e);return}if((e.type===`channel.created`||e.type===`channel.updated`)&&e.workspace_id===u(Y)){await ma(!1,!1,!1);return}if(e.type===`member.moderation_updated`&&e.workspace_id===u(Y)){let t=u(Z),n=e.payload.user_id===u(K)?.id;if(await Bi(),await _a(),await ma(!1,n,n),n){if(await tc(),t&&(u(J).some(e=>e.id===t)?(M(Z,t),M(X,``)):M(Z,``)),!u(X)&&!u(Z)){Ra(``,{messages:[],oldest_seq:0,newest_seq:0,has_older:!1,has_newer:!1},`replace`);return}await ja()}return}e.workspace_id===u(Y)&&e.payload.topic_id&&!u(rt).some(t=>t.id===e.payload.topic_id)&&await ha(e.workspace_id),(e.type===`message.updated`||e.type===`message.deleted`)&&u(zt).has(e.payload.message_id||``)&&await Nc();let n=(e.channel_id===u(X)||e.payload.direct_conversation_id===u(Z))&&!(e.type===`message.created`&&u(Et)&&e.payload.topic_id!==u(Et));if(n&&(e.type===`reaction.added`||e.type===`reaction.removed`)){Ze.applyEvent(e);return}if($o(e,n),e.type===`message.created`&&!n&&(await ts(e)||hc(e)),n&&(e.type===`message.created`||e.type===`message.updated`||e.type===`message.deleted`)){let n=e.payload.nonce;if(e.type===`message.created`&&n&&Nt.has(n))return;let r=ms(),i=Ko(e),a=e.type===`message.created`&&(i<=0||i>(u(lr).get($())?.newest_seq||0));if(a&&!r?(Cr=Date.now()+1200,Ua($())):a?await ko(t):e.type!==`message.created`&&await Ns(e.payload.message_id||``,t),!t())return;e.type===`message.created`&&hc(e,r,a)}if(await Q.handleEvent(e,t))return;let r=e.payload.root_message_id||e.payload.message_id;r&&e.type===`thread.state_updated`&&Ps(r,e)&&await Ms(r)}async function fc(e){let t=e.payload.bot_user_id||``;if(!t)return;let n=e.payload.deleted_at||e.created_at,r=e.payload.former_handle||``,i=e=>e.id===t?{...e,handle:``,former_handle:r,deleted_at:n}:e;M(J,u(J).map(e=>({...e,members:e.members.map(i)}))),M(Vt,u(Vt).filter(e=>e.user.id!==t)),M(Wt,u(Wt).filter(e=>e.bot_user_id!==t)),M(Gt,u(Gt).filter(e=>e.bot.id!==t)),M(Lr,u(Lr).filter(e=>e.userID!==t)),u(_n)&&M(_n,{...u(_n),results:u(_n).results.map(e=>({...e,author:i(e.author)}))}),u(Pt)?.id===t&&M(Pt,null);let a=Q.selection;await Promise.all([tc(),_a(),ya(),xa()]),va(),ls({id:t,handle:``,former_handle:r,deleted_at:n}),Q.isCurrent(a)&&await Q.refresh()}async function pc(e){let t=e.payload.bot_user_id||``;t&&(M(Vt,u(Vt).filter(e=>e.user.id!==t)),M(Wt,u(Wt).filter(e=>e.bot_user_id!==t)),M(Gt,u(Gt).filter(e=>e.bot.id!==t)),u(Pt)?.id===t&&M(Pt,null),await Promise.all([tc(e.workspace_id),_a(e.workspace_id),ya(e.workspace_id),xa(e.workspace_id)]),va(e.workspace_id))}function mc(e){let t=e.payload,n=typeof t.user_id==`string`?t.user_id:``;if(!n||n!==u(K)?.id)return;let r=e.seq??t.last_read_seq??t.seq,i=typeof r==`number`?r:Number(r)||0;if(e.type===`channel.read`){let n=typeof t.channel_id==`string`?t.channel_id:e.channel_id||``;if(!n)return;M(q,u(q).map(e=>{if(e.id!==n)return e;let t=Math.max(e.last_read_seq||0,i);return{...e,last_read_seq:t,unread_count:t>=(e.last_seq||0)?0:e.unread_count||0}}))}else{let e=typeof t.direct_conversation_id==`string`?t.direct_conversation_id:``;if(!e)return;M(J,u(J).map(t=>{if(t.id!==e)return t;let n=Math.max(t.last_read_seq||0,i);return{...t,last_read_seq:n,unread_count:n>=(t.last_seq||0)?0:t.unread_count||0}}))}}function hc(e,t,n=!1){let r=e.payload,i=typeof r.kind==`string`?r.kind:``;if(i===`agent_commentary`||i===`agent_tool`)return;let a=typeof r.author_id==`string`?r.author_id:``;if(a&&a===u(K)?.id||r.parent_message_id)return;let o=Ko(e),{channelID:s,dmID:c}=qo(e),l=s||c;if(!l)return;let d=ns(l),f=s?s===u(X)&&!u(Z):c===u(Z),p=f&&(!s||!u(Et))&&(t??ms());if(o>0&&o<=(d.last_seq||0)&&!(n&&p))return;let m=o>0?o:(d.last_seq||0)+1,h=f&&!p&&(d.unread_count||0)===0;h&&Go(l,d.last_read_seq||0,e.created_at);let g={last_seq:Math.max(d.last_seq||0,m),last_read_seq:h?Math.max(d.last_read_seq||0,m-1):d.last_read_seq||0,unread_count:p?0:(d.unread_count||0)+1};s?M(q,u(q).map(e=>e.id===l?{...e,...g}:e)):M(J,u(J).map(e=>e.id===l?{...e,...g}:e))}function gc(e){let t=e.payload,n=typeof t.user_id==`string`?t.user_id:``;if(!n||n===u(K)?.id)return;let r=e.channel_id||(typeof t.channel_id==`string`?t.channel_id:``),i=typeof t.direct_conversation_id==`string`?t.direct_conversation_id:``;if(!(u(X)&&r===u(X)||u(Z)&&i===u(Z)))return;if(e.type===`typing.stopped`){M(Lr,u(Lr).filter(e=>e.userID!==n));return}let a=yc(n),o=u(Lr).filter(e=>e.userID!==n);o.push({userID:n,user:a,expiresAt:Date.now()+Jn}),M(Lr,o),bc()}function _c(e){let t=e.payload,n=e.channel_id||(typeof t.channel_id==`string`?t.channel_id:``),r=typeof t.direct_conversation_id==`string`?t.direct_conversation_id:``;if(!(u(X)&&n===u(X)||u(Z)&&r===u(Z)))return;let i=typeof t.turn_id==`string`?t.turn_id:``,a=typeof t.op==`string`?t.op:``;if(!i||!a)return;let o=typeof t.user_id==`string`?t.user_id:``,s=Ya(o,i);if(a===`clear`){M(zr,u(zr).filter(e=>e.turnId===i?o&&e.userId?e.key!==s:!1:!0));return}let c=t.line,l=c&&typeof c.id==`string`?c.id:``;if(!l)return;let d=c&&typeof c.text==`string`?c.text:``,f=c&&typeof c.title==`string`?c.title:``,p=d||f,m=c&&typeof c.tool_name==`string`?c.tool_name:typeof c?.toolName==`string`?c.toolName:void 0,h=c&&typeof c.status==`string`?c.status:void 0,g=c&&typeof c.kind==`string`?c.kind:void 0,_=u(zr).find(e=>e.key===s),v=_?.lines.find(e=>e.id===l),y={id:l,kind:g??v?.kind??`lifecycle`,text:p||v?.text||``,toolName:m??v?.toolName,status:h??v?.status,finalized:a===`finalize`||(v?.finalized??!1)};if(!v&&!y.text&&!y.toolName)return;let b=Date.now()+Zn;if(!_)M(zr,[...u(zr),{key:s,turnId:i,userId:o,lines:[y],expiresAt:b}]);else{let e=_.lines.some(e=>e.id===l)?_.lines.map(e=>e.id===l?y:e):[..._.lines,y];M(zr,u(zr).map(t=>t.key===s?{...t,lines:e,expiresAt:b}:t))}vc()}function vc(){Br||=window.setInterval(()=>{let e=Date.now(),t=u(zr).filter(t=>t.expiresAt>e);t.length!==u(zr).length&&M(zr,t),t.length===0&&Br&&(window.clearInterval(Br),Br=void 0)},1e3)}function yc(e){if(u(K)?.id===e)return u(K);let t=u(Ht).find(t=>t.id===e);if(t)return t;let n=u(pt).find(t=>t.author?.id===e)?.author;if(n)return n;let r=u(C).find(t=>t.author?.id===e)?.author;if(r)return r;if(Q.root?.author?.id===e)return Q.root.author;let i=u(Vt).find(t=>t.user.id===e)?.user;if(i)return i;for(let t of u(J)){let n=t.members.find(t=>t.id===e);if(n)return n}}function bc(){Rr||=window.setInterval(()=>{let e=Date.now(),t=u(Lr).filter(t=>t.expiresAt>e);t.length!==u(Lr).length&&M(Lr,t),t.length===0&&Rr&&(window.clearInterval(Rr),Rr=void 0)},1e3)}function xc(){u(Y)&&(!u(X)&&!u(Z)||sn({workspaceID:u(Y),channelID:u(X)||void 0,directConversationID:u(Z)||void 0}))}function Sc(e){!e||e.deleted_at||(ca(),qs(),M(Zt,null),M(Qt,``),Xi(),M(Pt,e),Yi(),(u(A)===`owner`||u(A)===`moderator`)&&!u(Vt).some(t=>t.user.id===e.id)&&_a())}function Cc(e){e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),_s())}function wc(e){e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Fs())}function Tc(e,t){Ls()||M(Xt,{url:e,title:t})}function Ec(e){M(en,document.activeElement instanceof HTMLElement?document.activeElement:null),M(Qt,u(Er)),M(Zt,e),y().then(()=>{document.querySelector(`.artifact-viewer__actions > button:last-child`)?.focus()})}function Dc(){let e=u(en),t=u(Zt)?.id||``;M(Zt,null),M(Qt,``),M(en,null),y().then(()=>{if(e?.isConnected){e.focus({preventScroll:!0});return}(Q.root?document.querySelector(`.thread`):document)?.querySelector(`[data-artifact-upload-id="${CSS.escape(t)}"]`)?.focus({preventScroll:!0})})}function Oc(e,t){for(let e of rn)e.inert=!1;if(rn.clear(),!(!e||!u(nn)||!t))for(let e of u(nn).children)!(e instanceof HTMLElement)||e===t||e.inert||(e.inert=!0,rn.add(e))}function kc(e){if(!u(Zt)||!u(jr)||e.key!==`Tab`||!u(tn))return;let t=Array.from(u(tn).querySelectorAll(`a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])`)).filter(e=>!e.inert&&e.getClientRects().length>0);if(t.length===0){e.preventDefault(),u(tn).focus();return}let n=t[0],r=t[t.length-1];e.shiftKey&&(document.activeElement===n||!u(tn).contains(document.activeElement))?(e.preventDefault(),r.focus()):!e.shiftKey&&(document.activeElement===r||!u(tn).contains(document.activeElement))&&(e.preventDefault(),n.focus())}function Ac(e){let t=e.target;t instanceof HTMLImageElement&&t.closest(`.markdown`)&&(e.preventDefault(),Tc(Ge(t),t.alt||`Image`))}function jc(){if(u(Zt)){Dc();return}if(u(Ft)){M(Ft,!1),Yi();return}ca(),et.cancel($(),`thread`),Xi(),Yi()}function Mc(){if(Q.root){jc();return}u(Me)&&jc(),M(Kt,{kind:`ephemeral`,text:`Pick a message to open its thread.`})}async function Nc(){let e=u(X),t=++Bt,n=()=>t===Bt&&e===u(X)&&!u(Z);if(!e||u(Z)){M(It,[]),M(Rt,``),M(Lt,!1);return}M(Lt,!0),M(Rt,``);try{await dr.run(()=>G(`/api/channels/${e}/pins?limit=100`),e=>{M(It,e.messages.filter(e=>!e.deleted_at))},n)}catch(e){if(!n())return;M(Rt,e instanceof Error?e.message:`Could not load pinned messages`)}finally{n()&&M(Lt,!1)}}async function Pc(e,t){let n=u(X);if(!n||u(Z))throw Error(`Pins are available in channels only`);t?await G(`/api/channels/${n}/pins/${e.id}`,{method:`DELETE`}):await G(`/api/channels/${n}/pins`,{method:`POST`,body:JSON.stringify({message_id:e.id})}),n===u(X)&&!u(Z)&&await Nc()}function Fc(){if(!u(X)||u(Z))return;let e=!u(Ft);qs(),Xi(),M(Ft,e),Yi(),e&&Nc()}async function Ic(e){Gr++,M(Ft,!1),await As(e.thread_root_id,e.parent_message_id?void 0:e)&&u(Y)&&Q.root?.route_id&&window.location.pathname!==Hi(u(Y),Q.root.id)&&await qi(u(Y),Q.root.id)}function Lc(e){if(!(e.isComposing||e.keyCode===229)&&(kc(e),!e.defaultPrevented)){if(e.key===`Escape`){if(e.target instanceof Element&&e.target.closest(`[data-handles-escape]`)||u(Xt))return;if(Ls())Rc();else if(u(Ar)){e.preventDefault(),zc();return}else if(u(Zt)){e.preventDefault(),jc();return}else if(u(vn)){e.preventDefault(),jc();return}else if(u(Ne)){e.preventDefault(),qs();return}else if(u(Mr)||Q.draft?.quote){e.preventDefault(),Q.draft?.quote&&(u(Ir)===`thread`||!u(Mr))?Q.setQuote(null):zs();return}else{e.preventDefault(),hs();return}}if(u(Ar)&&e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey){let t=document.activeElement;if(!(t instanceof HTMLInputElement)&&!(t instanceof HTMLTextAreaElement)&&!(t instanceof HTMLSelectElement)&&!(t instanceof HTMLElement&&t.isContentEditable)){e.preventDefault();return}}$t(e,{authRequired:u(Ln),isModalOpen:()=>Ls()||u(Ar),messageInput:u(Pr),replyInput:u(Fr),target:Rs})}}function Rc(){u(ui)&&u(li).has(u(ui).id)||u(Dn)||(ca(),M(ui,null),M(di,``),M(Xt,null),M(wn,!1),M(En,!1),M(On,``))}function zc(){M(Ar,!1)}function Bc(){if(u(jr)){M(Ar,!u(Ar));return}M(kr,!u(kr))}V(()=>a(),()=>{M(C,a().replies)}),V(()=>(u(Sn),u(Y)),()=>{u(Sn)&&u(Sn)!==u(Y)&&$s()}),V(()=>(u(nt),u(Y)),()=>{M(T,u(nt).find(e=>e.id===u(Y)))}),V(()=>u(T),()=>{M(A,u(T)?.role||``)}),V(()=>u(A),()=>{M(j,u(A)===`owner`)}),V(()=>(u(Pt),u(Vt)),()=>{M(F,u(Pt)?u(Vt).find(e=>e.user.id===u(Pt)?.id):void 0)}),V(()=>(u(q),u(X)),()=>{M(I,u(q).find(e=>e.id===u(X)))}),V(()=>(u(I),u(A)),()=>{M(R,!!u(I)&&(u(A)===`owner`||u(A)===`moderator`))}),V(()=>(u(rt),u(X)),()=>{M(ie,hi(u(rt),u(X)))}),V(()=>(u(ie),u(Et)),()=>{M(U,u(ie).find(e=>e.id===u(Et)))}),V(()=>(u(X),u(Z)),()=>{Da(u(X),u(Z))}),V(()=>(u(J),u(Z)),()=>{M(W,u(J).find(e=>e.id===u(Z)))}),V(()=>u(W),()=>{M(me,u(W)?.can_send??!0)}),V(()=>(u(Z),u(X)),()=>{M(Er,u(Z)||u(X)||``)}),V(()=>u(Er),()=>{fi(u(Er))}),V(()=>u(Er),()=>{Ca(u(Er))}),V(()=>(u(X),u(Gt),u(W)),()=>{M(ye,u(X)?u(Gt):u(W)?u(Gt).filter(e=>u(W)?.members?.some(t=>t.id===e.bot.id)):[])}),V(()=>(u(Z),u(J),u(X),u(q)),()=>{M(Se,u(Z)?u(J).find(e=>e.id===u(Z))||{}:u(X)&&u(q).find(e=>e.id===u(X))||{})}),V(()=>(u(Er),u(Se)),()=>{M(we,Po(u(Er),u(Se)))}),V(()=>(u(In),u(q),u(J)),()=>{M(Te,u(In)?u(q).reduce((e,t)=>e+(t.unread_count||0),0)+u(J).reduce((e,t)=>e+(t.unread_count||0),0):0)}),V(()=>u(Te),()=>{jt?.setUnreadCount(u(Te))}),V(()=>(u(we),u(Se)),()=>{M(Ee,u(we)>0&&u(Se).last_read_seq||0)}),V(()=>(u(we),u(Er),u(Ee),u(lr)),()=>{M(De,u(we)>0&&rs(u(Er),u(Ee),u(lr)))}),V(()=>(u(we),u(Er),u(Ee),u(lr)),()=>{M(Oe,u(we)>0?is(u(Er),u(Ee),u(lr)):``)}),V(()=>(u(pt),u(Mn),u(Nn),u(Vr)),()=>{M(ke,Ut(u(pt),{hideCommentary:u(Mn),hideToolCalls:u(Nn)},u(Vr)))}),V(()=>u(zr),()=>{M(Ae,u(zr).some(e=>e.lines.some(e=>!e.finalized)))}),V(()=>u(It),()=>{M(zt,new Set(u(It).map(e=>e.id)))}),V(()=>(u(zr),u(Gt)),()=>{M(je,Za(u(zr),u(Gt),yc))}),V(()=>(u(Zt),u(Qt),u(Er)),()=>{u(Zt)&&u(Qt)&&u(Qt)!==u(Er)&&(M(Zt,null),M(Qt,``),M(en,null))}),V(()=>(u(Ft),a(),u(Pt),u(Zt)),()=>{M(Me,u(Ft)||a().selection!==null||u(Pt)!==null||u(Zt)!==null)}),V(()=>(u(_n),u(vn)),()=>{M(Ne,u(_n)!==null&&!u(vn))}),V(()=>(u(jr),u(Zt),u(tn)),()=>{Oc(u(jr)&&u(Zt)!==null,u(tn))}),V(()=>(u(pt),u(J),u(K)),()=>{M(Pe,st(u(pt),u(J),u(K)?.id||``))}),V(()=>(u(K),u(Pe),u(Ht),u(W)),()=>{M(Jt,ut(u(K),u(Pe),u(Ht),u(W)))}),V(()=>(u(K),u(Z),u(X),u(ot)),()=>{M(Yt,u(K)?.id&&(u(Z)||u(X)&&u(ot)!==null&&u(ot)!==`muted`)?u(K).id:``)}),V(()=>(u(Nr),u(Mr),u(pt)),()=>{u(Nr)===`channel`&&u(Mr)&&!u(pt).some(e=>e.id===u(Mr)?.id)&&zs()}),V(()=>(u(Nr),u(Mr),u(pt)),()=>{u(Nr)===`dm`&&u(Mr)&&!u(pt).some(e=>e.id===u(Mr)?.id)&&zs()}),V(()=>(u(In),c(Je()),c(Ye())),()=>{u(In)&&Ji(Je(),Ye())}),ne(),re();var Vc=s();r(`1oa2eo8`,e=>{var t=io();p(e,t)}),v(`keydown`,E,Lc,!0),v(`pointerdown`,E,function(...e){qt?.apply(this,e)},!0);var Hc=ce(Vc),Uc=e=>{var r=po(),i=ce(r),a=e=>{var t=ao();N(()=>B(t,`data-platform`,(c(jt),b(()=>jt.platform)))),p(e,t)};P(i,e=>{We&&jt&&e(a)});var o=k(i,2),s=L(o),l=L(s),f=L(l);Xe(f,{class:`mark`,size:44}),ee(2),t(l);var m=k(l,2),h=k(L(m),2),g=D(h,!0);t(m);var _=k(m,2),y=e=>{var n=oo(),r=L(n),i=k(L(r),2);O(i),t(r);var a=k(r,2),o=k(L(a),2);O(o),t(a);var s=k(a,2),c=D(s,!0);t(n),N(()=>{s.disabled=u(Kn),d(c,u(Kn)?`Signing in...`:`Sign in`)}),v(`submit`,n,bi),se(i,()=>u(Hn),e=>M(Hn,e)),se(o,()=>u(Un),e=>M(Un,e)),p(e,n)};P(_,e=>{Vn&&e(y)});var x=k(_,2),S=e=>{var t=co(),r=ce(t),i=e=>{var t=so();p(e,t)};P(r,e=>{Vn&&e(i)});var a=k(r,2);N(e=>B(a,`href`,e),[()=>(c(he),b(()=>he(`/api/auth/github/start`)))]),n(`click`,a,vi),p(e,t)};P(x,e=>{Bn&&e(S)});var C=k(x,2),w=e=>{var t=lo();N(e=>B(t,`href`,e),[()=>(c(he),b(()=>he(`/api/auth/openclaw/start`)))]),p(e,t)};P(C,e=>{jt||e(w)});var T=k(C,2),E=e=>{var t=uo(),n=D(t,!0);N(()=>d(n,u(Yn))),p(e,t)};P(T,e=>{u(Yn)&&e(E)});var A=k(T,2),j=k(L(A),2),F=L(j),I=k(L(F),2);O(I),t(F);var R=k(F,2);t(j),t(A);var z=k(A,2),te=e=>{var t=fo(),n=D(t,!0);N(()=>d(n,u(Rn)||$n)),p(e,t)};P(z,e=>{(u(Rn)||$n)&&e(te)}),t(s),t(o),N(()=>{d(g,Qn),A.open=!Bn&&!Vn,R.disabled=u(Kn)}),v(`submit`,j,xi),se(I,()=>u(Gn),e=>M(Gn,e)),p(e,r)},Wc=e=>{var r=Eo(),i=ce(r);let o;var s=L(i),l=e=>{{let t=H(()=>u(I)?u(ot):null),n=H(()=>(u(W),c(ct),u(K),u(I),c(_t),b(()=>u(W)?`@${ct(u(W),u(K)?.id)}`:u(I)?`#${_t(u(I))}`:void 0))),r=H(()=>(u(W),u(I),b(()=>u(W)?void 0:u(I)?.external_url))),i=H(()=>(u(I),b(()=>!!u(I)))),a=H(()=>(u(T),b(()=>u(T)?.name)));Fa(e,{get channelNotifPreference(){return u(t)},get channelNotifSaving(){return u(ft)},get pinnedOpen(){return u(Ft)},get channelTitle(){return u(n)},get externalURL(){return u(r)},get pinsAvailable(){return u(i)},get channelSettingsAvailable(){return u(R)},get connected(){return u(er)},get platform(){return c(jt),b(()=>jt.platform)},get searchQuery(){return u(gn)},get sidebarCollapsed(){return u(kr)},get mobileNavOpen(){return u(Ar)},get mobileNavigation(){return u(jr)},get workspaceName(){return u(a)},onOpenChannelSettings:Ni,onOpenWorkspaceSettings:Mi,onResetSearch:qs,onSearch:()=>void Ws(),onSearchQuery:e=>M(gn,e),onToggleSidebar:Bc,onToggleChannelNotifications:()=>void Oa(),onPinnedItems:Fc})}};P(s,e=>{We&&jt&&e(l)});var h=k(s,2),g=L(h),_=e=>{var t=m(`×`);p(e,t)},v=e=>{var t=mo();p(e,t)};P(g,e=>{u(Ar)?e(_):e(v,-1)}),t(h);var y=k(h,2),S=e=>{var t=ho();n(`click`,t,zc),p(e,t)};P(y,e=>{u(Ar)&&e(S)});var E=k(y,2);{let e=H(()=>(u(Ke),b(()=>We&&u(Ke).url===`/`?`/app`:u(Ke).url))),t=H(()=>(c(kt),u(Ke),b(()=>kt(u(Ke))))),n=H(()=>u(dn)===`workspace`);vr(E,{get workspaces(){return u(nt)},get homeHref(){return u(e)},get homeLabel(){return u(Ke),b(()=>u(Ke).label)},get homeTitle(){return u(t)},get selectedWorkspaceID(){return u(Y)},get workspaceName(){return u(on)},get showWorkspaceCreate(){return u(Or)},get createPending(){return u(n)},get createError(){return u(fn)},hrefForWorkspace:e=>Hi(e),onSelectWorkspace:e=>void pa(e),onToggleWorkspaceCreate:la,onWorkspaceName:e=>M(on,e),onCreateWorkspace:()=>void fa()})}var O=k(E,2);{let e=H(()=>(u(T),b(()=>u(T)?.name))),t=H(()=>(u(T),c(_e),b(()=>u(T)?.icon_url?_e(u(T).icon_url):``))),n=H(()=>!We),r=H(()=>(u(si),b(()=>u(si)?.title)));Wr(O,{get workspaceID(){return u(Y)},get workspaceName(){return u(e)},get workspaceIconURL(){return u(t)},get connected(){return u(er)},get sidebarCollapsed(){return u(kr)},get showHeader(){return u(n)},get channels(){return u(q)},get directConversations(){return u(J)},get recentPeople(){return u(Pe)},get currentUser(){return u(K)},get selectedChannelID(){return u(X)},get selectedDirectID(){return u(Z)},get selectedProfile(){return u(Pt)},onToggleCollapse:Bc,hrefForChannel:e=>Hi(u(Y),e),hrefForDirect:e=>Hi(u(Y),e),onSelectChannel:e=>void Ea(e),onCreateChannel:ua,onSelectDirect:e=>void rc(e),onCreateDirect:da,onHideDirect:e=>void cc(e),get hiddenDirectTitle(){return u(r)},onUndoHideDirect:()=>void sc(),onOpenProfile:Sc,onOpenSettings:ji,onOpenWorkspaceSettings:Mi})}var ee=k(O,2),z=L(ee),te=e=>{{let t=H(()=>(u(T),b(()=>u(T)?.name))),n=H(()=>(u(K),b(()=>u(K)?.id))),r=H(()=>(a(),b(()=>a().root!==null)));Ja(e,{get selectedDirect(){return u(W)},get selectedChannel(){return u(I)},get workspaceName(){return u(t)},get currentUserID(){return u(n)},get searchQuery(){return u(gn)},get threadOpen(){return u(r)},get pinnedOpen(){return u(Ft)},get channelNotifPreference(){return u(ot)},get channelNotifSaving(){return u(ft)},get channelSettingsAvailable(){return u(R)},onSearchQuery:e=>M(gn,e),onSearch:()=>void Ws(),onResetSearch:qs,onToggleThread:Mc,onToggleChannelNotifications:()=>void Oa(),onPinnedItems:Fc,onOpenChannelSettings:Ni})}};P(z,e=>{We||e(te)});var ne=k(z,2),re=e=>{var r=go(),i=L(r),a=k(L(i)),o=D(a,!0);t(i);var s=k(i,2);t(r),N(()=>d(o,(u(U),b(()=>u(U).name)))),n(`click`,s,()=>void La(``)),p(e,r)};P(ne,e=>{u(U)&&e(re)});var ae=k(ne,2);{let e=H(()=>u(pr)!==`idle`),t=H(()=>(a(),b(()=>a().root?.id))),n=H(()=>(u(K),b(()=>u(K)?.id))),r=H(()=>(u(W),u(me),b(()=>!!(u(W)&&!u(me))))),i=H(()=>u(j)&&!u(Z));ht(ae,{get channelID(){return u(X)},get pinnedMessageIDs(){return u(zt)},onTogglePin:Pc,onCopyLink:Ui,get messages(){return u(ke)},get selectedDirect(){return u(W)},get selectedChannel(){return u(I)},get mentionPeople(){return u(Jt)},get mentionAttentionUserID(){return u(Yt)},get restoreState(){return u(Tr)},get viewKey(){return u(wr)},get loading(){return u(Dr)},get unreadCount(){return u(we)},get unreadBoundarySeq(){return u(Ee)},get unreadBoundaryLoaded(){return u(De)},get unreadSince(){return u(Oe)},get hasOlder(){return u(_r)},get hasNewer(){return u(yr)},get loadingOlder(){return u(br)},get loadingNewer(){return u(xr)},get prepending(){return u(e)},get selectedThreadID(){return u(t)},get currentUserID(){return u(n)},get reactionController(){return Ze},get reactionsDisabled(){return u(r)},get canDeleteAnyMessage(){return u(i)},get deletingMessageIDs(){return u(li)},onListRef:e=>M(sr,e),onActivateMessageComposer:ga,onInlineImagePointerUp:Ac,onOpenProfile:Sc,onReply:Is,onOpenThread:ks,onJumpToQuote:e=>void Bs(e),onOpenImage:Tc,onOpenArtifact:Ec,onLoadOlder:$a,onLoadNewer:e=>ro(e===`wheel`),onJumpToUnread:()=>void Vs(),onHistorySettled:jo,onReachedBottom:zo,onMarkRead:e=>{zo({all:!0,seq:e})},onRetry:Cs,onDiscard:ws,onDeleteMessage:Ds,get editController(){return et},get editScope(){return u(Er)},onMessageEdited:Es,get topics(){return u(rt)},onSelectTopic:e=>void La(e)})}var V=k(ae,2);tr(V,{get turns(){return u(zr)}});var se=k(V,2);{let e=H(()=>(u(K),b(()=>u(K)?.id)));Xn(se,{get entries(){return u(Lr)},get currentUserID(){return u(e)}})}var ue=k(se,2),de=L(ue);{let e=H(()=>(u(Ae),a(),b(()=>u(Ae)&&a().root===null)));vt(de,{get active(){return u(e)},get agentNames(){return u(je)}})}var fe=k(de,2),pe=e=>{var t=_o(),n=D(t);N(()=>d(n,`Live updates: ${u(nr)??``}`)),p(e,t)};P(fe,e=>{u(nr)&&e(pe)});var he=k(fe,2),ge=e=>{var t=_o(),n=D(t);N(()=>d(n,`Mentions unavailable: ${u(ti)??``}`)),p(e,t)};P(he,e=>{u(ti)&&e(ge)});var ve=k(he,2),G=e=>{var r=vo();let i;var a=L(r),o=D(a,!0),s=k(a,2),c=D(s,!0),l=k(s,2);t(r),N(()=>{i=w(r,1,`composer-notice`,null,i,{"composer-notice--error":u(Kt).kind===`error`}),d(o,(u(Kt),b(()=>u(Kt).kind===`ephemeral`?`Only visible to you`:`Action failed`))),d(c,(u(Kt),b(()=>u(Kt).text)))}),n(`click`,l,()=>M(Kt,null)),p(e,r)};P(ve,e=>{u(Kt)&&e(G)});var be=k(ve,2),xe=e=>{var r=bo(),i=k(L(r),2),a=L(i);a.value=a.__value=``;var o=k(a);f(o,1,()=>u(ie),e=>e.id,(e,t)=>{var n=yo(),r=D(n,!0),i={};N(()=>{d(r,(u(t),b(()=>u(t).name))),i!==(i=(u(t),b(()=>u(t).id)))&&(n.value=(n.__value=i)??``)}),p(e,n)}),t(i);var s;x(i),t(r),N(()=>{s!==(s=u(St))&&(i.value=(i.__value=s)??``,le(i,s))}),n(`change`,i,e=>M(St,e.currentTarget.value)),p(e,r)};P(be,e=>{u(X),u(ie),b(()=>u(X)&&u(ie).length>0)&&e(xe)});var Se=k(be,2);{let e=H(()=>(u(W),u(me),c(ct),u(K),u(I),c(_t),b(()=>u(W)&&!u(me)?`No active recipient`:u(W)?`Message ${ct(u(W),u(K)?.id)}`:u(I)?`Message #${_t(u(I))}`:`Pick a channel to start`))),t=H(()=>!!u(W)&&!u(me)),n=H(()=>u(Mr)&&u(Nr)===(u(Z)?`dm`:`channel`)?u(Mr):null),r=H(()=>u(X)?u(Wt):[]);at(Se,{get value(){return u(an)},get placeholder(){return u(e)},ariaLabel:`Message body`,submitLabel:`Send`,get disabled(){return u(t)},get pendingUpload(){return u(xn)},get replyTarget(){return u(n)},showUpload:!0,showToolbar:!0,get slashCommands(){return u(r)},get botCommands(){return u(ye)},get mentionPeople(){return u(Jt)},onValue:e=>{let t=u(an);M(an,e),e.trim()&&e!==t?xc():e.trim()||ln()},onSubmit:()=>void _s(),onKeydown:Cc,onFocus:ga,onInputRef:e=>M(Pr,e),onUploadFile:ec,onRemoveUpload:$s,onClearReply:zs})}t(ue),t(ee);var Ce=k(ee,2),Te=e=>{var n=xo();Wn(L(n),{get upload(){return u(Zt)},onClose:Dc}),t(n),oe(n,e=>M(tn,e),()=>u(tn)),N(()=>{n.inert=u(Ar),B(n,`role`,u(jr)?`dialog`:`complementary`),B(n,`aria-modal`,u(jr)?`true`:void 0)}),p(e,n)};P(Ce,e=>{u(Zt)&&e(Te)});var Fe=k(Ce,2),Ie=e=>{{let t=H(()=>u(Zt)!==null),n=H(()=>u(Ar)||u(Zt)!==null);_i(e,{get session(){return u(_n)},get covered(){return u(t)},get inert(){return u(n)},contextFor:Js,onClose:qs,onOpenResult:e=>void Ys(e),onLoadMore:()=>void Ks()})}},Le=e=>{var r=To();let i;var o=L(r),s=e=>{ei(e,{get messages(){return u(It)},get loading(){return u(Lt)},get error(){return u(Rt)},get topics(){return u(rt)},get mentionPeople(){return u(Jt)},get mentionAttentionUserID(){return u(Yt)},onClose:jc,onOpenThread:e=>void Ic(e),onOpenImage:Tc,onOpenArtifact:Ec,onUnpin:e=>Pc(e,!0),onSelectTopic:e=>{M(Ft,!1),La(e)}})},c=e=>{{let t=H(()=>(a(),b(()=>a().draft?.body??``))),n=H(()=>(a(),b(()=>a().draft?.quote??null))),r=H(()=>(a(),b(()=>a().draft?.error||a().error))),i=H(()=>(a(),b(()=>a().draft?.sending??!1))),o=H(()=>(u(W),u(me),b(()=>!!(u(W)&&!u(me))))),s=H(()=>u(vn)&&u(_n)?()=>void Xs():void 0),c=H(()=>(u(K),b(()=>u(K)?.id))),l=H(()=>(u(W),u(me),b(()=>!!(u(W)&&!u(me))))),d=H(()=>u(j)&&!u(Z));bt(e,{get history(){return Q},get root(){return a(),b(()=>a().root)},get replies(){return u(C)},get threadState(){return a(),b(()=>a().state)},get replyBody(){return u(t)},get replyTarget(){return u(n)},get replyError(){return u(r)},get replySending(){return u(i)},get mentionPeople(){return u(Jt)},get mentionAttentionUserID(){return u(Yt)},get agentResponding(){return u(Ae)},get respondingAgentNames(){return u(je)},get replyDisabled(){return u(o)},onClose:jc,get onBack(){return u(s)},onReplyBody:e=>Q.updateDraft(e),onSubmitReply:()=>void Fs(),onReplyKeydown:wc,onReplyFocus:()=>M(Ir,`thread`),onReplyInputRef:e=>M(Fr,e),get currentUserID(){return u(c)},get reactionController(){return Ze},get reactionsDisabled(){return u(l)},onSetReplyTarget:Is,onClearReply:()=>Q.setQuote(null),get canDeleteAnyMessage(){return u(d)},get deletingMessageIDs(){return u(li)},onDeleteMessage:Ds,get channelID(){return u(X)},get pinnedMessageIDs(){return u(zt)},onTogglePin:Pc,onCopyLink:Ui,get editController(){return et},get editScope(){return u(Er)},onMessageEdited:Es,onActivateThreadComposer:()=>M(Ir,`thread`),onInlineImagePointerUp:Ac,onJumpToQuote:e=>void Bs(e),onOpenImage:Tc,onOpenArtifact:Ec})}},l=e=>{var r=wo(),i=ce(r),o=k(L(i),2);t(i);var s=k(i,2),c=e=>{var t=So(),r=ce(t),i=D(r,!0),o=k(r,2);N(()=>d(i,(a(),b(()=>a().error)))),n(`click`,o,()=>a().selection&&void As(a().selection.messageID)),p(e,t)},l=e=>{var t=Co();p(e,t)};P(s,e=>{a(),b(()=>a().error)?e(c):e(l,-1)}),n(`click`,o,jc),p(e,r)},f=e=>{{let t=H(()=>(u(T),b(()=>u(T)?.name))),n=H(()=>u(dn)===`direct`);gt(e,{get profile(){return u(Pt)},get currentUser(){return u(K)},get workspaceName(){return u(t)},get currentUserRole(){return u(A)},get moderation(){return u(F)},onClose:jc,onEdit:ji,get messagePending(){return u(n)},get messageError(){return u(mn)},onMessage:e=>void ic(e),onApprove:e=>void wa(e,{role:`member`,clear_timeout:!0,blocked:!1}),onTimeout:e=>void wa(e,{timeout_minutes:60}),onBlock:e=>void wa(e,{blocked:!0}),onUnblock:e=>void wa(e,{blocked:!1,clear_timeout:!0})})}},m=e=>{Sa(e,{})};P(o,e=>{u(Ft)?e(s):(a(),b(()=>a().root)?e(c,1):(a(),b(()=>a().selection)?e(l,2):u(Pt)?e(f,3):e(m,-1)))}),t(r),N(()=>{i=w(r,1,`thread`,null,i,{open:u(Me),covered:u(Zt)!==null}),r.inert=u(Ar)||u(Zt)!==null,B(r,`aria-hidden`,u(Zt)?`true`:void 0),B(r,`aria-label`,u(Ft)?`Pinned messages pane`:u(Pt)?`Profile pane`:`Thread pane`)}),p(e,r)};P(Fe,e=>{u(Ne)&&u(_n)?e(Ie):e(Le,-1)}),t(i),oe(i,e=>M(nn,e),()=>u(nn));var Re=k(i,2),ze=e=>{{let t=H(()=>jt!=null);ba(e,{get user(){return u(K)},get workspaces(){return u(nt)},get initialSection(){return u(Tn)},get hideCommentary(){return u(Mn)},get hideToolCalls(){return u(Nn)},get userAlign(){return u(Pn)},get otherAlign(){return u(Fn)},get isDesktop(){return u(t)},onUserUpdated:Fi,onHideCommentary:Di,onHideToolCalls:Oi,onUserAlign:Ti,onOtherAlign:Ei,onBrowserNotificationsChanged:e=>M(jn,e),onClose:Rc})}};P(Re,e=>{u(wn)&&u(K)&&e(ze)});var Be=k(Re,2),Ve=e=>{Ci(e,{get channel(){return u(I)},get saving(){return u(Dn)},get error(){return u(On)},onClose:Rc,onArchivedChange:e=>void Pi(e)})};P(Be,e=>{u(En)&&u(I)&&e(Ve)});var He=k(Be,2),Ue=e=>{{let t=H(()=>u(dn)===`channel`);ir(e,{get channelName(){return u(cn)},get pending(){return u(t)},get error(){return u(pn)},onChannelName:e=>M(cn,e),onClose:Rc,onCreate:()=>void Ta()})}};P(He,e=>{u(kn)&&e(Ue)});var Ge=k(He,2),qe=e=>{{let t=H(()=>(u(K),b(()=>u(K)?.id))),n=H(()=>u(dn)===`direct`),r=H(()=>u(mn)||u(ti));ur(e,{get people(){return u(Jt)},get currentUserID(){return u(t)},get memberID(){return u(un)},get pending(){return u(n)},get error(){return u(r)},onMemberID:e=>M(un,e),onClose:Rc,onStart:e=>void ic(e)})}};P(Ge,e=>{u(An)&&e(qe)});var Je=k(Ge,2),Ye=e=>{{let t=H(()=>(u(li),u(ui),b(()=>u(li).has(u(ui).id))));qn(e,{get message(){return u(ui)},get deleting(){return u(t)},get error(){return u(di)},onClose:Rc,onConfirm:()=>void Os()})}};P(Je,e=>{u(ui)&&e(Ye)});var Xe=k(Je,2),Qe=e=>{tt(e,{get url(){return u(Xt),b(()=>u(Xt).url)},get title(){return u(Xt),b(()=>u(Xt).title)},onClose:Rc})};P(Xe,e=>{u(Xt)&&e(Qe)}),N(()=>{o=w(i,1,`shell`,null,o,{"desktop-shell":We,"nav-open":u(Ar),"sidebar-collapsed":u(kr),"thread-open":u(Me)&&!u(Ne),"search-open":u(Ne),"artifact-open":u(Zt)!==null}),B(i,`data-connected`,u(er)),B(i,`data-app-ready`,u(er)&&u(In)),B(h,`aria-expanded`,u(Ar)),ee.inert=u(Ar)}),n(`click`,h,()=>M(Ar,!u(Ar))),p(e,r)};P(Hc,e=>{u(Ln)?e(Uc):e(Wc,-1)}),p(e,Vc),_(),h()}W([`click`,`change`]);export{ro as n,Do as t}; \ No newline at end of file diff --git a/apps/api/internal/webassets/dist/_app/immutable/chunks/CIKVmJ8v.js b/apps/api/internal/webassets/dist/_app/immutable/chunks/CIKVmJ8v.js new file mode 100644 index 000000000..7c6ff5d1b --- /dev/null +++ b/apps/api/internal/webassets/dist/_app/immutable/chunks/CIKVmJ8v.js @@ -0,0 +1,54 @@ +import{t as e}from"./HclGiUj8.js";var t=typeof process==`object`&&process+``==`[object process]`&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!==`browser`),n=[1/0,1/0,-1/0,-1/0],r=new Float32Array(n),i=[.001,0,0,.001,0,0],a=`http://www.w3.org/2000/svg`,o={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},s={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},c=`pdfjs_internal_id_`,l=`pdfjs_internal_editor_`,u={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},d={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},p={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},m={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},h={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26,RICHMEDIA:27},g={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},_={ERRORS:0,WARNINGS:1,INFOS:5},v={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},y={moveTo:0,lineTo:1,curveTo:2,quadraticCurveTo:3,closePath:4},b={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},x=_.WARNINGS;function S(e){Number.isInteger(e)&&(x=e)}function C(){return x}function w(e){x>=_.INFOS&&console.info(`Info: ${e}`)}function T(e){x>=_.WARNINGS&&console.warn(`Warning: ${e}`)}function E(e){throw Error(e)}function D(e,t){e||E(t)}function O(e){switch(e?.protocol){case`http:`:case`https:`:case`ftp:`:case`mailto:`:case`tel:`:return!0;default:return!1}}function k(e,t=null,n=null){if(!e)return null;if(n&&typeof e==`string`&&(n.addDefaultProtocol&&e.startsWith(`www.`)&&e.match(/\./g)?.length>=2&&(e=`http://${e}`),n.tryConvertEncoding))try{e=se(e)}catch{}let r=t?URL.parse(e,t):URL.parse(e);return O(r)?r:null}function A(e,t,n=!1){let r=URL.parse(e);return r?(r.hash=t,r.href):n&&k(e,`http://example.com`)?e.split(`#`,1)[0]+`${t?`#${t}`:``}`:``}function j(e){return e.substring(e.lastIndexOf(`/`)+1)}function M(e,t,n,r=!1){return Object.defineProperty(e,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}var N=function(){function e(e,t){this.message=e,this.name=t}return e.prototype=Error(),e.constructor=e,e}(),ee=class extends N{constructor(e,t){super(e,`PasswordException`),this.code=t}},te=class extends N{constructor(e,t){super(e,`UnknownErrorException`),this.details=t}},ne=class extends N{constructor(e){super(e,`InvalidPDFException`)}},re=class extends N{constructor(e,t,n){super(e,`ResponseException`),this.status=t,this.missing=n}},ie=class extends N{constructor(e){super(e,`FormatError`)}},P=class extends N{constructor(e){super(e,`AbortException`)}};function ae(e){(typeof e!=`object`||e?.length===void 0)&&E(`Invalid argument for bytesToString`);let t=e.length,n=8192;if(t`u`)return M(this,`isAlphaColorInputSupported`,!1);let e=document.createElement(`input`);return e.type=`color`,e.setAttribute(`alpha`,``),e.value=`#ff000080`,M(this,`isAlphaColorInputSupported`,e.value!==`#ff0000`)}static get isBackdropFilterSupported(){return M(this,`isBackdropFilterSupported`,typeof CSS<`u`&&CSS.supports(`backdrop-filter`,`blur(1px)`))}},I=class{static get hexNums(){return M(this,`hexNums`,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)))}static makeHexColor(e,t,n){return`#${this.hexNums[e]}${this.hexNums[t]}${this.hexNums[n]}`}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static multiplyByDOMMatrix(e,t){return[e[0]*t.a+e[2]*t.b,e[1]*t.a+e[3]*t.b,e[0]*t.c+e[2]*t.d,e[1]*t.c+e[3]*t.d,e[0]*t.e+e[2]*t.f+e[4],e[1]*t.e+e[3]*t.f+e[5]]}static applyTransform(e,t,n=0){let r=e[n],i=e[n+1];e[n]=r*t[0]+i*t[2]+t[4],e[n+1]=r*t[1]+i*t[3]+t[5]}static applyTransformToBezier(e,t,n=0){let r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5];for(let t=0;t<6;t+=2){let l=e[n+t],u=e[n+t+1];e[n+t]=l*r+u*a+s,e[n+t+1]=l*i+u*o+c}}static applyInverseTransform(e,t){let n=e[0],r=e[1],i=t[0]*t[3]-t[1]*t[2];e[0]=(n*t[3]-r*t[2]+t[2]*t[5]-t[4]*t[3])/i,e[1]=(-n*t[1]+r*t[0]+t[4]*t[1]-t[5]*t[0])/i}static axialAlignedBoundingBox(e,t,n){let r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=e[0],u=e[1],d=e[2],f=e[3],p=r*l+s,m=p,h=r*d+s,g=h,_=o*u+c,v=_,y=o*f+c,b=y;if(i!==0||a!==0){let e=i*l,t=i*d,n=a*u,r=a*f;p+=n,g+=n,h+=r,m+=r,_+=e,b+=e,y+=t,v+=t}n[0]=Math.min(n[0],p,h,m,g),n[1]=Math.min(n[1],_,y,v,b),n[2]=Math.max(n[2],p,h,m,g),n[3]=Math.max(n[3],_,y,v,b)}static inverseTransform(e){let t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e,t){let n=e[0],r=e[1],i=e[2],a=e[3],o=n**2+r**2,s=n*i+r*a,c=i**2+a**2,l=(o+c)/2,u=Math.sqrt(l**2-(o*c-s**2));t[0]=Math.sqrt(l+u||1),t[1]=Math.sqrt(l-u||1)}static normalizeRect(e){let t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){let n=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(n>r)return null;let i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>a?null:[n,i,r,a]}static pointBoundingBox(e,t,n){n[0]=Math.min(n[0],e),n[1]=Math.min(n[1],t),n[2]=Math.max(n[2],e),n[3]=Math.max(n[3],t)}static rectBoundingBox(e,t,n,r,i){i[0]=Math.min(i[0],e,n),i[1]=Math.min(i[1],t,r),i[2]=Math.max(i[2],e,n),i[3]=Math.max(i[3],t,r)}static#e(e,t,n,r,i,a,o,s,c,l){if(c<=0||c>=1)return;let u=1-c,d=c*c,f=d*c,p=u*(u*(u*e+3*c*t)+3*d*n)+f*r,m=u*(u*(u*i+3*c*a)+3*d*o)+f*s;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],m),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],m)}static#t(e,t,n,r,i,a,o,s,c,l,u,d){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,n,r,i,a,o,s,-u/l,d);return}let f=l**2-4*u*c;if(f<0)return;let p=Math.sqrt(f),m=2*c;this.#e(e,t,n,r,i,a,o,s,(-l+p)/m,d),this.#e(e,t,n,r,i,a,o,s,(-l-p)/m,d)}static bezierBoundingBox(e,t,n,r,i,a,o,s,c){c[0]=Math.min(c[0],e,o),c[1]=Math.min(c[1],t,s),c[2]=Math.max(c[2],e,o),c[3]=Math.max(c[3],t,s),this.#t(e,n,i,o,t,r,a,s,3*(-e+3*(n-i)+o),6*(e-2*n+i),3*(n-e),c),this.#t(e,n,i,o,t,r,a,s,3*(-t+3*(r-a)+s),6*(t-2*r+a),3*(r-t),c)}};function se(e){return decodeURIComponent(escape(e))}var ce=null,le=null;function ue(e){return ce||(ce=/([\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,le=new Map([[`ſt`,`ſt`]])),e.replaceAll(ce,(e,t,n)=>t?t.normalize(`NFKC`):le.get(n))}function de(){if(typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=new Uint8Array(32);return crypto.getRandomValues(e),ae(e)}function fe(e,t,n){if(!Array.isArray(n)||n.length<2)return!1;let[r,i,...a]=n;if(!e(r)&&!Number.isInteger(r)||!t(i))return!1;let o=a.length,s=!0;switch(i.name){case`XYZ`:if(o<2||o>3)return!1;break;case`Fit`:case`FitB`:return o===0;case`FitH`:case`FitBH`:case`FitV`:case`FitBV`:if(o>1)return!1;break;case`FitR`:if(o!==4)return!1;s=!1;break;default:return!1}for(let e of a)if(!(typeof e==`number`||s&&e===null))return!1;return!0}var pe=()=>[],me=()=>new Map,he=()=>Object.create(null),ge=()=>new Set;typeof Iterator.prototype.join!=`function`&&(Iterator.prototype.join=function(e){return[...this].join(e)});function L(e,t,n){return Math.min(Math.max(e,t),n)}var _e=class e{constructor({viewBox:e,userUnit:t,scale:n,rotation:r,offsetX:i=0,offsetY:a=0,dontFlip:o=!1}){this.viewBox=e,this.userUnit=t,this.scale=n,this.rotation=r,this.offsetX=i,this.offsetY=a,n*=t;let s=(e[2]+e[0])/2,c=(e[3]+e[1])/2,l,u,d,f;switch(r%=360,r<0&&(r+=360),r){case 180:l=-1,u=0,d=0,f=1;break;case 90:l=0,u=1,d=1,f=0;break;case 270:l=0,u=-1,d=-1,f=0;break;case 0:l=1,u=0,d=0,f=-1;break;default:throw Error(`PageViewport: Invalid rotation, must be a multiple of 90 degrees.`)}o&&(d=-d,f=-f);let p,m,h,g;l===0?(p=Math.abs(c-e[1])*n+i,m=Math.abs(s-e[0])*n+a,h=(e[3]-e[1])*n,g=(e[2]-e[0])*n):(p=Math.abs(s-e[0])*n+i,m=Math.abs(c-e[1])*n+a,h=(e[2]-e[0])*n,g=(e[3]-e[1])*n),this.transform=[l*n,u*n,d*n,f*n,p-l*n*s-d*n*c,m-u*n*s-f*n*c],this.width=h,this.height=g}get rawDims(){let e=this.viewBox;return M(this,`rawDims`,{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:t=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:a=!1}={}){return new e({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:n,offsetX:r,offsetY:i,dontFlip:a})}convertToViewportPoint(e,t){let n=[e,t];return I.applyTransform(n,this.transform),n}convertToPdfPoint(e,t){let n=[e,t];return I.applyInverseTransform(n,this.transform),n}},ve=class e{static textContent(t){let n=[],r={items:n,styles:Object.create(null)};function i(t){if(!t)return;let r=null,a=t.name;if(a===`#text`)r=t.value;else if(e.shouldBuildText(a))t?.attributes?.textContent?r=t.attributes.textContent:t.value&&(r=t.value);else return;if(r!==null&&n.push({str:r}),t.children)for(let e of t.children)i(e)}return i(t),r}static shouldBuildText(e){return e!==`textarea`&&e!==`input`&&e!==`option`&&e!==`select`}},ye=/url\(|image-set\(/i,be=/^on/i,xe=class{static get _allowedHtmlElements(){return M(this,`_allowedHtmlElements`,new Set([`a`,`b`,`br`,`button`,`div`,`i`,`img`,`input`,`label`,`li`,`ol`,`option`,`p`,`select`,`span`,`sub`,`sup`,`textarea`,`ul`]))}static get _allowedSvgElements(){return M(this,`_allowedSvgElements`,new Set([`ellipse`,`line`,`path`,`rect`,`svg`]))}static get _allowedRichTextElements(){return M(this,`_allowedRichTextElements`,new Set([`a`,`b`,`br`,`div`,`i`,`li`,`ol`,`p`,`span`,`sub`,`sup`,`ul`]))}static get _allowedRichTextAttributes(){return M(this,`_allowedRichTextAttributes`,new Set([`class`,`dir`,`style`]))}static get _allowedRichTextStyles(){return M(this,`_allowedRichTextStyles`,new Set(`color.font.fontFamily.fontSize.fontStretch.fontStyle.fontWeight.kerningMode.letterSpacing.lineHeight.margin.marginBottom.marginLeft.marginRight.marginTop.orphans.paddingLeft.paddingRight.breakAfter.breakBefore.breakInside.tabInterval.tabStop.textAlign.textDecoration.textIndent.transform.verticalAlign.widows`.split(`.`)))}static setupStorage(e,t,n,r,i){let a=r.getValue(t,{value:null});switch(n.name){case`textarea`:if(a.value!==null&&(e.textContent=a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})});break;case`input`:if(n.attributes.type===`radio`||n.attributes.type===`checkbox`){if(a.value===n.attributes.xfaOn?e.setAttribute(`checked`,!0):a.value===n.attributes.xfaOff&&e.removeAttribute(`checked`),i===`print`)break;e.addEventListener(`change`,e=>{r.setValue(t,{value:e.target.checked?e.target.getAttribute(`xfaOn`):e.target.getAttribute(`xfaOff`)})})}else{if(a.value!==null&&e.setAttribute(`value`,a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})})}break;case`select`:if(a.value!==null){e.setAttribute(`value`,a.value);for(let e of n.children)e.attributes.value===a.value?e.attributes.selected=!0:Object.hasOwn(e.attributes,`selected`)&&delete e.attributes.selected}e.addEventListener(`input`,e=>{let n=e.target.options,i=n.selectedIndex===-1?``:n[n.selectedIndex].value;r.setValue(t,{value:i})})}}static setAttributes({html:e,element:t,storage:n=null,intent:r,linkService:i}){let{attributes:a}=t,o=e instanceof HTMLAnchorElement;a.type===`radio`&&(a.name=`${a.name}-${r}`);for(let[t,n]of Object.entries(a))if(n!=null&&!be.test(t)&&!(r===`richText`&&!this._allowedRichTextAttributes.has(t)))switch(t){case`class`:n.length&&e.setAttribute(t,n.join(` `));break;case`dataId`:break;case`id`:e.setAttribute(`data-element-id`,n);break;case`style`:if(r===`richText`){let t=this._allowedRichTextStyles;for(let[r,i]of Object.entries(n))t.has(r)&&!ye.test(i)&&(e.style[r]=i)}else Object.assign(e.style,n);break;case`textContent`:e.textContent=n;break;default:(!o||t!==`href`&&t!==`newWindow`)&&e.setAttribute(t,n)}o&&i?.addLinkAttributes(e,a.href,a.newWindow),n&&a.dataId&&this.setupStorage(e,a.dataId,t,n)}static#e(e,t,n){return n===`richText`?!t&&this._allowedRichTextElements.has(e)?document.createElement(e):null:t?t===a&&this._allowedSvgElements.has(e)?document.createElementNS(a,e):null:this._allowedHtmlElements.has(e)?document.createElement(e):null}static render(e){let t=e.annotationStorage,n=e.linkService,r=e.xfaHtml,i=e.intent||`display`,a=this.#e(r.name,r.attributes?.xmlns,i)??document.createElement(`div`);r.attributes&&this.setAttributes({html:a,element:r,intent:i,linkService:n});let o=i!==`richText`,s=e.div;if(s.append(a),e.viewport){let t=`matrix(${e.viewport.transform.join(`,`)})`;s.style.transform=t}o&&s.setAttribute(`class`,`xfaLayer xfaFont`);let c=[];if(r.children.length===0){if(r.value){let e=document.createTextNode(r.value);a.append(e),o&&ve.shouldBuildText(r.name)&&c.push(e)}return{textDivs:c}}let l=[[r,-1,a]];for(;l.length>0;){let[e,r,a]=l.at(-1);if(r+1===e.children.length){l.pop();continue}let s=e.children[++l.at(-1)[1]];if(s===null)continue;let{name:u}=s;if(u===`#text`){let e=document.createTextNode(s.value);c.push(e),a.append(e);continue}let d=this.#e(u,s.attributes?.xmlns,i);if(d){if(a.append(d),s.attributes&&this.setAttributes({html:d,element:s,storage:t,intent:i,linkService:n}),s.children?.length>0)l.push([s,-1,d]);else if(s.value){let e=document.createTextNode(s.value);o&&ve.shouldBuildText(u)&&c.push(e),d.append(e)}}}for(let e of s.querySelectorAll(`.xfaNonInteractive input, .xfaNonInteractive textarea`))e.setAttribute(`readOnly`,!0);return{textDivs:c}}static update(e){let t=`matrix(${e.viewport.transform.join(`,`)})`;e.div.style.transform=t,e.div.hidden=!1}static getPageViewport(e,{scale:t=1,rotation:n=0}){let{width:r,height:i}=e.attributes.style;return new _e({viewBox:[0,0,parseInt(r,10),parseInt(i,10)],userUnit:1,scale:t,rotation:n})}},Se=class{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF};async function Ce(e,t=`text`){if(Ae(e,document.baseURI)){let n=await fetch(e);if(!n.ok)throw Error(n.statusText);switch(t){case`blob`:return n.blob();case`bytes`:return n.bytes();case`json`:return n.json()}return n.text()}return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open(`GET`,e,!0),i.responseType=t===`bytes`?`arraybuffer`:t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case`bytes`:n(new Uint8Array(i.response));return;case`blob`:case`json`:n(i.response);return}n(i.responseText);return}r(Error(i.statusText))}},i.send(null)})}var we=class extends N{constructor(e,t=0){super(e,`RenderingCancelledException`),this.extraDelay=t}};function Te(e){let t=e.length,n=0;for(;n{try{return new URL(e)}catch{}try{return new URL(decodeURIComponent(e))}catch{}try{return new URL(e,`https://foo.bar`)}catch{}try{return new URL(decodeURIComponent(e),`https://foo.bar`)}catch{}return null})(e);if(!n)return t;let r=e=>{try{let t=decodeURIComponent(e);return t.includes(`/`)&&(t=j(t),t.length===4&&i.test(t))?e:t}catch{return e}},i=/\.pdf$/i,a=j(n.pathname);if(i.test(a))return r(a);if(n.searchParams.size>0){let e=e=>[...e].findLast(e=>i.test(e)),t=e(n.searchParams.values())??e(n.searchParams.keys());if(t)return r(t)}if(n.hash){let{hash:e}=n,t=-1;for(let{index:n}of e.matchAll(/\.pdf\b/gi))t=n;if(t>0){let n=t;for(;n>0&&!`/?#=`.includes(e[n-1]);)n--;if(ne.name.length));return this.times.map(t=>`${t.name.padEnd(e)} ${t.end-t.start}ms\n`).join(``)}};function Ae(e,t){let n=t?URL.parse(e,t):URL.parse(e);return/https?:/.test(n?.protocol??``)}function R(e){e.preventDefault()}function z(e){e.preventDefault(),e.stopPropagation()}var je=class{static#e;static toDateObject(e){if(e instanceof Date)return e;if(!e||typeof e!=`string`)return null;this.#e||=RegExp(`^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?`);let t=this.#e.exec(e);if(!t)return null;let n=parseInt(t[1],10),r=parseInt(t[2],10);r=r>=1&&r<=12?r-1:0;let i=parseInt(t[3],10);i=i>=1&&i<=31?i:1;let a=parseInt(t[4],10);a=a>=0&&a<=23?a:0;let o=parseInt(t[5],10);o=o>=0&&o<=59?o:0;let s=parseInt(t[6],10);s=s>=0&&s<=59?s:0;let c=t[7]||`Z`,l=parseInt(t[8],10);l=l>=0&&l<=23?l:0;let u=parseInt(t[9],10)||0;return u=u>=0&&u<=59?u:0,c===`-`?(a+=l,o+=u):c===`+`&&(a-=l,o-=u),new Date(Date.UTC(n,r,i,a,o,s))}};function Me(e){if(e.startsWith(`#`)){let t=e.slice(1);return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16),t.length>=8?parseInt(t.slice(6,8),16)/255:1]}if(e.startsWith(`rgb(`)){let[t,n,r]=e.slice(4,-1).split(`,`).map(e=>parseInt(e,10));return[t,n,r,1]}if(e.startsWith(`rgba(`)){let t=e.slice(5,-1).split(`,`);return[parseInt(t[0],10),parseInt(t[1],10),parseInt(t[2],10),parseFloat(t[3])]}let t=e.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return t?[Math.round(parseFloat(t[1])*255),Math.round(parseFloat(t[2])*255),Math.round(parseFloat(t[3])*255),t[4]!==void 0&&t[4]!==`none`?parseFloat(t[4]):1]:null}function Ne(e){let t=Me(e);return t?t.slice(0,3):(T(`Not a valid color format: "${e}"`),[0,0,0])}function Pe(e){let t=document.createElement(`span`);t.style.visibility=`hidden`,t.style.colorScheme=`only light`,document.body.append(t);for(let n of e.keys()){t.style.color=n;let r=window.getComputedStyle(t).color;e.set(n,Ne(r))}t.remove()}function B(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform();return[t,n,r,i,a,o]}function V(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform().invertSelf();return[t,n,r,i,a,o]}function Fe(e,t,n=!1,r=!0){if(t instanceof _e){let{pageWidth:r,pageHeight:i}=t.rawDims,{style:a}=e,o=`round(down, var(--total-scale-factor) * ${r}px, var(--scale-round-x))`,s=`round(down, var(--total-scale-factor) * ${i}px, var(--scale-round-y))`;!n||t.rotation%180==0?(a.width=o,a.height=s):(a.width=s,a.height=o)}r&&e.setAttribute(`data-main-rotation`,t.rotation)}var Ie=class e{constructor(){let{pixelRatio:t}=e;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(t,n,r,i,a=-1){let o=1/0,s=1/0,c=1/0;r=e.capPixels(r,a),r>0&&(o=Math.sqrt(r/(t*n))),i!==-1&&(s=i/t,c=i/n);let l=Math.min(o,s,c);return this.sx>l||this.sy>l?(this.sx=l,this.sy=l,!0):!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(e,t){if(t>=0){let n=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+t/100));return e>0?Math.min(e,n):n}return e}},Le=[`image/apng`,`image/avif`,`image/bmp`,`image/gif`,`image/jpeg`,`image/png`,`image/svg+xml`,`image/webp`,`image/x-icon`],Re=class{static get isDarkMode(){return M(this,`isDarkMode`,!!window?.matchMedia?.(`(prefers-color-scheme: dark)`).matches)}},ze=class{static get commentForegroundColor(){let e=document.createElement(`span`);e.classList.add(`comment`,`sidebar`);let{style:t}=e;t.width=t.height=`0`,t.display=`none`,t.color=`var(--comment-fg-color)`,document.body.append(e);let{color:n}=window.getComputedStyle(e);return e.remove(),M(this,`commentForegroundColor`,Ne(n))}};function Be(e,t){t=L(t??1,0,1);let n=255*(1-t);return e.map(e=>Math.round(e*t+n))}function Ve(e,t){let n=e[0]/255,r=e[1]/255,i=e[2]/255,a=Math.max(n,r,i),o=Math.min(n,r,i),s=(a+o)/2;if(a===o)t[0]=t[1]=0;else{let e=a-o;switch(t[1]=s<.5?e/(a+o):e/(2-a-o),a){case n:t[0]=((r-i)/e+(ri?(r+.05)/(i+.05):(i+.05)/(r+.05)}var Ge=new Map;function Ke(e,t){let n=e[0]+e[1]*256+e[2]*65536+t[0]*16777216+t[1]*4294967296+t[2]*1099511627776,r=Ge.get(n);if(r)return r;let i=new Float32Array(9),a=i.subarray(0,3),o=i.subarray(3,6);Ve(e,o);let s=i.subarray(6,9);Ve(t,s);let c=s[2]<.5,l=c?12:4.5;if(o[2]=c?Math.sqrt(o[2]):1-Math.sqrt(1-o[2]),We(o,s,a).005;){let n=o[2]=(e+t)/2;c===We(o,s,a){n.delete()},{signal:n._signal}),this.#r.append(r)}get#p(){let e=document.createElement(`div`);return e.className=`divider`,e}async addAltText(e){let t=await e.render();this.#f(t),this.#r.append(t,this.#p),this.#i=e}addComment(e,t=null){if(this.#a)return;let n=e.renderForToolbar();if(!n)return;this.#f(n);let r=this.#o=this.#p;t?(this.#r.insertBefore(n,t),this.#r.insertBefore(r,t)):this.#r.append(n,r),this.#a=e,e.toolbar=this}addColorPicker(e){if(this.#t)return;this.#t=e;let t=e.renderButton();this.#f(t),this.#r.append(t,this.#p)}async addEditSignatureButton(e){let t=this.#s=await e.renderEditButton(this.#n);this.#f(t),this.#r.append(t,this.#p)}removeButton(e){e===`comment`&&(this.#a?.removeToolbarCommentButton(),this.#a=null,this.#o?.remove(),this.#o=null)}async addButton(e,t){switch(e){case`colorPicker`:t&&this.addColorPicker(t);break;case`altText`:t&&await this.addAltText(t);break;case`editSignature`:t&&await this.addEditSignatureButton(t);break;case`delete`:this.addDeleteButton();break;case`comment`:t&&this.addComment(t)}}async addButtonBefore(e,t,n){if(!t&&e===`comment`)return;let r=this.#r.querySelector(n);r&&e===`comment`&&this.addComment(t,r)}updateEditSignatureButton(e){this.#s&&(this.#s.title=e)}remove(){this.#e.remove(),this.#t?.destroy(),this.#t=null}},Xe=class{#e=null;#t=null;#n;constructor(e){this.#n=e}#r(){let e=this.#t=document.createElement(`div`);e.className=`editToolbar`,e.setAttribute(`role`,`toolbar`),e.dir=this.#n.direction;let t=this.#n._signal;t instanceof AbortSignal&&!t.aborted&&e.addEventListener(`contextmenu`,R,{signal:t});let n=this.#e=document.createElement(`div`);return n.className=`buttons`,e.append(n),this.#n.hasCommentManager()&&this.#a(`commentButton`,`pdfjs-comment-floating-button`,`pdfjs-comment-floating-button-label`,()=>{this.#n.commentSelection(`floating_button`)}),this.#a(`highlightButton`,`pdfjs-highlight-floating-button1`,`pdfjs-highlight-floating-button-label`,()=>{this.#n.highlightSelection(`floating_button`)}),e}#i(e,t){let n=0,r=0;for(let i of e){let e=i.y+i.height;if(en){r=a,n=e;continue}t?a>r&&(r=a):a=1}static clearPointerType(){e.#r=null}static clearPointerIds(){e.#e=NaN,e.#t=null}static clearTimeStamp(){e.#n=NaN}},$e=class{#e=0;get id(){return`${l}${this.#e++}`}},et=class e{#e=de();#t=0;#n=null;static get _isSVGFittingCanvas(){let e=`data:image/svg+xml;charset=UTF-8,`,t=new OffscreenCanvas(1,3).getContext(`2d`,{willReadFrequently:!0}),n=new Image;n.src=e;let r=n.decode().then(()=>(t.drawImage(n,0,0,1,1,0,0,1,3),new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]===0));return M(this,`_isSVGFittingCanvas`,r)}async#r(t,n){this.#n||=new Map;let r=this.#n.get(t);if(r===null)return null;if(r?.bitmap)return r.refCounter+=1,r;try{r||={bitmap:null,id:`image_${this.#e}_${this.#t++}`,refCounter:0,isSvg:!1};let t;if(typeof n==`string`?(r.url=n,t=await Ce(n,`blob`)):n instanceof File?t=r.file=n:n instanceof Blob&&(t=n),t.type===`image/svg+xml`){let n=e._isSVGFittingCanvas,i=new FileReader,a=new Image,o=new Promise((e,t)=>{a.onload=()=>{r.bitmap=a,r.isSvg=!0,e()},i.onload=async()=>{let e=r.svgUrl=i.result;a.src=await n?`${e}#svgView(preserveAspectRatio(none))`:e},a.onerror=i.onerror=t});i.readAsDataURL(t),await o}else r.bitmap=await createImageBitmap(t);r.refCounter=1}catch(e){T(e),r=null}return this.#n.set(t,r),r&&this.#n.set(r.id,r),r}async getFromFile(e){let{lastModified:t,name:n,size:r,type:i}=e;return this.#r(`${t}_${n}_${r}_${i}`,e)}async getFromUrl(e){return this.#r(e,e)}async getFromBlob(e,t){let n=await t;return this.#r(e,n)}async getFromId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){let{blobPromise:e}=t;return delete t.blobPromise,this.getFromBlob(t.id,e)}return this.getFromUrl(t.url)}getFromCanvas(e,t){this.#n||=new Map;let n=this.#n.get(e);if(n?.bitmap)return n.refCounter+=1,n;let r=new OffscreenCanvas(t.width,t.height);return r.getContext(`2d`).drawImage(t,0,0),n={bitmap:r.transferToImageBitmap(),id:`image_${this.#e}_${this.#t++}`,refCounter:1,isSvg:!1},this.#n.set(e,n),this.#n.set(n.id,n),n}getSvgUrl(e){let t=this.#n.get(e);return t?.isSvg?t.svgUrl:null}deleteId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t||(--t.refCounter,t.refCounter!==0))return;let{bitmap:n}=t;if(!t.url&&!t.file){let e=new OffscreenCanvas(n.width,n.height);e.getContext(`bitmaprenderer`).transferFromImageBitmap(n),t.blobPromise=e.convertToBlob()}n.close?.(),t.bitmap=null}isValidId(e){return e.startsWith(`image_${this.#e}_`)}},tt=class{#e=[];#t=!1;#n;#r=-1;constructor(e=128){this.#n=e}add({cmd:e,undo:t,post:n,mustExec:r,type:i=NaN,overwriteIfSameType:a=!1,keepUndo:o=!1}){if(r&&e(),this.#t)return;let s={cmd:e,undo:t,post:n,type:i};if(this.#r===-1){this.#e.length>0&&(this.#e.length=0),this.#r=0,this.#e.push(s);return}if(a&&this.#e[this.#r].type===i){o&&(s.undo=this.#e[this.#r].undo),this.#e[this.#r]=s;return}let c=this.#r+1;c===this.#n?this.#e.splice(0,1):(this.#r=c,c=0;t--)if(this.#e[t].type!==e){this.#e.splice(t+1,this.#r-t),this.#r=t;return}this.#e.length=0,this.#r=-1}}destroy(){this.#e=null}},nt=class e{static ALT=1;static CTRL=2;static META=4;static SHIFT=8;constructor(t){this.callbacks=new Map;let{isMac:n}=F.platform;for(let[r,i,a={}]of t){let t=r.some(e=>e.startsWith(`mac+`));for(let o of r){let r=o;if(t){let e=o.startsWith(`mac+`);if(n!==e)continue;e&&(r=o.slice(4))}let[s,c]=e.#e(r);s!==null&&this.callbacks.getOrInsertComputed(s,pe).push({callback:i,options:a,modifiers:c})}}}static#e(t){let n=null,r=0;for(let i of t.split(`+`)){if(i=i.trim(),!i)continue;let a=i.toUpperCase(),o=e[a];if(o){r|=o;continue}if(n!==null){T(`KeyboardManager: multiple keys in shortcut "${t}"`);break}n=a===`SPACE`?` `:i}return n===null&&T(`KeyboardManager: no key found in shortcut "${t}"`),[n,r]}static#t(e){let t=/^(?:Key([A-Z])|(?:Digit|Numpad)(\d))$/.exec(e);return t?t[1]?.toLowerCase()??t[2]:null}exec(t,n){let r=this.callbacks.get(n.key);if(!r){if(/^[a-z]$/i.test(n.key))return;let t=e.#t(n.code);if(t===null||t===n.key||(r=this.callbacks.get(t),!r))return}let i=(n.altKey?e.ALT:0)|(n.ctrlKey?e.CTRL:0)|(n.metaKey?e.META:0)|(n.shiftKey?e.SHIFT:0),a=r.find(e=>e.modifiers===i);if(!a)return;let{callback:o,options:{bubbles:s=!1,args:c=[],checker:l=null}}=a;l&&!l(t,n)||(o.bind(t,...c,n)(),s||z(n))}},rt=class e{static _colorsMapping=new Map([[`CanvasText`,[0,0,0]],[`Canvas`,[255,255,255]]]);get _colors(){let e=new Map([[`CanvasText`,null],[`Canvas`,null]]);return Pe(e),M(this,`_colors`,e)}convert(t){let n=Ne(t);if(!window.matchMedia(`(forced-colors: active)`).matches)return n;for(let[t,r]of this._colors)if(r.every((e,t)=>e===n[t]))return e._colorsMapping.get(t);return n}getHexCode(e){let t=this._colors.get(e);return t?I.makeHexColor(...t):e}},it=class e{#e=new AbortController;#t=null;#n=null;#r=new Map;#i=new Map;#a=null;#o=null;#s=null;#c=null;#l=null;#u=new tt;#d=null;#f=null;#p=null;#m=0;#h=new Set;#g=null;#_=null;#v=new Set;_editorUndoBar=null;#y=!1;#b=!1;#x=!1;#S=null;#C=null;#w=null;#T=null;#E=!1;#D=null;#O=new $e;#k=!1;#A=!1;#j=!1;#M=null;#N=null;#P=null;#F=null;#I=null;#L=u.NONE;#R=new Set;#z=null;#B=null;#V=null;#H=null;#U=null;#W={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#G=[0,0];#K=null;#q=null;#J=null;#Y=null;#X=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.#q.contains(document.activeElement)&&document.activeElement.tagName!==`BUTTON`&&e.hasSomethingToControl(),r=(e,{target:t})=>{if(t instanceof HTMLInputElement){let{type:e}=t;return e!==`text`&&e!==`number`}return!0},i=this.TRANSLATE_SMALL,a=this.TRANSLATE_BIG;return M(this,`_keyboardManager`,new nt([[[`ctrl+a`,`mac+meta+a`],t.selectAll,{checker:r}],[[`ctrl+z`,`mac+meta+z`],t.undo,{checker:r}],[[`ctrl+y`,`ctrl+shift+z`,`mac+meta+shift+z`,`ctrl+shift+Z`,`mac+meta+shift+Z`],t.redo,{checker:r}],[[`Backspace`,`alt+Backspace`,`ctrl+Backspace`,`shift+Backspace`,`mac+Backspace`,`mac+alt+Backspace`,`mac+ctrl+Backspace`,`Delete`,`ctrl+Delete`,`shift+Delete`,`mac+Delete`],t.delete,{checker:r}],[[`Enter`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#q.contains(t)&&!e.isEnterHandled}],[[`Space`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#q.contains(document.activeElement)}],[[`Escape`],t.unselectAll],[[`ArrowLeft`],t.translateSelectedEditors,{args:[-i,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t.translateSelectedEditors,{args:[-a,0],checker:n}],[[`ArrowRight`],t.translateSelectedEditors,{args:[i,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t.translateSelectedEditors,{args:[a,0],checker:n}],[[`ArrowUp`],t.translateSelectedEditors,{args:[0,-i],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t.translateSelectedEditors,{args:[0,-a],checker:n}],[[`ArrowDown`],t.translateSelectedEditors,{args:[0,i],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t.translateSelectedEditors,{args:[0,a],checker:n}]]))}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this._signal=this.#e.signal;this.#q=e,this.#J=t,this.#Y=n,this.#s=r,this.#d=i,this.#B=a,this.#U=s,this._eventBus=o;let _={signal:g,...Ze};o.on(`editingaction`,this.onEditingAction.bind(this),_),o.on(`pagechanging`,this.onPageChanging.bind(this),_),o.on(`scalechanging`,this.onScaleChanging.bind(this),_),o.on(`rotationchanging`,this.onRotationChanging.bind(this),_),o.on(`setpreference`,this.onSetPreference.bind(this),_),o.on(`switchannotationeditorparams`,e=>this.updateParams(e.type,e.value),_),window.addEventListener(`pointerdown`,()=>{this.#A=!0},{capture:!0,signal:g}),window.addEventListener(`pointerup`,()=>{this.#A=!1},{capture:!0,signal:g}),window.addEventListener(`beforeunload`,this.endCurrentEditing.bind(this),{capture:!0,signal:g}),this.#ne(),this.#le(),this.#ae(),this.#c=s.annotationStorage,this.#S=s.filterFactory,this.#V=c,this.#T=l||null,this.#y=u,this.#b=d,this.#x=f,this.#I=p||null,this.viewParameters={realScale:Se.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=m||null,this._supportsPinchToZoom=h!==!1,i?.setSidebarUiManager(this)}destroy(){this.#X?.resolve(),this.#X=null,this.#e?.abort(),this.#e=null,this._signal=null;for(let e of this.#i.values())e.destroy();this.#i.clear(),this.#r.clear(),this.#v.clear(),this.#F?.clear(),this.#t=null,this.#R.clear(),this.#u.destroy(),this.#s?.destroy(),this.#d?.destroy(),this.#B?.destroy(),this.#D?.hide(),this.#D=null,this.#P?.destroy(),this.#P=null,this.#n=null,this.#C&&=(clearTimeout(this.#C),null),this.#K&&=(clearTimeout(this.#K),null),this._editorUndoBar?.destroy(),this.#U=null}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return this.#I}get useNewAltTextFlow(){return this.#b}get useNewAltTextWhenAddingImage(){return this.#x}get hcmFilter(){return M(this,`hcmFilter`,this.#V?this.#S.addHCMFilter(this.#V.foreground,this.#V.background):`none`)}get direction(){return M(this,`direction`,getComputedStyle(this.#q).direction)}get _highlightColors(){return M(this,`_highlightColors`,this.#T?new Map(this.#T.split(`,`).map(e=>(e=e.split(`=`).map(e=>e.trim()),e[1]=e[1].toUpperCase(),e))):null)}get highlightColors(){let{_highlightColors:e}=this;if(!e)return M(this,`highlightColors`,null);let t=new Map,n=!!this.#V;for(let[r,i]of e){let e=r.endsWith(`_HCM`);if(n&&e){t.set(r.replace(`_HCM`,``),i);continue}!n&&!e&&t.set(r,i)}return M(this,`highlightColors`,t)}get highlightColorNames(){return M(this,`highlightColorNames`,this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}getNonHCMColor(e){if(!this._highlightColors)return e;let t=this.highlightColorNames.get(e);return this._highlightColors.get(t)||e}getNonHCMColorName(e){return this.highlightColorNames.get(e)||e}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#p=e}setMainHighlightColorPicker(e){this.#P=e}editAltText(e,t=!1){this.#s?.editAltText(this,e,t)}hasCommentManager(){return!!this.#d}editComment(e,t,n,r){this.#d?.showDialog(this,e,t,n,r)}selectComment(e,t){(this.#i.get(e)?.getEditorByUID(t))?.toggleComment(!0,!0)}updateComment(e){this.#d?.updateComment(e.getData())}updatePopupColor(e){this.#d?.updatePopupColor(e)}removeComment(e){this.#d?.removeComments([e.uid])}deleteComment(e,t){let n=()=>{e.comment=t};this.addCommands({cmd:()=>{this._editorUndoBar?.show(n,`comment`),this.toggleComment(null),e.comment=null},undo:n,mustExec:!0})}toggleComment(e,t,n=void 0){this.#d?.toggleCommentPopup(e,t,n)}makeCommentColor(e,t){return e&&this.#d?.makeCommentColor(e,t)||null}getCommentDialogElement(){return this.#d?.dialogElement||null}async waitForEditorsRendered(e){if(this.#i.has(e-1))return;let{resolve:t,promise:n}=Promise.withResolvers(),r=n=>{n.pageNumber===e&&(this._eventBus.off(`editorsrendered`,r),t())};this._eventBus.on(`editorsrendered`,r,Ze),await n}getSignature(e){this.#B?.getSignature({uiManager:this,editor:e})}get signatureManager(){return this.#B}switchToMode(e,t){this._eventBus.on(`annotationeditormodechanged`,t,{once:!0,signal:this._signal,...Ze}),this._eventBus.dispatch(`showannotationeditorui`,{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch(`setpreference`,{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){e===`enableNewAltTextWhenAddingImage`&&(this.#x=t)}onPageChanging({pageNumber:e}){this.#m=e-1}deletePage(e){for(let t of this.getEditors(e))t.remove();this.#i.delete(e),this.#m===e&&(this.#m=0)}focusMainContainer(){this.#q.focus()}findParent(e,t){for(let n of this.#i.values()){let{x:r,y:i,width:a,height:o}=n.div.getBoundingClientRect();if(e>=r&&e<=r+a&&t>=i&&t<=i+o)return n}return null}disableUserSelect(e=!1){this.#J.classList.toggle(`noUserSelect`,e)}addShouldRescale(e){this.#v.add(e)}removeShouldRescale(e){this.#v.delete(e)}onScaleChanging({scale:e}){this.commitOrRemove(),this.viewParameters.realScale=e*Se.PDF_TO_CSS_UNITS;for(let e of this.#v)e.onScaleChanging();this.#p?.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}#Z({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e}#Q(e){let{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(let t of this.#i.values())if(t.hasTextLayer(e))return t;return null}highlightSelection(e=``,t=!1){let n=document.getSelection();if(!n||n.isCollapsed)return;let{anchorNode:r,anchorOffset:i,focusNode:a,focusOffset:o}=n,s=n.toString(),c=this.#Z(n).closest(`.textLayer`),l=this.getSelectionBoxes(c);if(!l)return;n.empty();let d=this.#Q(c),f=this.#L===u.NONE,p=()=>{let n=d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:l,anchorNode:r,anchorOffset:i,focusNode:a,focusOffset:o,text:s});f&&this.showAllEditors(`highlight`,!0,!0),t&&n?.editComment()};if(f){this.switchToMode(u.HIGHLIGHT,p);return}p()}commentSelection(e=``){this.highlightSelection(e,!0)}endCurrentEditing(){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#$(){let e=document.getSelection();if(!e||e.isCollapsed)return;let t=this.#Z(e).closest(`.textLayer`),n=this.getSelectionBoxes(t);n&&(this.#D||=new Xe(this),this.#D.show(t,n,this.direction===`ltr`))}getAndRemoveDataFromAnnotationStorage(e){if(!this.#c)return null;let t=`${l}${e}`,n=this.#c.getRawValue(t);return n&&this.#c.remove(t),n}addToAnnotationStorage(e){!e.isEmpty()&&this.#c&&!this.#c.has(e.id)&&this.#c.setValue(e.id,e)}a11yAlert(e,t=null){let n=this.#Y;n&&(n.setAttribute(`data-l10n-id`,e),t?n.setAttribute(`data-l10n-args`,JSON.stringify(t)):n.removeAttribute(`data-l10n-args`))}#ee(){let e=document.getSelection();if(!e||e.isCollapsed){this.#z&&(this.#D?.hide(),this.#z=null,this.#ue({hasSelectedText:!1}));return}let{anchorNode:t}=e;if(t===this.#z)return;let n=this.#Z(e).closest(`.textLayer`);if(!n){this.#z&&(this.#D?.hide(),this.#z=null,this.#ue({hasSelectedText:!1}));return}if(this.#D?.hide(),this.#z=t,this.#ue({hasSelectedText:!0}),(this.#L===u.HIGHLIGHT||this.#L===u.NONE)&&(this.#L===u.HIGHLIGHT&&this.showAllEditors(`highlight`,!0,!0),this.#E=this.isShiftKeyDown,!this.isShiftKeyDown)){let e=this.#L===u.HIGHLIGHT?this.#Q(n):null;if(e?.toggleDrawing(),this.#A){let t=new AbortController,n=this.combinedSignal(t),r=n=>{(n.type!==`pointerup`||n.button===0)&&(t.abort(),e?.toggleDrawing(!0),n.type===`pointerup`&&this.#te(`main_toolbar`))};window.addEventListener(`pointerup`,r,{signal:n}),window.addEventListener(`blur`,r,{signal:n})}else e?.toggleDrawing(!0),this.#te(`main_toolbar`)}}#te(e=``){this.#L===u.HIGHLIGHT?this.highlightSelection(e):this.#y&&this.#$()}#ne(){document.addEventListener(`selectionchange`,this.#ee.bind(this),{signal:this._signal})}#re(){if(this.#w)return;this.#w=new AbortController;let e=this.combinedSignal(this.#w);window.addEventListener(`focus`,this.focus.bind(this),{signal:e}),window.addEventListener(`blur`,this.blur.bind(this),{signal:e})}#ie(){this.#w?.abort(),this.#w=null}blur(){if(this.isShiftKeyDown=!1,this.#E&&(this.#E=!1,this.#te(`main_toolbar`)),!this.hasSelection)return;let{activeElement:e}=document;for(let t of this.#R)if(t.div.contains(e)){this.#N=[t,e],t._focusEventsAllowed=!1;break}}focus(){if(!this.#N)return;let[e,t]=this.#N;this.#N=null,t.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}#ae(){if(this.#M)return;this.#M=new AbortController;let e=this.combinedSignal(this.#M);window.addEventListener(`keydown`,this.keydown.bind(this),{signal:e}),window.addEventListener(`keyup`,this.keyup.bind(this),{signal:e})}#oe(){this.#M?.abort(),this.#M=null}#se(){if(this.#f)return;this.#f=new AbortController;let e=this.combinedSignal(this.#f);document.addEventListener(`copy`,this.copy.bind(this),{signal:e}),document.addEventListener(`cut`,this.cut.bind(this),{signal:e}),document.addEventListener(`paste`,this.paste.bind(this),{signal:e})}#ce(){this.#f?.abort(),this.#f=null}#le(){let e=this._signal;document.addEventListener(`dragover`,this.dragOver.bind(this),{signal:e}),document.addEventListener(`drop`,this.drop.bind(this),{signal:e})}addEditListeners(){this.#ae(),this.setEditingState(!0)}removeEditListeners(){this.#oe(),this.setEditingState(!1)}dragOver(e){for(let{type:t}of e.dataTransfer.items)for(let n of this.#_)if(n.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect=`copy`,e.preventDefault();return}}drop(e){for(let t of e.dataTransfer.items)for(let n of this.#_)if(n.isHandlingMimeForPasting(t.type)){n.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){if(e.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let t=[];for(let e of this.#R){let n=e.serialize(!0);n&&t.push(n)}t.length!==0&&e.clipboardData.setData(`application/pdfjs`,JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();let{clipboardData:t}=e;for(let e of t.items)for(let t of this.#_)if(t.isHandlingMimeForPasting(e.type)){t.paste(e,this.currentLayer);return}let n=t.getData(`application/pdfjs`);if(!n)return;try{n=JSON.parse(n)}catch(e){T(`paste: "${e.message}".`);return}if(!Array.isArray(n))return;this.unselectAll();let r=this.currentLayer;try{let e=[];for(let t of n){let n=await r.deserialize(t);if(!n)return;e.push(n)}this.addCommands({cmd:()=>{for(let t of e)this.#me(t);this.#_e(e)},undo:()=>{for(let t of e)t.remove()},mustExec:!0})}catch(e){T(`paste: "${e.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key===`Shift`&&(this.isShiftKeyDown=!0),this.#L!==u.NONE&&!this.isEditorHandlingKeyboard&&e._keyboardManager.exec(this,t)}keyup(e){this.isShiftKeyDown&&e.key===`Shift`&&(this.isShiftKeyDown=!1,this.#E&&(this.#E=!1,this.#te(`main_toolbar`)))}onEditingAction({name:e}){switch(e){case`undo`:case`redo`:case`delete`:case`selectAll`:this[e]();break;case`highlightSelection`:this.highlightSelection(`context_menu`);break;case`commentSelection`:this.commentSelection(`context_menu`)}}updatePageIndex(e,t){for(let n of this.#o.get(e)||[])n.pageIndex=t;let n=this.#a.get(e);n&&(n.pageIndex=t,this.#i.set(t,n),this.#k?n.enable():n.disable())}startUpdatePages(){this.#a=new Map(this.#i),this.#i.clear();let e=this.#o=new Map,t=t=>{e.getOrInsertComputed(t.pageIndex,pe).push(t)};for(let e of this.#r.values())t(e);for(let[e,n]of this.#c)e.startsWith(l)&&!this.#r.has(e)&&Number.isInteger(n?.pageIndex)&&t(n)}endUpdatePages(){this.#a=null,this.#o=null}clonePage(e,t){for(let n of this.getEditors(e)){let e=n.serialize(n.mode!==u.HIGHLIGHT);e&&(e.pageIndex=t,e.id=this.getId(),e.isClone=!0,delete e.popupRef,this.#c.setValue(e.id,e))}}findClonesForPage(e){let t=[],{pageIndex:n}=e;for(let[r,i]of this.#c)i.pageIndex===n&&i.isClone&&(this.#c.remove(r),t.push(e.deserialize(i).then(t=>{t&&(t.isClone=!0,e.addOrRebuild(t))})));return Promise.all(t)}#ue(e){Object.entries(e).some(([e,t])=>this.#W[e]!==t)&&(this._eventBus.dispatch(`editingstateschanged`,{source:this,details:Object.assign(this.#W,e)}),this.#L===u.HIGHLIGHT&&e.hasSelectedEditor===!1&&this.#de([[d.HIGHLIGHT_FREE,!0]]))}#de(e){this._eventBus.dispatch(`annotationeditorparamschanged`,{source:this,details:e})}setEditingState(e){e?(this.#re(),this.#se(),this.#ue({isEditing:this.#L!==u.NONE,isEmpty:this.#ge(),hasSomethingToUndo:this.#u.hasSomethingToUndo(),hasSomethingToRedo:this.#u.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#ie(),this.#ce(),this.#ue({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!this.#_){this.#_=e;for(let e of this.#_)this.#de(e.defaultPropertiesToUpdate)}}getId(){return this.#O.id}get currentLayer(){return this.#i.get(this.#m)}getLayer(e){return this.#i.get(e)}get currentPageIndex(){return this.#m}addLayer(e){this.#i.set(e.pageIndex,e),this.#k?e.enable():e.disable()}removeLayer(e){this.#i.delete(e.pageIndex)}async updateMode(e,t=null,n=!1,r=!1,i=!1,a=!1){if(this.#L!==e&&!(this.#X&&(await this.#X.promise,!this.#X))){if(this.#X=Promise.withResolvers(),this.#p?.commitOrRemove(),this.#L===u.POPUP&&this.#d?.hideSidebar(),this.#d?.destroyPopup(),this.#L=e,e===u.NONE){this.setEditingState(!1),this.#pe();for(let e of this.#r.values())e.hideStandaloneCommentButton();this._editorUndoBar?.hide(),this.toggleComment(null),this.#X.resolve();return}for(let e of this.#r.values())e.addStandaloneCommentButton();e===u.SIGNATURE&&await this.#B?.loadSignatures(),n&&H.clearPointerType(),this.setEditingState(!0),await this.#fe(),this.unselectAll();for(let t of this.#i.values())t.updateMode(e);if(e===u.POPUP){this.#n||=await this.#U.getAnnotationsByType(new Set(this.#_.map(e=>e._editorType)));let e=new Set,t=[];for(let n of this.#r.values()){let{annotationElementId:r,hasComment:i,deleted:a}=n;r&&e.add(r),i&&!a&&t.push(n.getData())}for(let n of this.#n){let{id:r,popupRef:i,contentsObj:a}=n;i&&a?.str&&!e.has(r)&&!this.#h.has(r)&&t.push(n)}this.#d?.showSidebar(t)}if(!t){r&&this.addNewEditorFromKeyboard(),this.#X.resolve();return}for(let e of this.#r.values())e.uid===t?(this.setSelected(e),a?e.editComment():i?e.enterInEditMode():e.focus()):e.unselect();this.#X.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e.mode!==this.#L&&this._eventBus.dispatch(`switchannotationeditormode`,{source:this,...e})}updateParams(e,t){if(this.#_){switch(e){case d.CREATE:this.currentLayer.addNewEditor(t);return;case d.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:{type:`highlight`,action:`toggle_visibility`}}}),(this.#H||=new Map).set(e,t),this.showAllEditors(`highlight`,t)}if(this.hasSelection)for(let n of this.#R)n.updateParams(e,t);else for(let n of this.#_)n.updateDefaultParams(e,t)}}showAllEditors(e,t,n=!1){for(let n of this.#r.values())n.editorType===e&&n.show(t);(this.#H?.get(d.HIGHLIGHT_SHOW_ALL)??!0)!==t&&this.#de([[d.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(this.#j!==e){this.#j=e;for(let t of this.#i.values())e?t.disableClick():t.enableClick(),t.div.classList.toggle(`waiting`,e)}}async#fe(){if(!this.#k){this.#k=!0;let e=[];for(let t of this.#i.values())e.push(t.enable());await Promise.all(e);for(let e of this.#r.values())e.enable()}}#pe(){if(this.unselectAll(),this.#k){this.#k=!1;for(let e of this.#i.values())e.disable();for(let e of this.#r.values())e.disable()}}*getEditors(e){for(let t of this.#r.values())t.pageIndex===e&&(yield t)}getEditor(e){return this.#r.get(e)}addEditor(e){this.#r.set(e.id,e)}removeEditor(e){e.div.contains(document.activeElement)&&(this.#C&&clearTimeout(this.#C),this.#C=setTimeout(()=>{this.focusMainContainer(),this.#C=null},0)),this.#r.delete(e.id),e.annotationElementId&&this.#F?.delete(e.annotationElementId),this.unselect(e),(!e.annotationElementId||!this.#h.has(e.annotationElementId))&&this.#c?.remove(e.id)}addDeletedAnnotationElement(e){this.#h.add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return this.#h.has(e)}removeDeletedAnnotationElement(e){this.#h.delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}#me(e){let t=this.#i.get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))}setActiveEditor(e){this.#t!==e&&(this.#t=e,e&&this.#de(e.propertiesToUpdate))}get#he(){let e=null;for(e of this.#R);return e}updateUI(e){this.#he===e&&this.#de(e.propertiesToUpdate)}updateUIForDefaultProperties(e){this.#de(e.defaultPropertiesToUpdate)}toggleSelected(e){if(this.#R.has(e)){this.#R.delete(e),e.unselect(),this.#ue({hasSelectedEditor:this.hasSelection});return}this.#R.add(e),e.select(),this.#de(e.propertiesToUpdate),this.#ue({hasSelectedEditor:!0})}setSelected(e){this.updateToolbar({mode:e.mode,editId:e.uid}),this.#p?.commitOrRemove();for(let t of this.#R)t!==e&&t.unselect();this.#d?.destroyPopup(),this.#R.clear(),this.#R.add(e),e.select(),this.#de(e.propertiesToUpdate),this.#ue({hasSelectedEditor:!0})}get firstSelectedEditor(){return this.#R.values().next().value}unselect(e){e.unselect(),this.#R.delete(e),this.#ue({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#R.size!==0}get isEnterHandled(){return this.#R.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#u.undo(),this.#ue({hasSomethingToUndo:this.#u.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#ge()}),this._editorUndoBar?.hide()}redo(){this.#u.redo(),this.#ue({hasSomethingToUndo:!0,hasSomethingToRedo:this.#u.hasSomethingToRedo(),isEmpty:this.#ge()})}addCommands(e){this.#u.add(e),this.#ue({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#ge()})}cleanUndoStack(e){this.#u.cleanType(e)}#ge(){if(this.#r.size===0)return!0;if(this.#r.size===1)for(let e of this.#r.values())return e.isEmpty();return!1}delete(){this.commitOrRemove();let e=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!e)return;let t=e?[e]:[...this.#R],n=()=>{this._editorUndoBar?.show(r,t.length===1?t[0].editorType:t.length);for(let e of t)e.remove()},r=()=>{for(let e of t)this.#me(e)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#_e(e){for(let e of this.#R)e.unselect();this.#R.clear();for(let t of e)t.isEmpty()||(this.#R.add(t),t.select());this.#ue({hasSelectedEditor:this.hasSelection})}selectAll(){for(let e of this.#R)e.commit();this.#_e(this.#r.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#L!==u.NONE))&&!this.#p?.commitOrRemove()&&(this.#d?.destroyPopup(),this.hasSelection)){for(let e of this.#R)e.unselect();this.#R.clear(),this.#ue({hasSelectedEditor:!1})}}translateSelectedEditors(e,t,n=!1){if(n||this.commitOrRemove(),!this.hasSelection)return;this.#G[0]+=e,this.#G[1]+=t;let[r,i]=this.#G,a=[...this.#R];this.#K&&clearTimeout(this.#K),this.#K=setTimeout(()=>{this.#K=null,this.#G[0]=this.#G[1]=0,this.addCommands({cmd:()=>{for(let e of a)this.#r.has(e.id)&&(e.translateInPage(r,i),e.translationDone())},undo:()=>{for(let e of a)this.#r.has(e.id)&&(e.translateInPage(-r,-i),e.translationDone())},mustExec:!1})},1e3);for(let n of a)n.translateInPage(e,t),n.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#g=new Map;for(let e of this.#R)this.#g.set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#g)return!1;this.disableUserSelect(!1);let e=this.#g;this.#g=null;let t=!1;for(let[{x:n,y:r,pageIndex:i},a]of e)a.newX=n,a.newY=r,a.newPageIndex=i,t||=n!==a.savedX||r!==a.savedY||i!==a.savedPageIndex;if(!t)return!1;let n=(e,t,n,r)=>{if(this.#r.has(e.id)){let i=this.#i.get(r);i?e._setParentAndPosition(i,t,n):(e.pageIndex=r,e.x=t,e.y=n)}};return this.addCommands({cmd:()=>{for(let[t,{newX:r,newY:i,newPageIndex:a}]of e)n(t,r,i,a)},undo:()=>{for(let[t,{savedX:r,savedY:i,savedPageIndex:a}]of e)n(t,r,i,a)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(this.#g)for(let n of this.#g.keys())n.drag(e,t)}rebuild(e){if(e.parent===null){let t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#R.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return this.#t===e}getActive(){return this.#t}getMode(){return this.#L}isEditingMode(){return this.#L!==u.NONE}get imageManager(){return M(this,`imageManager`,new et)}getSelectionBoxes(e){if(!e)return null;let t=document.getSelection();for(let n=0,r=t.rangeCount;n({x:(t-r)/a,y:1-(e+o-n)/i,width:s/a,height:o/i});break;case`180`:o=(e,t,o,s)=>({x:1-(e+o-n)/i,y:1-(t+s-r)/a,width:o/i,height:s/a});break;case`270`:o=(e,t,o,s)=>({x:1-(t+s-r)/a,y:(e-n)/i,width:s/a,height:o/i});break;default:o=(e,t,o,s)=>({x:(e-n)/i,y:(t-r)/a,width:o/i,height:s/a})}let s=[];for(let e=0,n=t.rangeCount;ee.stopPropagation(),{signal:r});let i=e=>{e.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#d&&this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_clicked`,data:{label:this.#p}})};return t.addEventListener(`click`,i,{capture:!0,signal:r}),t.addEventListener(`keydown`,e=>{e.target===t&&e.key===`Enter`&&(this.#o=!0,i(e))},{signal:r}),await this.#m(),t}get#p(){return this.#e&&`added`||this.#e===null&&this.guessedText&&`review`||`missing`}finish(){this.#n&&(this.#n.focus({focusVisible:this.#o}),this.#o=!1)}isEmpty(){return this.#d?this.#e===null:!this.#e&&!this.#t}hasData(){return this.#d?this.#e!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#e===null&&(this.#l=t,this.#u=await e._l10n.get(`pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer`,{generatedAltText:t}),this.#m())}toggleAltTextBadge(e=!1){if(!this.#d||this.#e){this.#s?.remove(),this.#s=null;return}if(!this.#s){let e=this.#s=document.createElement(`div`);e.className=`noAltTextBadge`,this.#c.div.append(e)}this.#s.classList.toggle(`hidden`,!e)}serialize(e){let t=this.#e;return!e&&this.#l===t&&(t=this.#u),{altText:t,decorative:this.#t,guessedText:this.#l,textWithDisclaimer:this.#u}}get data(){return{altText:this.#e,decorative:this.#t}}set data({altText:e,decorative:t,guessedText:n,textWithDisclaimer:r,cancel:i=!1}){n&&(this.#l=n,this.#u=r),(this.#e!==e||this.#t!==t)&&(i||(this.#e=e,this.#t=t),this.#m())}toggle(e=!1){this.#n&&(!e&&this.#a&&(clearTimeout(this.#a),this.#a=null),this.#n.disabled=!e)}shown(){this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_displayed`,data:{label:this.#p}})}destroy(){this.#n?.remove(),this.#n=null,this.#r=null,this.#i=null,this.#s?.remove(),this.#s=null}async#m(){let t=this.#n;if(!t)return;if(this.#d){if(t.classList.toggle(`done`,!!this.#e),t.setAttribute(`data-l10n-id`,e.#f[this.#p]),this.#r?.setAttribute(`data-l10n-id`,e.#f[`${this.#p}-label`]),!this.#e){this.#i?.remove();return}}else{if(!this.#e&&!this.#t){t.classList.remove(`done`),this.#i?.remove();return}t.classList.add(`done`),t.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-edit-button`)}let n=this.#i;if(!n){this.#i=n=document.createElement(`span`),n.className=`tooltip`,n.setAttribute(`role`,`tooltip`),n.id=`alt-text-tooltip-${this.#c.id}`;let e=this.#c._uiManager._signal;e.addEventListener(`abort`,()=>{clearTimeout(this.#a),this.#a=null},{once:!0}),t.addEventListener(`mouseenter`,()=>{this.#a=setTimeout(()=>{this.#a=null,this.#i.classList.add(`show`),this.#c._reportTelemetry({action:`alt_text_tooltip`})},100)},{signal:e}),t.addEventListener(`mouseleave`,()=>{this.#a&&=(clearTimeout(this.#a),null),this.#i?.classList.remove(`show`)},{signal:e})}this.#t?n.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-decorative-tooltip`):(n.removeAttribute(`data-l10n-id`),n.textContent=this.#e),n.parentNode||t.append(n),this.#c.getElementForAltText()?.setAttribute(`aria-describedby`,n.id)}},ot=class{#e=null;#t=null;#n=!1;#r=null;#i=null;#a=null;#o=null;#s=null;#c=!1;#l=null;constructor(e){this.#r=e}renderForToolbar(){let e=this.#t=document.createElement(`button`);return e.className=`comment`,this.#u(e,!1)}renderForStandalone(){let e=this.#e=document.createElement(`button`);e.className=`annotationCommentButton`;let t=this.#r.commentButtonPosition;if(t){let{style:n}=e;n.insetInlineEnd=`calc(${100*(this.#r._uiManager.direction===`ltr`?1-t[0]:t[0])}% - var(--comment-button-dim))`,n.top=`calc(${100*t[1]}% - var(--comment-button-dim))`;let r=this.#r.commentButtonColor;r&&(n.backgroundColor=r)}return this.#u(e,!0)}focusButton(){setTimeout(()=>{(this.#e??this.#t)?.focus()},0)}onUpdatedColor(){if(!this.#e)return;let e=this.#r.commentButtonColor;e&&(this.#e.style.backgroundColor=e),this.#r._uiManager.updatePopupColor(this.#r)}get commentButtonWidth(){return(this.#e?.getBoundingClientRect().width??0)/this.#r.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#l)return this.#l;if(!this.#e)return null;let{x:e,y:t,height:n}=this.#e.getBoundingClientRect(),{x:r,y:i,width:a,height:o}=this.#r.parent.boundingClientRect;return[(e-r)/a,(t+n-i)/o]}set commentPopupPositionInLayer(e){this.#l=e}hasDefaultPopupPosition(){return this.#l===null}removeStandaloneCommentButton(){this.#e?.remove(),this.#e=null}removeToolbarCommentButton(){this.#t?.remove(),this.#t=null}setCommentButtonStates({selected:e,hasPopup:t}){this.#e&&(this.#e.classList.toggle(`selected`,e),this.#e.ariaExpanded=t)}#u(e,t){if(!this.#r._uiManager.hasCommentManager())return null;e.tabIndex=`0`,e.ariaHasPopup=`dialog`,t?(e.ariaControls=`commentPopup`,e.setAttribute(`data-l10n-id`,`pdfjs-show-comment-button`)):(e.ariaControlsElements=[this.#r._uiManager.getCommentDialogElement()],e.setAttribute(`data-l10n-id`,`pdfjs-editor-add-comment-button`));let n=this.#r._uiManager._signal;if(!(n instanceof AbortSignal)||n.aborted)return e;e.addEventListener(`contextmenu`,R,{signal:n}),t&&(e.addEventListener(`focusin`,e=>{this.#r._focusEventsAllowed=!1,z(e)},{capture:!0,signal:n}),e.addEventListener(`focusout`,e=>{this.#r._focusEventsAllowed=!0,z(e)},{capture:!0,signal:n})),e.addEventListener(`pointerdown`,e=>e.stopPropagation(),{signal:n});let r=t=>{t.preventDefault(),e===this.#t?this.edit():this.#r.toggleComment(!0)};return e.addEventListener(`click`,r,{capture:!0,signal:n}),e.addEventListener(`keydown`,t=>{t.target===e&&t.key===`Enter`&&(this.#n=!0,r(t))},{signal:n}),e.addEventListener(`pointerenter`,()=>{this.#r.toggleComment(!1,!0)},{signal:n}),e.addEventListener(`pointerleave`,()=>{this.#r.toggleComment(!1,!1)},{signal:n}),e}edit(e){let t=this.commentPopupPositionInLayer,n,r;if(t)[n,r]=t;else{[n,r]=this.#r.commentButtonPosition;let{width:e,height:t,x:i,y:a}=this.#r;n=i+n*e,r=a+r*t}let i=this.#r.parent.boundingClientRect,{x:a,y:o,width:s,height:c}=i;this.#r._uiManager.editComment(this.#r,a+n*s,o+r*c,{...e,parentDimensions:i})}finish(){this.#t&&(this.#t.focus({focusVisible:this.#n}),this.#n=!1)}isDeleted(){return this.#c||this.#o===``}isEmpty(){return this.#o===null}hasBeenEdited(){return this.isDeleted()||this.#o!==this.#i}serialize(){return this.data}get data(){return{text:this.#o,richText:this.#a,date:this.#s,deleted:this.isDeleted()}}set data(e){if(e!==this.#o&&(this.#a=null),e===null){this.#o=``,this.#c=!0;return}this.#o=e,this.#s=new Date,this.#c=!1}restoreData({text:e,richText:t,date:n}){this.#o=e,this.#a=t,this.#s=n,this.#c=!1}setInitialText(e,t=null){this.#i=e,this.data=e,this.#s=null,this.#a=t}shown(){}destroy(){this.#t?.remove(),this.#t=null,this.#e?.remove(),this.#e=null,this.#o=``,this.#a=null,this.#s=null,this.#r=null,this.#n=!1,this.#c=!1}};function st(e){e.preventDefault()}var ct=1e-4;function lt(e){return e.cancelable?(z(e),!0):(e.stopPropagation(),!1)}var ut=class{#e;#t=!1;#n=null;#r;#i;#a;#o;#s;#c=!1;#l=null;#u;#d=new Set;#f=null;#p;#m=null;#h=0;constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:n=null,onPinchStart:r=null,onPinching:i=null,onPinchEnd:a=null,onPanning:o=null,signal:s}){this.#e=e,this.#n=n,this.#r=t,this.#i=r,this.#a=i,this.#o=a,this.#s=o,this.#p=new AbortController,this.#u=AbortSignal.any([s,this.#p.signal]),e.addEventListener(`touchstart`,this.#g.bind(this),{passive:!1,signal:this.#u})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Ie.pixelRatio}get MIN_TOUCH_DISTANCE_TO_SCALE(){return 4/Ie.pixelRatio}#g(e){if(this.#r?.())return;this.#v(e);let t=this.#d;for(let{identifier:n}of e.changedTouches)t.add(n);if(t.size===1){this.#_();return}if(!this.#m){this.#m=new AbortController;let e=AbortSignal.any([this.#u,this.#m.signal]),t=this.#e,n={signal:e,capture:!1,passive:!1};t.addEventListener(`touchmove`,this.#x.bind(this),n);let r=this.#S.bind(this);t.addEventListener(`touchend`,r,n),t.addEventListener(`touchcancel`,r,n),n.capture=!0,t.addEventListener(`pointerdown`,z,n),t.addEventListener(`pointermove`,z,n),t.addEventListener(`pointercancel`,st,n),t.addEventListener(`pointerup`,st,n),this.#i?.()}this.#c=lt(e),this.#b(e)}#_(){if(this.#l)return;let e=this.#l=new AbortController,t=AbortSignal.any([this.#u,e.signal]),n=this.#e,r={capture:!0,signal:t,passive:!1},i=e=>{e.pointerType===`touch`&&(this.#l?.abort(),this.#l=null)};n.addEventListener(`pointerdown`,e=>{e.pointerType===`touch`&&(z(e),i(e))},r),n.addEventListener(`pointerup`,i,r),n.addEventListener(`pointercancel`,i,r)}#v(e){let t=this.#d;if(t.size===0)return;let n=this.#d=new Set;for(let{identifier:r}of e.touches)t.has(r)&&n.add(r)}#y(e){let t=this.#d,n=[];for(let r of e.touches)t.has(r.identifier)&&n.push(r);return n}#b(e){let t=this.#y(e);if(t.length!==2||this.#n?.()){this.#f=null;return}let[n,r]=t;this.#f={touch0X:n.screenX,touch0Y:n.screenY,touch1X:r.screenX,touch1Y:r.screenY,panX:(n.clientX+r.clientX)/2,panY:(n.clientY+r.clientY)/2,screenPanX:(n.screenX+r.screenX)/2,screenPanY:(n.screenY+r.screenY)/2}}#x(e){if(!this.#f)return;let t=this.#y(e);if(t.length!==2)return;let n=this.#c;if(this.#c=lt(e),!this.#c)return;if(!n){this.#b(e);return}let[r,i]=t,{screenX:a,screenY:o}=r,{screenX:s,screenY:c}=i,l=this.#f,{touch0X:u,touch0Y:d,touch1X:f,touch1Y:p,panX:m,panY:h}=l,g=f-u,_=p-d,v=s-a,y=c-o,b=(r.clientX+i.clientX)/2,x=(r.clientY+i.clientY)/2;l.panX=b,l.panY=x;let S=b-m,C=x-h,w=(a+s)/2,T=(o+c)/2,E=Math.hypot(w-l.screenPanX,T-l.screenPanY);l.screenPanX=w,l.screenPanY=T;let D=Math.hypot(v,y),O=Math.hypot(g,_),k=this.#t?this.MIN_TOUCH_DISTANCE_TO_SCALE:this.MIN_TOUCH_DISTANCE_TO_PINCH+2*E;if(D=2){this.#b(e);return}let t=!!this.#f;this.#C(),this.#d.size===1&&this.#_(),t&<(e)}#C(){this.#f=null,this.#t=!1,this.#h=0,this.#c=!1,this.#m&&(this.#m.abort(),this.#m=null,this.#o?.())}destroy(){this.#C(),this.#d.clear(),this.#p?.abort(),this.#p=null,this.#l?.abort(),this.#l=null}},U=class e{#e=null;#t=null;#n=null;#r=null;#i=null;#a=!1;#o=null;#s=``;#c=null;#l=null;#u=null;#d=null;#f=null;#p=``;#m=!1;#h=null;#g=!1;#_=!1;#v=!1;#y=null;#b=0;#x=0;#S=null;#C=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#w=!1;#T=e._zIndex++;static _borderLineWidth=-1;static _colorManager=new rt;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let t=e.prototype._resizeWithKeyboard,n=it.TRANSLATE_SMALL,r=it.TRANSLATE_BIG;return M(this,`_resizerKeyboardManager`,new nt([[[`ArrowLeft`],t,{args:[-n,0]}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t,{args:[-r,0]}],[[`ArrowRight`],t,{args:[n,0]}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t,{args:[r,0]}],[[`ArrowUp`],t,{args:[0,-n]}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t,{args:[0,-r]}],[[`ArrowDown`],t,{args:[0,n]}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t,{args:[0,r]}],[[`Escape`],e.prototype._stopResizingWithKeyboard]]))}constructor(e){this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null,this.annotationElementId=e.annotationElementId||null,this.creationDate=e.creationDate||new Date,this.modificationDate=e.modificationDate||null,this.canAddComment=!0;let{rotation:t,rawDims:{pageWidth:n,pageHeight:r,pageX:i,pageY:a}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[n,r],this.pageTranslation=[i,a];let[o,s]=this.parentDimensions;this.x=e.x/o,this.y=e.y/s,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(e){this.pageIndex=e}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return M(this,`_defaultLineColor`,this._colorManager.getHexCode(`CanvasText`))}static deleteAnnotationElement(e){let t=new dt({id:e._uiManager.getId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(t,n){if(e._l10n??=t,e._l10nAlert??=Object.freeze({highlight:`pdfjs-editor-highlight-added-alert`,freetext:`pdfjs-editor-freetext-added-alert`,ink:`pdfjs-editor-ink-added-alert`,stamp:`pdfjs-editor-stamp-added-alert`,signature:`pdfjs-editor-signature-added-alert`}),e._l10nResizer??=Object.freeze({topLeft:`pdfjs-editor-resizer-top-left`,topMiddle:`pdfjs-editor-resizer-top-middle`,topRight:`pdfjs-editor-resizer-top-right`,middleRight:`pdfjs-editor-resizer-middle-right`,bottomRight:`pdfjs-editor-resizer-bottom-right`,bottomMiddle:`pdfjs-editor-resizer-bottom-middle`,bottomLeft:`pdfjs-editor-resizer-bottom-left`,middleLeft:`pdfjs-editor-resizer-middle-left`}),e._borderLineWidth!==-1)return;let r=getComputedStyle(document.documentElement);e._borderLineWidth=parseFloat(r.getPropertyValue(`--outline-width`))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){E(`Not implemented`)}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#w}set _isDraggable(e){this.#w=e,this.div?.classList.toggle(`draggable`,e)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){let[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#T}setParent(e){e===null?(this.#G(),this.#d?.remove(),this.#d=null):(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions),this.parent=e}focusin(e){this._focusEventsAllowed&&(this.#m?this.#m=!1:this.parent.setSelected(this))}focusout(e){this._focusEventsAllowed&&this.isAttachedToDOM&&(e.relatedTarget?.closest(`#${this.id}`)||(e.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove()))}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,n,r){let[i,a]=this.parentDimensions;[n,r]=this.screenToPageTranslation(n,r),this.x=(e+n)/i,this.y=(t+r)/a,this.fixAndSetPosition()}_moveAfterPaste(e,t){if(this.isClone){delete this.isClone;return}let[n,r]=this.parentDimensions;this.setAt(e*n,t*r,this.width*n,this.height*r),this._onTranslated()}#E([e,t],n,r){[n,r]=this.screenToPageTranslation(n,r),this.x+=n/e,this.y+=r/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(e,t){this.#E(this.parentDimensions,e,t)}translateInPage(e,t){this.#h||=[this.x,this.y,this.width,this.height],this.#E(this.pageDimensions,e,t),this.div.scrollIntoView({block:`nearest`})}translationDone(){this._onTranslated(this.x,this.y)}drag(e,t){this.#h||=[this.x,this.y,this.width,this.height];let{div:n,parentDimensions:[r,i]}=this;if(this.x+=e/r,this.y+=t/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:e,y:t}=this.div.getBoundingClientRect();this.parent.findNewParent(this,e,t)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:o}=this,[s,c]=this.getBaseTranslation();a+=s,o+=c;let{style:l}=n;l.left=`${(100*a).toFixed(2)}%`,l.top=`${(100*o).toFixed(2)}%`,this._onTranslating(a,o)}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!this.#h&&(this.#h[0]!==this.x||this.#h[1]!==this.y)}get _hasBeenResized(){return!!this.#h&&(this.#h[2]!==this.width||this.#h[3]!==this.height)}getBaseTranslation(){let[t,n]=this.parentDimensions,{_borderLineWidth:r}=e,i=r/t,a=r/n;switch(this.rotation){case 90:return[-i,a];case 180:return[i,a];case 270:return[i,-a];default:return[-i,-a]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){let{div:{style:t},pageDimensions:[n,r]}=this,{x:i,y:a,width:o,height:s}=this;if(o*=n,s*=r,i*=n,a*=r,this._mustFixPosition)switch(e){case 0:i=L(i,0,n-o),a=L(a,0,r-s);break;case 90:i=L(i,0,n-s),a=L(a,o,r);break;case 180:i=L(i,o,n),a=L(a,s,r);break;case 270:i=L(i,s,n),a=L(a,0,r-o)}this.x=i/=n,this.y=a/=r;let[c,l]=this.getBaseTranslation();i+=c,a+=l,t.left=`${(100*i).toFixed(2)}%`,t.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#D(e,t,n){switch(n){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}}screenToPageTranslation(t,n){return e.#D(t,n,this.parentRotation)}pageTranslationToScreen(t,n){return e.#D(t,n,360-this.parentRotation)}#O(e){switch(e){case 90:{let[e,t]=this.pageDimensions;return[0,-e/t,t/e,0]}case 180:return[-1,0,0,-1];case 270:{let[e,t]=this.pageDimensions;return[0,e/t,-t/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:e,pageDimensions:[t,n]}=this;return[t*e,n*e]}setDims(){let{div:{style:e},width:t,height:n}=this;e.width=`${(100*t).toFixed(2)}%`,e.height=`${(100*n).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#k(){if(this.#c)return;this.#c=document.createElement(`div`),this.#c.classList.add(`resizers`);let e=this._willKeepAspectRatio?[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`]:[`topLeft`,`topMiddle`,`topRight`,`middleRight`,`bottomRight`,`bottomMiddle`,`bottomLeft`,`middleLeft`],t=this._uiManager._signal;for(let n of e){let e=document.createElement(`div`);this.#c.append(e),e.classList.add(`resizer`,n),e.setAttribute(`data-resizer-name`,n),e.addEventListener(`pointerdown`,this.#A.bind(this,n),{signal:t}),e.addEventListener(`contextmenu`,R,{signal:t}),e.tabIndex=-1}this.div.prepend(this.#c)}#A(e,t){t.preventDefault();let{isMac:n}=F.platform;if(t.button!==0||t.ctrlKey&&n)return;this.#n?.toggle(!1);let r=this._isDraggable;this._isDraggable=!1,this.#l=[t.screenX,t.screenY];let i=new AbortController,a=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener(`pointermove`,this.#N.bind(this,e),{passive:!0,capture:!0,signal:a}),window.addEventListener(`touchmove`,z,{passive:!1,signal:a}),window.addEventListener(`contextmenu`,R,{signal:a}),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let o=this.parent.div.style.cursor,s=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;let c=()=>{i.abort(),this.parent.togglePointerEvents(!0),this.#n?.toggle(!0),this._isDraggable=r,this.parent.div.style.cursor=o,this.div.style.cursor=s,this.#M()};window.addEventListener(`pointerup`,c,{signal:a}),window.addEventListener(`blur`,c,{signal:a})}#j(e,t,n,r){this.width=n,this.height=r,this.x=e,this.y=t,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#M(){if(!this.#u)return;let{savedX:e,savedY:t,savedWidth:n,savedHeight:r}=this.#u;this.#u=null;let i=this.x,a=this.y,o=this.width,s=this.height;(i!==e||a!==t||o!==n||s!==r)&&this.addCommands({cmd:this.#j.bind(this,i,a,o,s),undo:this.#j.bind(this,e,t,n,r),mustExec:!0})}static _round(e){return Math.round(e*1e4)/1e4}#N(t,n){let[r,i]=this.parentDimensions,a=this.x,o=this.y,s=this.width,c=this.height,l=e.MIN_SIZE/r,u=e.MIN_SIZE/i,d=this.#O(this.rotation),f=(e,t)=>[d[0]*e+d[2]*t,d[1]*e+d[3]*t],p=this.#O(360-this.rotation),m=(e,t)=>[p[0]*e+p[2]*t,p[1]*e+p[3]*t],h,g,_=!1,v=!1;switch(t){case`topLeft`:_=!0,h=(e,t)=>[0,0],g=(e,t)=>[e,t];break;case`topMiddle`:h=(e,t)=>[e/2,0],g=(e,t)=>[e/2,t];break;case`topRight`:_=!0,h=(e,t)=>[e,0],g=(e,t)=>[0,t];break;case`middleRight`:v=!0,h=(e,t)=>[e,t/2],g=(e,t)=>[0,t/2];break;case`bottomRight`:_=!0,h=(e,t)=>[e,t],g=(e,t)=>[0,0];break;case`bottomMiddle`:h=(e,t)=>[e/2,t],g=(e,t)=>[e/2,0];break;case`bottomLeft`:_=!0,h=(e,t)=>[0,t],g=(e,t)=>[e,0];break;case`middleLeft`:v=!0,h=(e,t)=>[0,t/2],g=(e,t)=>[e,t/2]}let y=h(s,c),b=g(s,c),x=f(...b),S=e._round(a+x[0]),C=e._round(o+x[1]),w=1,T=1,E,D;if(n.fromKeyboard)({deltaX:E,deltaY:D}=n);else{let{screenX:e,screenY:t}=n,[r,i]=this.#l;[E,D]=this.screenToPageTranslation(e-r,t-i),this.#l[0]=e,this.#l[1]=t}if([E,D]=m(E/r,D/i),_){let e=Math.hypot(s,c);w=T=Math.max(Math.min(Math.hypot(b[0]-y[0]-E,b[1]-y[1]-D)/e,1/s,1/c),l/s,u/c)}else v?w=L(Math.abs(b[0]-y[0]-E),l,1)/s:T=L(Math.abs(b[1]-y[1]-D),u,1)/c;let O=e._round(s*w),k=e._round(c*T);x=f(...g(O,k));let A=S-x[0],j=C-x[1];this.#h||=[this.x,this.y,this.width,this.height],this.width=O,this.height=k,this.x=A,this.y=j,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#n?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#_)return this._editToolbar;this._editToolbar=new Ye(this),this.div.append(this._editToolbar.render());let{toolbarButtons:e}=this;if(e)for(let[t,n]of e)await this._editToolbar.addButton(t,n);return this.hasComment||this._editToolbar.addButton(`comment`,this.addCommentButton()),this._editToolbar.addButton(`delete`),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore(`comment`,this.addCommentButton(),`.deleteButton`)}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton(`comment`)}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#n?.destroy()}addContainer(e){let t=this._editToolbar?.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#n||(at.initialize(e._l10n),this.#n=new at(this),this.#e&&=(this.#n.data=this.#e,null)),this.#n}get altTextData(){return this.#n?.data}set altTextData(e){this.#n&&(this.#n.data=e)}get guessedAltText(){return this.#n?.guessedText}async setGuessedAltText(e){await this.#n?.setGuessedText(e)}serializeAltText(e){return this.#n?.serialize(e)}hasAltText(){return!!this.#n&&!this.#n.isEmpty()}hasAltTextData(){return this.#n?.hasData()??!1}focusCommentButton(){this.#r?.focusButton()}addCommentButton(){return this.canAddComment?this.#r||=new ot(this):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager()){if(this.#i){this._uiManager.isEditingMode()&&this.#i.classList.remove(`hidden`);return}this.hasComment&&(this.#i=this.#r.renderForStandalone(),this.div.append(this.#i))}}removeStandaloneCommentButton(){this.#r.removeStandaloneCommentButton(),this.#i=null}hideStandaloneCommentButton(){this.#i?.classList.add(`hidden`)}get comment(){if(!this.#r)return null;let{data:{richText:e,text:t,date:n,deleted:r}}=this.#r;return{text:t,richText:e,date:n,deleted:r,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(e){this.#r||=new ot(this),typeof e==`object`&&e?this.#r.restoreData(e):this.#r.data=e,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:e,popupRef:t,richText:n}){if(!t||(this.#r||=new ot(this),this.#r.setInitialText(e,n),!this.annotationElementId))return;let r=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);r&&this.updateFromAnnotationLayer(r)}get hasEditedComment(){return this.#r?.hasBeenEdited()}get hasDeletedComment(){return this.#r?.isDeleted()}get hasComment(){return!!this.#r&&!this.#r.isEmpty()&&!this.#r.isDeleted()}async editComment(e){this.#r||=new ot(this),this.#r.edit(e)}toggleComment(e,t=void 0){this.hasComment&&this._uiManager.toggleComment(this,e,t)}setSelectedCommentButton(e){this.#r.setSelectedButton(e)}addComment(e){if(this.hasEditedComment){let[,,,t]=e.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,i=r+n+1,a=t-100,o=i+180;e.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[i,a,o,t]}}}updateFromAnnotationLayer({popup:{contents:e,deleted:t}}){this.#r.data=t?null:e}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){let e=this.div=document.createElement(`div`);e.setAttribute(`data-editor-rotation`,(360-this.rotation)%360),e.className=this.name,e.setAttribute(`id`,this.id),e.tabIndex=this.#a?-1:0,e.setAttribute(`role`,`application`),this.defaultL10nId&&e.setAttribute(`data-l10n-id`,this.defaultL10nId),this._isVisible||e.classList.add(`hidden`),this.setInForeground(),this.#z();let[t,n]=this.parentDimensions;this.parentRotation%180!=0&&(e.style.maxWidth=`${(100*n/t).toFixed(2)}%`,e.style.maxHeight=`${(100*t/n).toFixed(2)}%`);let[r,i]=this.getInitialTranslation();return this.translate(r,i),Qe(this,e,[`keydown`,`pointerdown`,`dblclick`]),this.#B(),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),e}#P(){this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#n?.toggle(!1),this.parent.togglePointerEvents(!1)}#F(t,n,r){let i=.7,a=r/n*i+1-i;if(a===1)return;let o=this.#O(this.rotation),s=(e,t)=>[o[0]*e+o[2]*t,o[1]*e+o[3]*t],[c,l]=this.parentDimensions,u=this.x,d=this.y,f=this.width,p=this.height,m=e.MIN_SIZE/c,h=e.MIN_SIZE/l;a=Math.max(Math.min(a,1/f,1/p),m/f,h/p);let g=e._round(f*a),_=e._round(p*a);if(g===f&&_===p)return;this.#h||=[u,d,f,p];let v=s(f/2,p/2),y=e._round(u+v[0]),b=e._round(d+v[1]),x=s(g/2,_/2);this.x=y-x[0],this.y=b-x[1],this.width=g,this.height=_,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#I(){this.#n?.toggle(!0),this.parent.togglePointerEvents(!0),this.#M()}pointerdown(e){let{isMac:t}=F.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(this.#m=!0,this._isDraggable){this.#R(e);return}this.#L(e)}#L(e){let{isMac:t}=F.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)}#R(e){let{isSelected:t}=this;this._uiManager.setUpDragSession();let n=!1,r=new AbortController,i=this._uiManager.combinedSignal(r),a={capture:!0,passive:!1,signal:i},o=e=>{r.abort(),this.#o=null,this.#m=!1,this._uiManager.endDragSession()||this.#L(e),n&&this._onStopDragging()};t&&(this.#b=e.clientX,this.#x=e.clientY,this.#o=e.pointerId,this.#s=e.pointerType,window.addEventListener(`pointermove`,e=>{n||(n=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());let{clientX:t,clientY:r,pointerId:i}=e;if(i!==this.#o){z(e);return}let[a,o]=this.screenToPageTranslation(t-this.#b,r-this.#x);this.#b=t,this.#x=r,this._uiManager.dragSelectedEditors(a,o),this.div.scrollIntoView({block:`nearest`})},a),window.addEventListener(`touchmove`,z,a),window.addEventListener(`pointerdown`,e=>{e.pointerType===this.#s&&(this.#C||e.isPrimary)&&o(e),z(e)},a));let s=e=>{if(!this.#o||this.#o===e.pointerId){o(e);return}z(e)};window.addEventListener(`pointerup`,s,{signal:i}),window.addEventListener(`blur`,s,{signal:i})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#y&&clearTimeout(this.#y),this.#y=setTimeout(()=>{this.#y=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(e,t,n){e.changeParent(this),this.x=t,this.y=n,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,n=this.rotation){let r=this.parentScale,[i,a]=this.pageDimensions,[o,s]=this.pageTranslation,c=e/r,l=t/r,u=this.x*i,d=this.y*a,f=this.width*i,p=this.height*a;switch(n){case 0:return[u+c+o,a-d-l-p+s,u+c+f+o,a-d-l+s];case 90:return[u+l+o,a-d+c+s,u+l+p+o,a-d+c+f+s];case 180:return[u-c-f+o,a-d+l+s,u-c+o,a-d+l+p+s];case 270:return[u-l-p+o,a-d-c-f+s,u-l+o,a-d-c+s];default:throw Error(`Invalid rotation`)}}getRectInCurrentCoords(e,t){let[n,r,i,a]=e,o=i-n,s=a-r;switch(this.rotation){case 0:return[n,t-a,o,s];case 90:return[n,t-r,s,o];case 180:return[i,t-r,o,s];case 270:return[i,t-a,s,o];default:throw Error(`Invalid rotation`)}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&e._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#r?.onUpdatedColor()}getData(){let{comment:{text:e,color:t,date:n,opacity:r,deleted:i,richText:a},uid:o,pageIndex:s,creationDate:c,modificationDate:l}=this;return{id:o,pageIndex:s,rect:this.getPDFRect(),richText:a,contentsObj:{str:e},creationDate:c,modificationDate:n||l,popupRef:!i,color:t,opacity:r}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#_=!0,!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),this.#_=!1,!0):!1}isInEditMode(){return this.#_}shouldGetKeyboardEvents(){return this.#v}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){let{top:e,left:t,bottom:n,right:r}=this.getClientDimensions(),{innerHeight:i,innerWidth:a}=window;return t0&&e0}#z(){if(this.#f||!this.div)return;this.#f=new AbortController;let e=this._uiManager.combinedSignal(this.#f);this.div.addEventListener(`focusin`,this.focusin.bind(this),{signal:e}),this.div.addEventListener(`focusout`,this.focusout.bind(this),{signal:e})}#B(){this.#C||!this.div||!this.isResizable||!this._uiManager._supportsPinchToZoom||(this.#C=new ut({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#P.bind(this),onPinching:this.#F.bind(this),onPinchEnd:this.#I.bind(this),signal:this._uiManager._signal}))}rebuild(){this.#z(),this.#B()}rotate(e){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||``}}serialize(e=!1,t=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||``}}static async deserialize(e,t,n){let r=new this.prototype.constructor({parent:t,id:n.getId(),uiManager:n,annotationElementId:e.annotationElementId,creationDate:e.creationDate,modificationDate:e.modificationDate});r.rotation=e.rotation,r.#e=e.accessibilityData,r._isCopy=e.isCopy||!1;let[i,a]=r.pageDimensions,[o,s,c,l]=r.getRectInCurrentCoords(e.rect,a);return r.x=o/i,r.y=s/a,r.width=c/i,r.height=l/a,r}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#f?.abort(),this.#f=null,this.isEmpty()||this.commit(),this.#C?.destroy(),this.#C=null,this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#y&&=(clearTimeout(this.#y),null),this.#G(),this.removeEditToolbar(),this.#S){for(let e of this.#S.values())clearTimeout(e);this.#S=null}this.parent=null,this.#d?.remove(),this.#d=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#k(),this.#c.classList.remove(`hidden`))}get toolbarPosition(){return null}get commentButtonPosition(){return this._uiManager.direction===`ltr`?[1,0]:[0,0]}get commentButtonPositionInPage(){let{commentButtonPosition:[t,n]}=this,[r,i,a,o]=this.getPDFRect();return[e._round(r+(a-r)*t),e._round(i+(o-i)*(1-n))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#r.commentPopupPositionInLayer}set commentPopupPosition(e){this.#r.commentPopupPositionInLayer=e}hasDefaultPopupPosition(){return this.#r.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#r.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(e){this.#r?.setCommentButtonStates(e)}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!==`Enter`)return;this._uiManager.setSelected(this),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let n=this.#c.children;if(!this.#t){this.#t=Array.from(n);let t=this.#V.bind(this),r=this.#H.bind(this),i=this._uiManager._signal;for(let n of this.#t){let a=n.getAttribute(`data-resizer-name`);n.setAttribute(`role`,`spinbutton`),n.addEventListener(`keydown`,t,{signal:i}),n.addEventListener(`blur`,r,{signal:i}),n.addEventListener(`focus`,this.#U.bind(this,a),{signal:i}),n.setAttribute(`data-l10n-id`,e._l10nResizer[a])}}let r=this.#t[0],i=0;for(let e of n){if(e===r)break;i++}let a=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(a!==i){if(ai)for(let e=0;e{this.div?.classList.contains(`selectedEditor`)&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#n?.toggleAltTextBadge(!1)}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#c?.classList.add(`hidden`),this.div?.classList.remove(`selectedEditor`),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#n?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(e,t){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(e){e.target.nodeName!==`BUTTON`&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#g}set isEditing(e){this.#g=e,this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:`added`}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){this.#S||=new Map;let{action:n}=t,r=this.#S.get(n);r&&clearTimeout(r),r=setTimeout(()=>{this._reportTelemetry(t),this.#S.delete(n),this.#S.size===0&&(this.#S=null)},e._telemetryTimeout),this.#S.set(n,r);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:t}})}show(e=this._isVisible){this.div.classList.toggle(`hidden`,!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),this.#a=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#a=!0}updateFakeAnnotationElement(e){if(!this.#d&&!this.deleted){this.#d=e.addFakeAnnotation(this);return}if(this.deleted){this.#d.remove(),this.#d=null;return}(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#d.updateEdited({rect:this.getPDFRect(),popup:this.comment})}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let t=e.container.querySelector(`.annotationContent`);if(!t)t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.container.prepend(t);else if(t.nodeName===`CANVAS`){let e=t;t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.before(t)}return t}resetAnnotationElement(e){let{firstElementChild:t}=e.container;t?.nodeName===`DIV`&&t.classList.contains(`annotationContent`)&&t.remove()}},dt=class extends U{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}},ft=3285377520,W=4294901760,pt=65535,mt=class{constructor(e){this.h1=e?e&4294967295:ft,this.h2=e?e&4294967295:ft}update(e){let t,n;if(typeof e==`string`){t=new Uint8Array(e.length*2),n=0;for(let r=0,i=e.length;r>>8,t[n++]=i&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),n=t.byteLength;else throw Error(`Invalid data format, must be a string or TypedArray.`);let r=n>>2,i=n-r*4,a=new Uint32Array(t.buffer,0,r),o=0,s=0,c=this.h1,l=this.h2,u=3432918353,d=461845907,f=11601,p=13715;for(let e=0;e>>17,o=o*d&W|o*p&pt,c^=o,c=c<<13|c>>>19,c=c*5+3864292196):(s=a[e],s=s*u&W|s*f&pt,s=s<<15|s>>>17,s=s*d&W|s*p&pt,l^=s,l=l<<13|l>>>19,l=l*5+3864292196);switch(o=0,i){case 3:o^=t[r*4+2]<<16;case 2:o^=t[r*4+1]<<8;case 1:o^=t[r*4],o=o*u&W|o*f&pt,o=o<<15|o>>>17,o=o*d&W|o*p&pt,r&1?c^=o:l^=o}this.h1=c,this.h2=l}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&W|e*36045&pt,t=t*4283543511&W|((t<<16|e>>>16)*2950163797&W)>>>16,e^=t>>>1,e=e*444984403&W|e*60499&pt,t=t*3301882366&W|((t<<16|e>>>16)*3120437893&W)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}},ht=Object.freeze({map:null,hash:``,transfer:void 0}),gt=class{#e=!1;#t=null;#n=null;#r=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(e,t){let n=this.#r.get(e);return n===void 0?t:Object.assign(t,n)}getRawValue(e){return this.#r.get(e)}remove(e){let t=this.#r.get(e);t!==void 0&&(t instanceof U&&this.#n.delete(t.annotationElementId),this.#r.delete(e),this.#r.size===0&&this.resetModified(),!this.#r.values().some(e=>e instanceof U)&&this.onAnnotationEditor?.(null))}setValue(e,t){let n=this.#r.get(e),r=!1;if(n!==void 0)for(let[e,i]of Object.entries(t))n[e]!==i&&(r=!0,n[e]=i);else r=!0,this.#r.set(e,t);r&&this.#i(),t instanceof U&&((this.#n||=new Map).set(t.annotationElementId,t),this.onAnnotationEditor?.(t.constructor._type))}has(e){return this.#r.has(e)}get size(){return this.#r.size}#i(){this.#e||(this.#e=!0,this.onSetModified?.())}resetModified(){this.#e&&(this.#e=!1,this.onResetModified?.())}get print(){return new _t(this)}get serializable(){if(this.#r.size===0)return ht;let e=new Map,t=new mt,n=[],r=Object.create(null),i=!1;for(let[n,a]of this.#r){let o=a instanceof U?a.serialize(!1,r):a;a.page&&(a.pageIndex=a.page._pageIndex,delete a.page),o&&(e.set(n,o),t.update(`${n}:${JSON.stringify(o)}`),i||=!!o.bitmap)}if(i)for(let t of e.values())t.bitmap&&n.push(t.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:n}:ht}get editorStats(){let e=null,t=new Map,n=0,r=0;for(let i of this.#r.values()){if(!(i instanceof U)){i.popup&&(i.popup.deleted?r+=1:n+=1);continue}i.isCommentDeleted?r+=1:i.hasEditedComment&&(n+=1);let a=i.telemetryFinalData;if(!a)continue;let{type:o}=a;t.getOrInsertComputed(o,()=>Object.getPrototypeOf(i).constructor),e||=Object.create(null);let s=e[o]||=new Map;for(let[e,t]of Object.entries(a)){if(e===`type`)continue;let n=s.getOrInsertComputed(e,me);n.set(t,(n.get(t)??0)+1)}}if((r>0||n>0)&&(e||=Object.create(null),e.comments={deleted:r,edited:n}),!e)return null;for(let[n,r]of t)e[n]=r.computeTelemetryFinalData(e[n]);return e}resetModifiedIds(){this.#t=null}updateEditor(e,t){let n=this.#n?.get(e);return n?(n.updateFromAnnotationLayer(t),!0):!1}getEditor(e){return this.#n?.get(e)||null}get modifiedIds(){if(this.#t)return this.#t;let e=[];if(this.#n)for(let t of this.#n.values())t.serialize()&&e.push(t.annotationElementId);let t=``;if(e.length){let n=new mt;n.update(e.join(`,`)),t=n.hexdigest()}return this.#t={ids:new Set(e),hash:t}}[Symbol.iterator](){return this.#r.entries()}},_t=class extends gt{#e=ht;constructor(e){super();let{serializable:t}=e;if(t===ht)return;let{map:n,hash:r,transfer:i}=t,a=structuredClone(n,i?{transfer:i}:null);this.#e={map:a,hash:r,transfer:[]}}get print(){E(`Should not call PrintAnnotationStorage.print`)}get serializable(){return this.#e}get modifiedIds(){return M(this,`modifiedIds`,{ids:new Set,hash:``})}},vt=`__forcedDependency`,{floor:yt,ceil:bt}=Math;function xt(e,t,n,r,i,a){e[t*4+0]=Math.min(e[t*4+0],n),e[t*4+1]=Math.min(e[t*4+1],r),e[t*4+2]=Math.max(e[t*4+2],i),e[t*4+3]=Math.max(e[t*4+3],a)}function St(e,t,n,r,i){let a;e?(e<0&&(a=i[0],i[0]=i[2],i[2]=a),i[0]*=e,i[2]*=e,t<0&&(a=i[1],i[1]=i[3],i[3]=a),i[1]*=t,i[3]*=t):i.fill(0),i[0]+=n,i[1]+=r,i[2]+=n,i[3]+=r}var Ct=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0],wt=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get length(){return this.#e.length}isEmpty(e){return this.#e[e]===Ct}minX(e){return this.#t[e*4+0]/256}minY(e){return this.#t[e*4+1]/256}maxX(e){return(this.#t[e*4+2]+1)/256}maxY(e){return(this.#t[e*4+3]+1)/256}},Tt=(e,t)=>e?.getOrInsertComputed(t,()=>({dependencies:new Set,isRenderingOperation:!1})),Et=class{#e=[[1,0,0,1,0,0]];#t=[-1/0,-1/0,1/0,1/0];#n=new Float64Array(n);_pendingBBoxIdx=-1;#r;#i;#a;#o;_savesStack=[];_markedContentStack=[];constructor(e,t){this.#r=e.width,this.#i=e.height,this.#s(t)}growOperationsCount(e){e>=this.#o.length&&this.#s(e,this.#o)}#s(e,t){let n=new ArrayBuffer(e*4);this.#a=new Uint8ClampedArray(n),this.#o=new Uint32Array(n),t&&t.length>0?(this.#o.set(t),this.#o.fill(Ct,t.length)):this.#o.fill(Ct)}get clipBox(){return this.#t}save(e){return this.#t={__proto__:this.#t},this._savesStack.push(e),this}restore(e,t){let n=Object.getPrototypeOf(this.#t);if(n===null)return this;this.#t=n;let r=this._savesStack.pop();return r!==void 0&&(t?.(r,e),this.#o[e]=this.#o[r]),this}recordOpenMarker(e){return this._savesStack.push(e),this}getOpenMarker(){return this._savesStack.length===0?null:this._savesStack.at(-1)}recordCloseMarker(e,t){let n=this._savesStack.pop();return n!==void 0&&(t?.(n,e),this.#o[e]=this.#o[n]),this}beginMarkedContent(e){return this._markedContentStack.push(e),this}endMarkedContent(e,t){let n=this._markedContentStack.pop();return n!==void 0&&(t?.(n,e),this.#o[e]=this.#o[n]),this}pushBaseTransform(e){return this.#e.push(I.multiplyByDOMMatrix(this.#e.at(-1),e.getTransform())),this}popBaseTransform(){return this.#e.length>1&&this.#e.pop(),this}resetBBox(e){return this._pendingBBoxIdx!==e&&(this._pendingBBoxIdx=e,this.#n.set(n,0)),this}recordClipBox(e,t,r,i,a,o){let s=I.multiplyByDOMMatrix(this.#e.at(-1),t.getTransform()),c=n.slice();I.axialAlignedBoundingBox([r,a,i,o],s,c);let l=I.intersect(this.#t,c);return l?(this.#t[0]=l[0],this.#t[1]=l[1],this.#t[2]=l[2],this.#t[3]=l[3]):(this.#t[0]=this.#t[1]=1/0,this.#t[2]=this.#t[3]=-1/0),this}recordBBox(e,t,r,i,a,o){let s=this.#t;if(s[0]===1/0)return this;let c=I.multiplyByDOMMatrix(this.#e.at(-1),t.getTransform());if(s[0]===-1/0)return I.axialAlignedBoundingBox([r,a,i,o],c,this.#n),this;let l=n.slice();return I.axialAlignedBoundingBox([r,a,i,o],c,l),this.#n[0]=L(l[0],s[0],this.#n[0]),this.#n[1]=L(l[1],s[1],this.#n[1]),this.#n[2]=L(l[2],this.#n[2],s[2]),this.#n[3]=L(l[3],this.#n[3],s[3]),this}recordFullPageBBox(e){return this.#n[0]=Math.max(0,this.#t[0]),this.#n[1]=Math.max(0,this.#t[1]),this.#n[2]=Math.min(this.#r,this.#t[2]),this.#n[3]=Math.min(this.#i,this.#t[3]),this}recordOperation(e,t=!1,n){if(this._pendingBBoxIdx!==e)return this;let r=yt(this.#n[0]*256/this.#r),i=yt(this.#n[1]*256/this.#i),a=bt(this.#n[2]*256/this.#r),o=bt(this.#n[3]*256/this.#i);if(xt(this.#a,e,r,i,a,o),n)for(let t of n)for(let n of t)n!==e&&xt(this.#a,n,r,i,a,o);return t||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(e){return this._pendingBBoxIdx===e&&(this._pendingBBoxIdx=-1,this.#t[0]=Math.max(this.#t[0],this.#n[0]),this.#t[1]=Math.max(this.#t[1],this.#n[1]),this.#t[2]=Math.min(this.#t[2],this.#n[2]),this.#t[3]=Math.min(this.#t[3],this.#n[3])),this}take(){return new wt(this.#o,this.#a)}takeDebugMetadata(){throw Error(`Unreachable`)}recordSimpleData(e,t){return this}recordIncrementalData(e,t){return this}resetIncrementalData(e,t){return this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this}recordFutureForcedDependency(e,t){return this}inheritSimpleDataAsFutureForcedDependencies(e){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(e,t,n,r=1,i=0,a=0,o){return this}getSimpleIndex(e){}recordDependencies(e,t){return this}recordNamedDependency(e,t){return this}recordShowTextOperation(e,t=!1){return this}},Dt=class{#e={__proto__:null};#t={__proto__:null,transform:[],moveText:[],sameLineText:[],[vt]:[]};#n=new Map;#r=new Set;#i=new Map;#a;#o;#s;constructor(e,t=!1){this.#s=e,t&&(this.#a=new Map,this.#o=(e,t)=>{Tt(this.#a,t).dependencies.add(e)})}get clipBox(){return this.#s.clipBox}growOperationsCount(e){this.#s.growOperationsCount(e)}save(e){return this.#e={__proto__:this.#e},this.#t={__proto__:this.#t,transform:{__proto__:this.#t.transform},moveText:{__proto__:this.#t.moveText},sameLineText:{__proto__:this.#t.sameLineText},[vt]:{__proto__:this.#t[vt]}},this.#s.save(e),this}restore(e){this.#s.restore(e,this.#o);let t=Object.getPrototypeOf(this.#e);return t===null?this:(this.#e=t,this.#t=Object.getPrototypeOf(this.#t),this)}recordOpenMarker(e){return this.#s.recordOpenMarker(e,this.#o),this}getOpenMarker(){return this.#s.getOpenMarker()}recordCloseMarker(e){return this.#s.recordCloseMarker(e,this.#o),this}beginMarkedContent(e){return this.#s.beginMarkedContent(e),this}endMarkedContent(e){return this.#s.endMarkedContent(e,this.#o),this}pushBaseTransform(e){return this.#s.pushBaseTransform(e),this}popBaseTransform(){return this.#s.popBaseTransform(),this}recordSimpleData(e,t){return this.#e[e]=t,this}recordIncrementalData(e,t){return this.#t[e].push(t),this}resetIncrementalData(e,t){return this.#t[e].length=0,this}recordNamedData(e,t){return this.#n.set(e,t),this}recordSimpleDataFromNamed(e,t,n){this.#e[e]=this.#n.get(t)??n}recordFutureForcedDependency(e,t){return this.recordIncrementalData(vt,t),this}inheritSimpleDataAsFutureForcedDependencies(e){for(let t of e)t in this.#e&&this.recordFutureForcedDependency(t,this.#e[t]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(let e of this.#r)this.recordFutureForcedDependency(vt,e);return this}resetBBox(e){return this.#s.resetBBox(e),this}recordClipBox(e,t,n,r,i,a){return this.#s.recordClipBox(e,t,n,r,i,a),this}recordBBox(e,t,n,r,i,a){return this.#s.recordBBox(e,t,n,r,i,a),this}recordCharacterBBox(e,t,n,r=1,i=0,a=0,o){let s=n.bbox,c,l;if(s&&(c=s[2]!==s[0]&&s[3]!==s[1]&&this.#i.get(n),c!==!1&&(l=[0,0,0,0],I.axialAlignedBoundingBox(s,n.fontMatrix,l),(r!==1||i!==0||a!==0)&&St(r,-r,i,a,l),c)))return this.recordBBox(e,t,l[0],l[2],l[1],l[3]);if(!o)return this.recordFullPageBBox(e);let u=o();return s&&l&&c===void 0&&(c=l[0]<=i-u.actualBoundingBoxLeft&&l[2]>=i+u.actualBoundingBoxRight&&l[1]<=a-u.actualBoundingBoxAscent&&l[3]>=a+u.actualBoundingBoxDescent,this.#i.set(n,c),c)?this.recordBBox(e,t,l[0],l[2],l[1],l[3]):this.recordBBox(e,t,i-u.actualBoundingBoxLeft,i+u.actualBoundingBoxRight,a-u.actualBoundingBoxAscent,a+u.actualBoundingBoxDescent)}recordFullPageBBox(e){return this.#s.recordFullPageBBox(e),this}getSimpleIndex(e){return this.#e[e]}recordDependencies(e,t){let n=this.#r,r=this.#e,i=this.#t;for(let e of t)e in this.#e?n.add(r[e]):e in i&&i[e].forEach(n.add,n);return this}recordNamedDependency(e,t){return this.#n.has(t)&&this.#r.add(this.#n.get(t)),this}recordOperation(e,t=!1){if(this.recordDependencies(e,[vt]),this.#a){let t=Tt(this.#a,e),{dependencies:n}=t;this.#r.forEach(n.add,n),this.#s._savesStack.forEach(n.add,n),this.#s._markedContentStack.forEach(n.add,n),n.delete(e),t.isRenderingOperation=!0}let n=!t&&e===this.#s._pendingBBoxIdx;return this.#s.recordOperation(e,t,[this.#r,this.#s._savesStack,this.#s._markedContentStack]),n&&this.#r.clear(),this}recordShowTextOperation(e,t=!1){let n=Array.from(this.#r);this.recordOperation(e,t),this.recordIncrementalData(`sameLineText`,e);for(let e of n)this.recordIncrementalData(`sameLineText`,e);return this}bboxToClipBoxDropOperation(e,t=!1){let n=!t&&e===this.#s._pendingBBoxIdx;return this.#s.bboxToClipBoxDropOperation(e),n&&this.#r.clear(),this}take(){return this.#i.clear(),this.#s.take()}takeDebugMetadata(){return this.#a}},Ot=class e{#e;#t;#n;#r=0;#i=0;constructor(t,n,r){if(t instanceof e&&t.#n===!!r)return t;this.#e=t,this.#t=n,this.#n=!!r}get clipBox(){return this.#e.clipBox}growOperationsCount(){throw Error(`Unreachable`)}save(e){return this.#i++,this.#e.save(this.#t),this}restore(e){return this.#i>0&&(this.#e.restore(this.#t),this.#i--),this}recordOpenMarker(e){return this.#r++,this}getOpenMarker(){return this.#r>0?this.#t:this.#e.getOpenMarker()}recordCloseMarker(e){return this.#r--,this}beginMarkedContent(e){return this}endMarkedContent(e){return this}pushBaseTransform(e){return this.#e.pushBaseTransform(e),this}popBaseTransform(){return this.#e.popBaseTransform(),this}recordSimpleData(e,t){return this.#e.recordSimpleData(e,this.#t),this}recordIncrementalData(e,t){return this.#e.recordIncrementalData(e,this.#t),this}resetIncrementalData(e,t){return this.#e.resetIncrementalData(e,this.#t),this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this.#e.recordSimpleDataFromNamed(e,t,this.#t),this}recordFutureForcedDependency(e,t){return this.#e.recordFutureForcedDependency(e,this.#t),this}inheritSimpleDataAsFutureForcedDependencies(e){return this.#e.inheritSimpleDataAsFutureForcedDependencies(e),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#e.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(e){return this.#n||this.#e.resetBBox(this.#t),this}recordClipBox(e,t,n,r,i,a){return this.#n||this.#e.recordClipBox(this.#t,t,n,r,i,a),this}recordBBox(e,t,n,r,i,a){return this.#n||this.#e.recordBBox(this.#t,t,n,r,i,a),this}recordCharacterBBox(e,t,n,r,i,a,o){return this.#n||this.#e.recordCharacterBBox(this.#t,t,n,r,i,a,o),this}recordFullPageBBox(e){return this.#n||this.#e.recordFullPageBBox(this.#t),this}getSimpleIndex(e){return this.#e.getSimpleIndex(e)}recordDependencies(e,t){return this.#e.recordDependencies(this.#t,t),this}recordNamedDependency(e,t){return this.#e.recordNamedDependency(this.#t,t),this}recordOperation(e){return this.#e.recordOperation(this.#t,!0),this}recordShowTextOperation(e){return this.#e.recordShowTextOperation(this.#t,!0),this}bboxToClipBoxDropOperation(e){return this.#n||this.#e.bboxToClipBoxDropOperation(this.#t,!0),this}take(){throw Error(`Unreachable`)}takeDebugMetadata(){throw Error(`Unreachable`)}},G={stroke:[`path`,`transform`,`filter`,`strokeColor`,`strokeAlpha`,`lineWidth`,`lineCap`,`lineJoin`,`miterLimit`,`dash`],fill:[`path`,`transform`,`filter`,`fillColor`,`fillAlpha`,`globalCompositeOperation`,`SMask`],imageXObject:[`transform`,`SMask`,`filter`,`fillAlpha`,`strokeAlpha`,`globalCompositeOperation`],rawFillPath:[`filter`,`fillColor`,`fillAlpha`],showText:[`transform`,`leading`,`charSpacing`,`wordSpacing`,`hScale`,`textRise`,`moveText`,`textMatrix`,`font`,`fontObj`,`filter`,`fillColor`,`textRenderingMode`,`SMask`,`fillAlpha`,`strokeAlpha`,`globalCompositeOperation`,`sameLineText`],transform:[`transform`],transformAndFill:[`transform`,`fillColor`]},kt=class e{#e;#t;#n=4;#r=0;#i=new e.#a(this.#n*6);static#a=F.isFloat16ArraySupported?Float16Array:Float32Array;constructor(e){this.#e=e.width,this.#t=e.height}record(t,r,i,a){if(this.#r===this.#n){this.#n*=2;let t=new e.#a(this.#n*6);t.set(this.#i),this.#i=t}let o=B(t),s;if(a[0]!==1/0){let e=n.slice();I.axialAlignedBoundingBox([0,-i,r,0],o,e);let t=I.intersect(a,e);if(!t)return;let[c,l,u,d]=t;if(c!==e[0]||l!==e[1]||u!==e[2]||d!==e[3]){let e=Math.atan2(o[1],o[0]),t=Math.abs(Math.sin(e)),n=Math.abs(Math.cos(e));if(t<1e-6||n<1e-6||Math.abs(t-n)<1e-6)s=[c,l,c,d,u,l];else{let e=u-c,r=d-l,i=t*t,a=n*n,o=n*t,f=a-i,p=(r*a-e*o)/f;s=[c+(r*o-e*i)/f,l,c,l+p,u,d-p]}}}s||(s=[0,-i,0,0,r,-i],I.applyTransform(s,o,0),I.applyTransform(s,o,2),I.applyTransform(s,o,4)),s[0]/=this.#e,s[1]/=this.#t,s[2]/=this.#e,s[3]/=this.#t,s[4]/=this.#e,s[5]/=this.#t,this.#i.set(s,this.#r*6),this.#r++}take(){return this.#i.subarray(0,this.#r*6)}},At=/\p{Cc}/u;function jt(e){let t=e[0];if(e.length<2||t!==`"`&&t!==`'`||e.at(-1)!==t)return!1;let n=e.length-1;for(let r=1;r=n||At.test(e[r])))return!1}return!0}function Mt(e){return jt(e)?e:`"${e.replaceAll(/["\\\p{Cc}]/gu,e=>e===`"`||e===`\\`?`\\${e}`:`\\${e.codePointAt(0).toString(16)} `)}"`}var Nt=class{#e=new Set;#t=null;constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){let t=this.#n();t.insertRule(e,t.cssRules.length)}#n(){if(this.#t)return this.#t;let e=this._document.defaultView?.CSSStyleSheet||globalThis.CSSStyleSheet;if(!this.styleElement&&e){let{adoptedStyleSheets:t}=this._document;if(t){let n=new e;return t.push(n),this.#t=n}}return this.styleElement||(this.styleElement=this._document.createElement(`style`),this._document.documentElement.getElementsByTagName(`head`)[0].append(this.styleElement)),this.#t=this.styleElement.sheet}clear(){for(let e of this.nativeFontFaces)this._document.fonts.delete(e);if(this.nativeFontFaces.clear(),this.#e.clear(),this.#t){let{adoptedStyleSheets:e}=this._document;e?.includes(this.#t)&&(this._document.adoptedStyleSheets=e.filter(e=>e!==this.#t)),this.#t=null}this.styleElement&&=(this.styleElement.remove(),null)}async loadSystemFont({systemFontInfo:e,disableFontFace:t,_inspectFont:n}){if(!(!e||this.#e.has(e.loadedName))){if(D(!t,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:t,src:r,style:i}=e,a=new FontFace(t,r,i);this.addNativeFontFace(a);try{await a.load(),this.#e.add(t),n?.(e)}catch{T(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}E(`Not implemented: loadSystemFont without the Font Loading API.`)}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){let t=e.createNativeFontFace();if(t){this.addNativeFontFace(t);try{await t.loaded}catch(n){throw T(`Failed to load font '${t.family}': '${n}'.`),e.disableFontFace=!0,n}}return}let t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(t=>{let n=this._queueLoadingCallback(t);this._prepareFontLoadEvent(e,n)})}}get isFontLoadingAPISupported(){let e=!!this._document?.fonts;return M(this,`isFontLoadingAPISupported`,e)}get isSyncFontLoadingSupported(){return M(this,`isSyncFontLoadingSupported`,t||F.platform.isFirefox)}_queueLoadingCallback(e){function t(){for(D(!r.done,`completeRequest() cannot be called twice.`),r.done=!0;n.length>0&&n[0].done;){let e=n.shift();setTimeout(e.callback,0)}}let{loadingRequests:n}=this,r={done:!1,complete:t,callback:e};return n.push(r),r}get _loadTestFont(){let e=atob(`T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==`);return M(this,`_loadTestFont`,e)}_prepareFontLoadEvent(e,t){function n(e,t){return e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3)&255}function r(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,e&255)}function i(e,t,n,r){let i=e.substring(0,t),a=e.substring(t+n);return i+r+a}let a,o,s=this._document.createElement(`canvas`);s.width=1,s.height=1;let c=s.getContext(`2d`),l=0;function u(e,t){if(++l>30){T(`Load test font never loaded.`),t();return}if(c.font=`30px `+e,c.fillText(`.`,0,20),c.getImageData(0,0,1,1).data[3]>0){t();return}setTimeout(u.bind(null,e,t))}let d=`lt${Date.now()}${this.loadTestFontId++}`,f=this._loadTestFont;f=i(f,976,d.length,d);let p=1482184792,m=n(f,16);for(a=0,o=d.length-3;a{g.remove(),t.complete()})}},Pt=class{compiledGlyphs=Object.create(null);#e;constructor(e,t=null,n,r){this.#e=e,this._inspectFont=t,n&&(this.charProcOperatorList=n),r&&Object.assign(this,r)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{let t={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(t.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(Mt(this.cssFontInfo.fontFamily),this.data,t)}return this._inspectFont?.(this),e}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let e=`url(data:${this.mimetype};base64,${this.data.toBase64()});`,t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let n=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(n+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:${Mt(this.cssFontInfo.fontFamily)};${n}src:${e}}`}return this._inspectFont?.(this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];let n=this.loadedName+`_path_`+t,r;try{r=e.get(n)}catch(e){T(`getPathGenerator - ignoring character: "${e}".`)}let i=Je(r?.path);return this.fontExtraProperties||e.delete(n),this.compiledGlyphs[t]=i}get black(){return this.#e.black}get bold(){return this.#e.bold}get disableFontFace(){return this.#e.disableFontFace}set disableFontFace(e){M(this,`disableFontFace`,!!e)}get fontExtraProperties(){return this.#e.fontExtraProperties}get isInvalidPDFjsFont(){return this.#e.isInvalidPDFjsFont}get isType3Font(){return this.#e.isType3Font}get italic(){return this.#e.italic}get missingFile(){return this.#e.missingFile}get remeasure(){return this.#e.remeasure}get vertical(){return this.#e.vertical}get ascent(){return this.#e.ascent}get defaultWidth(){return this.#e.defaultWidth}get descent(){return this.#e.descent}get bbox(){return this.#e.bbox}get fontMatrix(){return this.#e.fontMatrix}get fallbackName(){return this.#e.fallbackName}get loadedName(){return this.#e.loadedName}get mimetype(){return this.#e.mimetype}get name(){return this.#e.name}get data(){return this.#e.data}clearData(){this.#e.clearData()}get cssFontInfo(){return this.#e.cssFontInfo}get systemFontInfo(){return this.#e.systemFontInfo}get defaultVMetrics(){return this.#e.defaultVMetrics}},Ft=class{static strings=[`fontFamily`,`fontWeight`,`italicAngle`]},It=class{static strings=[`css`,`loadedName`,`baseFontName`,`src`]},K=class{static bools=[`black`,`bold`,`disableFontFace`,`fontExtraProperties`,`isInvalidPDFjsFont`,`isType3Font`,`italic`,`missingFile`,`remeasure`,`vertical`];static numbers=[`ascent`,`defaultWidth`,`descent`];static strings=[`fallbackName`,`loadedName`,`mimetype`,`name`];static OFFSET_NUMBERS=Math.ceil(this.bools.length*2/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+this.numbers.length*8;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6},Lt=class{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16},Rt=class{static get decoder(){return M(this,`decoder`,new TextDecoder)}static get encoder(){return M(this,`encoder`,new TextEncoder)}},zt=class{#e;#t;constructor(e){this.#e=e,this.#t=new DataView(e)}#n(e){D(e>n&3;return r===0?void 0:r===2}get black(){return this.#n(0)}get bold(){return this.#n(1)}get disableFontFace(){return this.#n(2)}get fontExtraProperties(){return this.#n(3)}get isInvalidPDFjsFont(){return this.#n(4)}get isType3Font(){return this.#n(5)}get italic(){return this.#n(6)}get missingFile(){return this.#n(7)}get remeasure(){return this.#n(8)}get vertical(){return this.#n(9)}#r(e){return D(e0){t=n.slice();for(let e=0,n=l.length;etypeof e==`object`&&Number.isInteger(e?.num)&&e.num>=0&&Number.isInteger(e?.gen)&&e.gen>=0,Jt=fe.bind(null,qt,e=>typeof e==`object`&&typeof e?.name==`string`),Yt=class{#e=new Map;#t=Promise.resolve();postMessage(e,t){let n={data:structuredClone(e,t?{transfer:t}:null)};this.#t.then(()=>{for(let[e]of this.#e)e.call(this,n)})}addEventListener(e,t,n=null){let r=null;if(n?.signal instanceof AbortSignal){let{signal:i}=n;if(i.aborted){T("LoopbackPort - cannot use an `aborted` signal.");return}let a=()=>this.removeEventListener(e,t);r=()=>i.removeEventListener(`abort`,a),i.addEventListener(`abort`,a)}this.#e.set(t,r)}removeEventListener(e,t){this.#e.get(t)?.(),this.#e.delete(t)}terminate(){for(let[,e]of this.#e)e?.();this.#e.clear()}},Xt={DATA:1,ERROR:2},q={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Zt(){}function J(e){if(e instanceof P||e instanceof ne||e instanceof ee||e instanceof re||e instanceof te)return e;switch(e instanceof Error||typeof e==`object`&&e||E(`wrapReason: Expected "reason" to be a (possibly cloned) Error.`),e.name){case`AbortException`:return new P(e.message);case`InvalidPDFException`:return new ne(e.message);case`PasswordException`:return new ee(e.message,e.code);case`ResponseException`:return new re(e.message,e.status,e.missing);case`UnknownErrorException`:return new te(e.message,e.details)}return new te(e.message,e.toString())}var Qt=class{#e=new AbortController;constructor(e,t,n){this.sourceName=e,this.targetName=t,this.comObj=n,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),n.addEventListener(`message`,this.#t.bind(this),{signal:this.#e.signal})}#t({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#r(e);return}if(e.callback){let t=e.callbackId,n=this.callbackCapabilities[t];if(!n)throw Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],e.callback===Xt.DATA)n.resolve(e.data);else if(e.callback===Xt.ERROR)n.reject(J(e.reason));else throw Error(`Unexpected callback case`);return}let t=this.actionHandler[e.action];if(!t)throw Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){let n=this.sourceName,r=e.sourceName,i=this.comObj;Promise.try(t,e.data).then(function(t){i.postMessage({sourceName:n,targetName:r,callback:Xt.DATA,callbackId:e.callbackId,data:t})},function(t){i.postMessage({sourceName:n,targetName:r,callback:Xt.ERROR,callbackId:e.callbackId,reason:J(t)})});return}if(e.streamId){this.#n(e);return}t(e.data)}on(e,t){let n=this.actionHandler;if(n[e])throw Error(`There is already an actionName called "${e}"`);n[e]=t}send(e,t,n){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},n)}sendWithPromise(e,t,n){let r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},n)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,n,r){let i=this.streamId++,a=this.sourceName,o=this.targetName,s=this.comObj;return new ReadableStream({start:n=>{let c=Promise.withResolvers();return this.streamControllers[i]={controller:n,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},s.postMessage({sourceName:a,targetName:o,action:e,streamId:i,data:t,desiredSize:n.desiredSize},r),c.promise},pull:e=>{let t=Promise.withResolvers();return this.streamControllers[i].pullCall=t,s.postMessage({sourceName:a,targetName:o,stream:q.PULL,streamId:i,desiredSize:e.desiredSize}),t.promise},cancel:e=>{D(e instanceof Error,`cancel must have a valid reason`);let t=Promise.withResolvers();return this.streamControllers[i].cancelCall=t,this.streamControllers[i].isClosed=!0,s.postMessage({sourceName:a,targetName:o,stream:q.CANCEL,streamId:i,reason:J(e)}),t.promise}},n)}#n(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this,o=this.actionHandler[e.action],s={enqueue(e,a=1,o){if(this.isCancelled)return;let s=this.desiredSize;this.desiredSize-=a,s>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),i.postMessage({sourceName:n,targetName:r,stream:q.ENQUEUE,streamId:t,chunk:e},o)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:q.CLOSE,streamId:t}),delete a.streamSinks[t])},error(e){D(e instanceof Error,`error must have a valid reason`),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:q.ERROR,streamId:t,reason:J(e)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};s.sinkCapability.resolve(),s.ready=s.sinkCapability.promise,this.streamSinks[t]=s,Promise.try(o,e.data,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.START_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.START_COMPLETE,streamId:t,reason:J(e)})})}#r(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this.streamControllers[t],o=this.streamSinks[t];switch(e.stream){case q.START_COMPLETE:e.success?a.startCall.resolve():a.startCall.reject(J(e.reason));break;case q.PULL_COMPLETE:e.success?a.pullCall.resolve():a.pullCall.reject(J(e.reason));break;case q.PULL:if(!o){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,success:!0});break}o.desiredSize<=0&&e.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=e.desiredSize,Promise.try(o.onPull||Zt).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,reason:J(e)})});break;case q.ENQUEUE:if(D(a,`enqueue should have stream controller`),a.isClosed)break;a.controller.enqueue(e.chunk);break;case q.CLOSE:if(D(a,`close should have stream controller`),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#i(a,t);break;case q.ERROR:D(a,`error should have stream controller`),a.controller.error(J(e.reason)),this.#i(a,t);break;case q.CANCEL_COMPLETE:e.success?a.cancelCall.resolve():a.cancelCall.reject(J(e.reason)),this.#i(a,t);break;case q.CANCEL:if(!o)break;let s=J(e.reason);Promise.try(o.onCancel||Zt,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.CANCEL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.CANCEL_COMPLETE,streamId:t,reason:J(e)})}),o.sinkCapability.reject(s),o.isCancelled=!0,delete this.streamSinks[t];break;default:throw Error(`Unexpected stream case`)}}async#i(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]),delete this.streamControllers[t]}destroy(){this.#e?.abort(),this.#e=null}},$t=class{#e=Object.freeze({cMapUrl:`CMap`,standardFontDataUrl:`font`,wasmUrl:`wasm`});constructor({cMapUrl:e=null,standardFontDataUrl:t=null,wasmUrl:n=null}){this.cMapUrl=e,this.standardFontDataUrl=t,this.wasmUrl=n}async fetch({kind:e,filename:t}){switch(e){case`cMapUrl`:case`standardFontDataUrl`:case`wasmUrl`:break;default:E(`Not implemented: ${e}`)}let n=this[e];if(!n)throw Error(`Ensure that the \`${e}\` API parameter is provided.`);let r=`${n}${t}`;return this._fetch(r,e).catch(t=>{throw Error(`Unable to load ${this.#e[e]} data at: ${r}`)})}async _fetch(e,t){E("Abstract method `_fetch` called.")}},en=class extends $t{async _fetch(e,t){let n=await Ce(e,t===`cMapUrl`&&!e.endsWith(`.bcmap`)?`text`:`bytes`);return n instanceof Uint8Array?n:oe(n)}},tn=class{#e=!1;constructor({enableHWA:e=!1}){this.#e=e}create(e,t){if(e<=0||t<=0)throw Error(`Invalid canvas size`);let n=this._createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`,{willReadFrequently:!this.#e})}}reset({canvas:e},t,n){if(!e)throw Error(`Canvas is not specified`);if(t<=0||n<=0)throw Error(`Invalid canvas size`);e.width=t,e.height=n}destroy(e){let{canvas:t}=e;if(!t)throw Error(`Canvas is not specified`);t.width=t.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){E("Abstract method `_createCanvas` called.")}},nn=class extends tn{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){let n=this._document.createElement(`canvas`);return n.width=e,n.height=t,n}},rn=class{addFilter(e){return`none`}addHCMFilter(e,t){return`none`}addAlphaFilter(e){return`none`}addLuminosityFilter(e){return`none`}addKnockoutFilter(e=0){return`none`}addHighlightHCMFilter(e,t,n,r,i){return`none`}addSelectionHCMFilter(e,t){return`none`}addSelectionFilter(){return`none`}createSelectionStyle(e=null){return null}destroy(e=!1){}},an=class extends rn{#e;#t;#n;#r;#i;#a;#o=0;constructor({docId:e,ownerDocument:t=globalThis.document}){super(),this.#r=e,this.#i=t}get#s(){return this.#t||=new Map}get#c(){return this.#a||=new Map}get#l(){if(!this.#n){let e=this.#i.createElement(`div`),{style:t}=e;t.colorScheme=`only light`,t.visibility=`hidden`,t.contain=`strict`,t.width=t.height=0,t.position=`absolute`,t.top=t.left=0,t.zIndex=-1;let n=this.#i.createElementNS(a,`svg`);n.setAttribute(`width`,0),n.setAttribute(`height`,0),this.#n=this.#i.createElementNS(a,`defs`),e.append(n),n.append(this.#n),this.#i.body.append(e)}return this.#n}#u(e){if(e.length===1){let t=e[0],n=Array(256);for(let e=0;e<256;e++)n[e]=t[e]/255;let r=n.join(`,`);return[r,r,r]}let[t,n,r]=e,i=Array(256),a=Array(256),o=Array(256);for(let e=0;e<256;e++)i[e]=t[e]/255,a[e]=n[e]/255,o[e]=r[e]/255;return[i.join(`,`),a.join(`,`),o.join(`,`)]}#d(e){if(this.#e===void 0){this.#e=``;let e=this.#i.URL;e!==this.#i.baseURI&&(Te(e)?T(`#createUrl: ignore "data:"-URL for performance reasons.`):this.#e=A(e,``))}return`url(${this.#e}#${e})`}addFilter(e){if(!e)return`none`;let t=this.#s.get(e);if(t)return t;let[n,r,i]=this.#u(e),a=e.length===1?n:`${n}${r}${i}`;if(t=this.#s.get(a),t)return this.#s.set(e,t),t;let o=`g_${this.#r}_transfer_map_${this.#o++}`,s=this.#d(o);this.#s.set(e,s),this.#s.set(a,s);let c=this.#m(o);return this.#g(n,r,i,c),s}addHCMFilter(e,t){let n=`${e}-${t}`,r=`base`,i=this.#c.get(r);if(i?.key===n||(i?(i.filter?.remove(),i.key=n,i.url=`none`,i.filter=null):(i={key:n,url:`none`,filter:null},this.#c.set(r,i)),!e||!t))return i.url;let a=this.#v(e);e=I.makeHexColor(...a);let o=this.#v(t);if(t=I.makeHexColor(...o),this.#b(),e===`#000000`&&t===`#ffffff`||e===t)return i.url;let s=Array.from({length:256},(e,t)=>Ue(t/255)).join(`,`),c=`g_${this.#r}_hcm_filter`,l=i.filter=this.#m(c);this.#g(s,s,s,l),this.#p(l);let u=(e,t)=>{let n=a[e]/255,r=o[e]/255,i=Array(t+1);for(let e=0;e<=t;e++)i[e]=n+e/t*(r-n);return i.join(`,`)};return this.#g(u(0,5),u(1,5),u(2,5),l),i.url=this.#d(c),i.url}addSelectionHCMFilter(e,t){return this.addHighlightHCMFilter(`selection`,e,t,`HighlightText`,`Highlight`)}addSelectionFilter(){return this.addHighlightHCMFilter(`selection_default`,`black`,`white`,`HighlightText`,`Highlight`)}createSelectionStyle(e=null){let t=e?this.addSelectionHCMFilter(e.foreground,e.background):this.addSelectionFilter();return t===`none`||!F.platform.isFirefox?null:{"backdrop-filter":t,"background-color":`transparent`}}addAlphaFilter(e){let t=this.#s.get(e);if(t)return t;let[n]=this.#u([e]),r=`alpha_${n}`;if(t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_alpha_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#_(n,o),a}addLuminosityFilter(e){let t=this.#s.get(e||`luminosity`);if(t)return t;let n,r;if(e?([n]=this.#u([e]),r=`luminosity_${n}`):r=`luminosity`,t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_luminosity_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#f(o),e&&this.#_(n,o),a}addKnockoutFilter(e=0){let t=e>0?Math.min(1/e,1e6):1e6,n=`knockout_${t}`,r=this.#s.get(n);if(r)return r;let i=`g_${this.#r}_knockout_filter_${this.#o++}`,o=this.#d(i);this.#s.set(n,o);let s=this.#m(i),c=this.#i.createElementNS(a,`feComponentTransfer`);s.append(c);let l=this.#i.createElementNS(a,`feFuncA`);return l.setAttribute(`type`,`linear`),l.setAttribute(`slope`,`${t}`),l.setAttribute(`intercept`,`0`),c.append(l),o}addHighlightHCMFilter(e,t,n,r,i){let a=`${t}-${n}-${r}-${i}`,o=this.#c.get(e);if(o?.key===a||(o?(o.filter?.remove(),o.key=a,o.url=`none`,o.filter=null):(o={key:a,url:`none`,filter:null},this.#c.set(e,o)),!t||!n))return o.url;let[s,c]=[t,n].map(this.#v.bind(this)),l=Math.round(.2126*s[0]+.7152*s[1]+.0722*s[2]),u=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),[d,f]=[r,i].map(this.#x.bind(this));u{let r=Array(256),i=(u-l)/n,a=e/255,o=(t-e)/(255*n),s=0;for(let e=0;e<=n;e++){let t=Math.round(l+e*i),n=a+e*o;for(let e=s;e<=t;e++)r[e]=n;s=t+1}for(let e=s;e<256;e++)r[e]=r[s-1];return r.join(`,`)},m=`g_${this.#r}_hcm_${e}_filter`,h=o.filter=this.#m(m);return this.#p(h),this.#g(p(d[0],f[0],5),p(d[1],f[1],5),p(d[2],f[2],5),h),o.url=this.#d(m),o.url}destroy(e=!1){e&&this.#a?.size||(this.#n?.parentNode.parentNode.remove(),this.#n=null,this.#t?.clear(),this.#t=null,this.#a?.clear(),this.#a=null,this.#o=0)}#f(e){let t=this.#i.createElementNS(a,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.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`),e.append(t)}#p(e){let t=this.#i.createElementNS(a,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.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`),e.append(t)}#m(e){let t=this.#i.createElementNS(a,`filter`);return t.setAttribute(`color-interpolation-filters`,`sRGB`),t.setAttribute(`id`,e),this.#l.append(t),t}#h(e,t,n){let r=this.#i.createElementNS(a,t);r.setAttribute(`type`,`discrete`),r.setAttribute(`tableValues`,n),e.append(r)}#g(e,t,n,r){let i=this.#i.createElementNS(a,`feComponentTransfer`);r.append(i),this.#h(i,`feFuncR`,e),this.#h(i,`feFuncG`,t),this.#h(i,`feFuncB`,n)}#_(e,t){let n=this.#i.createElementNS(a,`feComponentTransfer`);t.append(n),this.#h(n,`feFuncA`,e)}#v(e){return this.#l.style.color=`CanvasText`,this.#l.style.backgroundColor=e,Ne(getComputedStyle(this.#l).getPropertyValue(`background-color`))}#y(e){return this.#l.style.color=`CanvasText`,this.#l.style.backgroundColor=e,Me(getComputedStyle(this.#l).getPropertyValue(`background-color`))}#b(){this.#l.style.color=``,this.#l.style.backgroundColor=``}#x(e){let[t,n,r,i]=this.#y(e);if(i===1)return[t,n,r];let[a,o,s]=this.#v(`Canvas`);return[on(t,a,i),on(n,o,i),on(r,s,i)]}};function on(e,t,n){return Math.round(n*e+(1-n)*t)}t&&T("Please use the `legacy` build in Node.js environments.");async function sn(e){let t=await process.getBuiltinModule(`fs/promises`).readFile(e);return new Uint8Array(t)}var cn=class extends rn{},ln=class extends tn{_createCanvas(e,t){return process.getBuiltinModule(`module`).createRequire(import.meta.url)(`@napi-rs/canvas`).createCanvas(e,t)}},un=class extends $t{async _fetch(e,t){return sn(e)}};function dn({src:e,srcPos:t=0,dest:n,width:r,height:i,nonBlackColor:a=4294967295,inverseDecode:o=!1}){let s=F.isLittleEndian?4278190080:255,[c,l]=o?[a,s]:[s,a],u=r>>3,d=r&7,f=c^l,p=e.length;n=new Uint32Array(n.buffer);let m=0;for(let r=0;r>7&1)&f,n[m+1]=c^-(r>>6&1)&f,n[m+2]=c^-(r>>5&1)&f,n[m+3]=c^-(r>>4&1)&f,n[m+4]=c^-(r>>3&1)&f,n[m+5]=c^-(r>>2&1)&f,n[m+6]=c^-(r>>1&1)&f,n[m+7]=c^-(r&1)&f}if(d===0)continue;let r=t>7-e&1)&f}return{srcPos:t,destPos:m}}function fn({src:e,srcPos:t=0,dest:n,destPos:r=0,width:i,height:a}){let o=0,s=i*a*3,c=s>>2,l=new Uint32Array(e.buffer,t,c),u=F.isLittleEndian?4278190080:255;if(F.isLittleEndian){for(;o>>24|t<<8|u,n[r+2]=t>>>16|i<<16|u,n[r+3]=i>>>8|u}for(let i=o*4,a=t+s;i>>8|u,n[r+2]=t<<16|i>>>16|u,n[r+3]=i<<8|u}for(let i=o*4,a=t+s;i u : Uniforms; + +struct VertexInput { + @location(0) position : vec2, + @location(1) color : vec4, +}; + +struct VertexOutput { + @builtin(position) position : vec4, + @location(0) color : vec3, +}; + +@vertex +fn vs_main(in : VertexInput) -> VertexOutput { + var out : VertexOutput; + let cx = (in.position.x + u.offsetX) * u.scaleX; + let cy = (in.position.y + u.offsetY) * u.scaleY; + out.position = vec4( + ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0, + 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0, + 0.0, + 1.0 + ); + out.color = in.color.rgb; + return out; +} + +@fragment +fn fs_main(in : VertexOutput) -> @location(0) vec4 { + return vec4(in.color, 1.0); +} +`,mn=new class{#e=null;#t=null;#n=null;#r=null;async#i(){if(!globalThis.navigator?.gpu)return!1;try{let e=await navigator.gpu.requestAdapter();return e?(this.#r=navigator.gpu.getPreferredCanvasFormat(),this.#t=await e.requestDevice(),!0):!1}catch{return!1}}init(){return this.#e||=this.#i()}get isReady(){return this.#t!==null}loadMeshShader(){if(!this.#t||this.#n)return;let e=this.#t.createShaderModule({code:pn});this.#n=this.#t.createRenderPipeline({layout:`auto`,vertex:{module:e,entryPoint:`vs_main`,buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:`float32x2`}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:`unorm8x4`}]}]},fragment:{module:e,entryPoint:`fs_main`,targets:[{format:this.#r}]},primitive:{topology:`triangle-list`}})}draw(e,t,n,r,i,a,o,s){this.loadMeshShader();let c=this.#t,{offsetX:l,offsetY:u,scaleX:d,scaleY:f}=r,p=c.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&c.queue.writeBuffer(p,0,e);let m=c.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&c.queue.writeBuffer(m,0,t);let h=c.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});c.queue.writeBuffer(h,0,new Float32Array([l,u,d,f,a,o,s,0]));let g=c.createBindGroup({layout:this.#n.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:h}}]}),_=new OffscreenCanvas(a,o),v=_.getContext(`webgpu`);v.configure({device:c,format:this.#r,alphaMode:i?`opaque`:`premultiplied`});let y=i?{r:i[0]/255,g:i[1]/255,b:i[2]/255,a:1}:{r:0,g:0,b:0,a:0},b=c.createCommandEncoder(),x=b.beginRenderPass({colorAttachments:[{view:v.getCurrentTexture().createView(),clearValue:y,loadOp:`clear`,storeOp:`store`}]});return n>0&&(x.setPipeline(this.#n),x.setBindGroup(0,g),x.setVertexBuffer(0,p),x.setVertexBuffer(1,m),x.draw(n)),x.end(),c.queue.submit([b.finish()]),p.destroy(),m.destroy(),h.destroy(),_.transferToImageBitmap()}};function hn(){return mn.init()}function gn(){return mn.isReady}function _n(){mn.loadMeshShader()}function vn(e,t,n,r,i,a,o,s){return mn.draw(e,t,n,r,i,a,o,s)}var Y={FILL:`Fill`,STROKE:`Stroke`,SHADING:`Shading`};function yn(e,t){if(!t)return;let n=t[2]-t[0],r=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],n,r),e.clip(i)}var bn=class{matrix=null;isModifyingCurrentTransform(){return!1}getPattern(){E("Abstract method `getPattern` called.")}},xn=class extends bn{constructor(e){super(),this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7]}isOriginBased(){return this._p0[0]===0&&this._p0[1]===0&&(!this.isRadial()||this._p1[0]===0&&this._p1[1]===0)}isRadial(){return this._type===`radial`}areConic(){if(!this.isRadial())return!1;let e=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return e+this._r1>this._r0&&e+this._r0>this._r1}_createGradient(e,t=null){let n,r=this._p0,i=this._p1;if(t&&(r=r.slice(),i=i.slice(),I.applyTransform(r,t),I.applyTransform(i,t)),this._type===`axial`)n=e.createLinearGradient(r[0],r[1],i[0],i[1]);else if(this._type===`radial`){let a=this._r0,o=this._r1;if(t){let e=new Float32Array(2);I.singularValueDecompose2dScale(t,e),a*=e[0],o*=e[0]}n=e.createRadialGradient(r[0],r[1],a,i[0],i[1],o)}for(let e of this._colorStops)n.addColorStop(e[0],e[1]);return n}_createReversedGradient(e,t=null){let n=this._p1,r=this._p0;t&&(n=n.slice(),r=r.slice(),I.applyTransform(n,t),I.applyTransform(r,t));let i=this._r1,a=this._r0;if(t){let e=new Float32Array(2);I.singularValueDecompose2dScale(t,e),i*=e[0],a*=e[0]}let o=e.createRadialGradient(n[0],n[1],i,r[0],r[1],a),s=this._colorStops.map(([e,t])=>[1-e,t]).reverse();for(let[e,t]of s)o.addColorStop(e,t);return o}getPattern(e,t,n,r){let i;if(r===Y.STROKE||r===Y.FILL){if(this.isOriginBased()){let r=I.transform(n,t.baseTransform);this.matrix&&(r=I.transform(r,this.matrix));let i=.001,a=Math.hypot(r[0],r[1]),o=Math.hypot(r[2],r[3]),s=(r[0]*r[2]+r[1]*r[3])/(a*o);if(Math.abs(s)c[r*2+1]&&(f=n,n=r,r=f,f=a,a=o,o=f),c[r*2+1]>c[i*2+1]&&(f=r,r=i,i=f,f=o,o=s,s=f),c[n*2+1]>c[r*2+1]&&(f=n,n=r,r=f,f=a,a=o,o=f);let p=(c[n*2]+t.offsetX)*t.scaleX,m=(c[n*2+1]+t.offsetY)*t.scaleY,h=(c[r*2]+t.offsetX)*t.scaleX,g=(c[r*2+1]+t.offsetY)*t.scaleY,_=(c[i*2]+t.offsetX)*t.scaleX,v=(c[i*2+1]+t.offsetY)*t.scaleY;if(m>=v)return;let y=l[a*4],b=l[a*4+1],x=l[a*4+2],S=l[o*4],C=l[o*4+1],w=l[o*4+2],T=l[s*4],E=l[s*4+1],D=l[s*4+2],O=Math.round(m),k=Math.round(v),A,j,M,N,ee,te,ne,re;for(let e=O;e<=k;e++){if(ev?1:g===v?0:(g-e)/(g-v),A=h-(h-_)*t,j=S-(S-T)*t,M=C-(C-E)*t,N=w-(w-D)*t}let t;t=ev?1:(m-e)/(m-v),ee=p-(p-_)*t,te=y-(y-T)*t,ne=b-(b-E)*t,re=x-(x-D)*t;let n=Math.round(Math.min(A,ee)),r=Math.round(Math.max(A,ee)),i=d*e+n*4;for(let e=n;e<=r;e++)t=(A-e)/(A-ee),t<0?t=0:t>1&&(t=1),u[i++]=j-(j-te)*t|0,u[i++]=M-(M-ne)*t|0,u[i++]=N-(N-re)*t|0,u[i++]=255}}var Cn=class extends bn{constructor(e){super(),this._posData=e[2],this._colData=e[3],this._vertexCount=e[4],this._bounds=e[5],this._bbox=e[6],this._background=e[7],_n()}_createMeshCanvas(e,t,n){let r=1.1,i=3e3,a=Math.floor(this._bounds[0]),o=Math.floor(this._bounds[1]),s=Math.ceil(this._bounds[2])-a,c=Math.ceil(this._bounds[3])-o,l=Math.min(Math.ceil(Math.abs(s*e[0]*r)),i)||1,u=Math.min(Math.ceil(Math.abs(c*e[1]*r)),i)||1,d=s?s/l:1,f=c?c/u:1,p={coords:this._posData,colors:this._colData,offsetX:-a,offsetY:-o,scaleX:1/d,scaleY:1/f},m=l+4,h=u+4,g=n.create(m,h);if(gn()&&this._vertexCount>48)g.context.drawImage(vn(this._posData,this._colData,this._vertexCount,p,t,m,h,2),0,0);else{let e=g.context.createImageData(l,u);if(t){let n=e.data;for(let e=0,r=n.length;ec+1e-6||t>l+1e-6)return null;let u=Math.floor((n-o)/c)+1,d=Math.ceil((n+e-i)/c)-1,f=Math.floor((r-s)/l)+1,p=Math.ceil((r+t-a)/l)-1;return d<=u&&p<=f?[u,f]:null}updatePatternDims(e,t){let n=I.inverseTransform(this.patternBaseMatrix),r=[e[0],e[1]],i=[e[2],e[3]];I.applyTransform(r,n),I.applyTransform(i,n),t[0]=Math.abs(i[0]-r[0]),t[1]=Math.abs(i[1]-r[1]),t[2]=Math.min(r[0],i[0]),t[3]=Math.min(r[1],i[1])}_renderTileCanvas(e,t,n,r){let[i,a,o,s]=this.bbox,c=e.canvasFactory.create(n.size,r.size),l=c.context,u=this.canvasGraphicsFactory.createCanvasGraphics(l,t);return u.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(u,this.paintType,this.color),l.translate(-n.scale*i,-r.scale*a),u.transform(0,n.scale,0,0,r.scale,0,0),l.save(),u.dependencyTracker?.save(),this.clipBbox(u,i,a,o,s),u.baseTransform=B(u.ctx),u.executeOperatorList(this.operatorList),u.endDrawing(),u.dependencyTracker?.restore(),l.restore(),c}_getCombinedScales(){let e=new Float32Array(2);I.singularValueDecompose2dScale(this.matrix,e);let[t,n]=e;return I.singularValueDecompose2dScale(this.baseTransform,e),[t*e[0],n*e[1]]}drawPattern(e,t,n=!1,[r,i],a){let[o,s,c,l]=this.bbox,u=e.dependencyTracker;if(u&&(e.dependencyTracker=new Ot(u,a)),e.save(),n?e.ctx.clip(t,`evenodd`):e.ctx.clip(t),e.ctx.setTransform(...this.patternBaseMatrix),e.ctx.translate(r*this.xstep,i*this.ystep),this.needsIsolation||e.ctx.globalAlpha!==1||e.ctx.globalCompositeOperation!==`source-over`||e.inSMaskMode){let t=c-o,n=l-s,[r,i]=this._getCombinedScales(),u=this.getSizeAndScale(t,this.ctx.canvas.width,r),d=this.getSizeAndScale(n,this.ctx.canvas.height,i),f=this._renderTileCanvas(e,a,u,d);e.ctx.drawImage(f.canvas,o,s,t,n),e.canvasFactory.destroy(f)}else this.setFillAndStrokeStyleToContext(e,this.paintType,this.color),this.clipBbox(e,o,s,c,l),e.baseTransformStack.push(e.baseTransform),e.baseTransform=B(e.ctx),e.executeOperatorList(this.operatorList),e.baseTransform=e.baseTransformStack.pop();e.restore(),u&&(e.dependencyTracker=u)}createPatternCanvas(e,t){let[n,r,i,a]=this.bbox,o=i-n,s=a-r,{xstep:c,ystep:l}=this;c=Math.abs(c),l=Math.abs(l),w(`TilingType: `+this.tilingType);let[u,d]=this._getCombinedScales(),f=o,p=s,m=!1,h=!1;Math.ceil(c*u)>=Math.ceil(o*u)?f=c:m=!0,Math.ceil(l*d)>=Math.ceil(s*d)?p=l:h=!0;let g=this.getSizeAndScale(f,this.ctx.canvas.width,u),_=this.getSizeAndScale(p,this.ctx.canvas.height,d),v=this._renderTileCanvas(e,t,g,_);if(m||h){let t=v.canvas;m&&(f=c),h&&(p=l);let i=this.getSizeAndScale(f,this.ctx.canvas.width,u),a=this.getSizeAndScale(p,this.ctx.canvas.height,d),g=i.size,_=a.size,y=e.canvasFactory.create(g,_),b=y.context,x=m?Math.floor(o/c):0,S=h?Math.floor(s/l):0;for(let e=0;e<=x;e++)for(let n=0;n<=S;n++)b.drawImage(t,g*e,_*n,g,_,0,0,g,_);return e.canvasFactory.destroy(v),{canvas:y.canvas,canvasEntry:y,scaleX:i.scale,scaleY:a.scale,offsetX:n,offsetY:r}}return{canvas:v.canvas,canvasEntry:v,scaleX:g.scale,scaleY:_.scale,offsetX:n,offsetY:r}}getSizeAndScale(t,n,r){let i=Math.max(e.MAX_PATTERN_SIZE,n),a=Math.ceil(t*r);return a>=i?a=i:r=a/t,{scale:r,size:a}}clipBbox(e,t,n,r,i){let a=r-t,o=i-n,s=new Path2D;s.rect(t,n,a,o),I.axialAlignedBoundingBox([t,n,r,i],B(e.ctx),e.current.minMax),e.ctx.clip(s),e.current.updateClipFromPath()}setFillAndStrokeStyleToContext(e,t,n){let r=e.ctx,i=e.current;switch(i.patternFill=i.patternStroke=!1,t){case En.COLORED:let{fillStyle:e,strokeStyle:a}=this.ctx;r.fillStyle=i.fillColor=e,r.strokeStyle=i.strokeColor=a;break;case En.UNCOLORED:r.fillStyle=r.strokeStyle=n,i.fillColor=i.strokeColor=n;break;default:throw new ie(`Unsupported paint type: ${t}`)}}isModifyingCurrentTransform(){return!1}getPattern(e,t,n,r,i){let a=r===Y.SHADING?n:I.transform(n,this.patternBaseMatrix),o=this.createPatternCanvas(t,i),s=new DOMMatrix(a);s=s.translate(o.offsetX,o.offsetY),s=s.scale(1/o.scaleX,1/o.scaleY);let c=e.createPattern(o.canvas,`repeat`);return t.canvasFactory.destroy(o.canvasEntry),c.setTransform(s),c}},On=16,kn=100,An=15,jn=10,X=16,Z=new Float32Array(2);function Mn(e,t){if(e._removeMirroring)throw Error(`Context is already forwarding operations.`);let n=new Map;for(let r of[`save`,`restore`,`rotate`,`scale`,`translate`,`transform`,`setTransform`,`resetTransform`,`clip`,`moveTo`,`lineTo`,`bezierCurveTo`,`quadraticCurveTo`,`arc`,`arcTo`,`ellipse`,`rect`,`roundRect`,`closePath`,`beginPath`]){let i=e[r];typeof i==`function`&&typeof t[r]==`function`&&(n.set(r,i),e[r]=function(...e){return t[r](...e),i.apply(this,e)})}e._removeMirroring=()=>{for(let[t,r]of n)e[t]=r;delete e._removeMirroring}}function Nn(e,t,n,r,i,a,o,s,c,l){let[u,d,f,p,m,h]=B(e);if(d===0&&f===0){let g=o*u+m,_=Math.round(g),v=s*p+h,y=Math.round(v),b=(o+c)*u+m,x=Math.abs(Math.round(b)-_)||1,S=(s+l)*p+h,C=Math.abs(Math.round(S)-y)||1;return e.setTransform(Math.sign(u),0,0,Math.sign(p),_,y),e.drawImage(t,n,r,i,a,0,0,x,C),e.setTransform(u,d,f,p,m,h),[x,C]}if(u===0&&p===0){let g=s*f+m,_=Math.round(g),v=o*d+h,y=Math.round(v),b=(s+l)*f+m,x=Math.abs(Math.round(b)-_)||1,S=(o+c)*d+h,C=Math.abs(Math.round(S)-y)||1;return e.setTransform(0,Math.sign(d),Math.sign(f),0,_,y),e.drawImage(t,n,r,i,a,0,0,C,x),e.setTransform(u,d,f,p,m,h),[C,x]}e.drawImage(t,n,r,i,a,o,s,c,l);let g=Math.hypot(u,d),_=Math.hypot(f,p);return[g*c,_*l]}var Pn=class{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=i;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=p.FILL;textRise=0;fillColor=`#000000`;strokeColor=`#000000`;tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps=`none`;minMax=r.slice();constructor(e,t){this.clipBox=new Float32Array([0,0,e,t])}clone(){let e=Object.create(this);return e.clipBox=this.clipBox.slice(),e.minMax=this.minMax.slice(),e.tilingPatternDims=this.tilingPatternDims?.slice(),e}getPathBoundingBox(e=Y.FILL,t=null){let n=this.minMax.slice();if(e===Y.STROKE){t||E(`Stroke bounding box must include transform.`),I.singularValueDecompose2dScale(t,Z);let e=Z[0]*this.lineWidth/2,r=Z[1]*this.lineWidth/2;n[0]-=e,n[1]-=r,n[2]+=e,n[3]+=r}return n}updateClipFromPath(){let e=I.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(e){this.clipBox.set(e,0),this.minMax.set(r,0)}getClippedPathBoundingBox(e=Y.FILL,t=null){return I.intersect(this.clipBox,this.getPathBoundingBox(e,t))}};function Fn(e,t){let{width:n,height:r,kind:i}=t,a=r%X,o=(r-a)/X,s=a===0?o:o+1,c=e.createImageData(n,X),l=0,u=t.data,d=c.data,f;if(i===m.GRAYSCALE_1BPP)for(f=0;fjn&&typeof n==`function`,u=l?Date.now()+An:0,d=0,f=this.commonObjs,p=this.objs,m,h;for(;;){if(r!==void 0){if(s===r.nextBreakPoint)return r.breakIt(s,n),s;if(r.shouldSkip(s)){if(++s===c)return s;continue}}if(!i||i(s)){if(m=o[s],h=a[s]??null,m!==v.dependency)h===null?this[m](s):this[m](s,...h);else for(let e of h){this.dependencyTracker?.recordNamedData(e,s);let t=e.startsWith(`g_`)?f:p;if(!t.has(e))return t.get(e,n),s}}if(s++,s===c)return s;if(l&&++d>jn){if(Date.now()>u)return n(),s;d=0}}}#d(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)}endDrawing(){this.#d();for(let e of this.smaskGroupCanvases)this.canvasFactory.destroy(e);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0;for(let e of this.#u)this.#b(e);this.#u.length=0,this.#r=null,this.#i=null,this.#a=null,this.#o=null,this.#s=1,this.#l=null,this.#n=0,this.#t=0,this.cachedPatterns.clear();for(let e of this._cachedBitmapsMap.values()){for(let t of e.values())typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement&&(t.width=t.height=0);e.clear()}this._cachedBitmapsMap.clear(),this.#f()}#f(){if(this.pageColors){let e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!==`none`){let t=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=t}}}_scaleImage(e,t){let n=e.width??e.displayWidth,r=e.height??e.displayHeight,i=Math.max(Math.hypot(t[0],t[1]),1),a=Math.max(Math.hypot(t[2],t[3]),1),o=[],s=i,c=a,l=n,u=r;for(;s>2&&l>1||c>2&&u>1;){let e=l,t=u;s>2&&l>1&&(e=Math.ceil(l/2),s/=l/e),c>2&&u>1&&(t=Math.ceil(u/2),c/=u/t),o.push({newWidth:e,newHeight:t}),l=e,u=t}if(o.length===0)return{img:e,paintWidth:n,paintHeight:r,tmpCanvas:null};if(o.length===1){let{newWidth:t,newHeight:i}=o[0],a=this.canvasFactory.create(t,i);return a.context.drawImage(e,0,0,n,r,0,0,t,i),{img:a.canvas,paintWidth:t,paintHeight:i,tmpCanvas:a}}let d=this.canvasFactory.create(1,1),f=this.canvasFactory.create(1,1),p=n,m=r,h=e;for(let{newWidth:e,newHeight:t}of o)this.canvasFactory.reset(f,e,t),f.context.drawImage(h,0,0,p,m,0,0,e,t),[d,f]=[f,d],h=d.canvas,p=e,m=t;return this.canvasFactory.destroy(f),{img:d.canvas,paintWidth:p,paintHeight:m,tmpCanvas:d}}_createMaskCanvas(e,t){let n=this.ctx,{width:i,height:a}=t,o=this.current.fillColor,s=this.current.patternFill,c=B(n),l,u,d,f;if((t.bitmap||t.data)&&t.count>1){let n=t.bitmap||t.data.buffer;u=JSON.stringify(s?c:[c.slice(0,4),o]),l=this._cachedBitmapsMap.getOrInsertComputed(n,me);let r=l.get(u);if(r&&!s){let t=Math.round(Math.min(c[0],c[2])+c[4]),n=Math.round(Math.min(c[1],c[3])+c[5]);return this.dependencyTracker?.recordDependencies(e,G.transformAndFill),{canvas:r,offsetX:t,offsetY:n}}d=r}d||(f=this.canvasFactory.create(i,a),In(f.context,t));let p=I.transform(c,[1/i,0,0,-1/a,0,0]);p=I.transform(p,[1,0,0,1,0,-a]);let m=r.slice();I.axialAlignedBoundingBox([0,0,i,a],p,m);let[h,g,_,v]=m,y=Math.round(_-h)||1,b=Math.round(v-g)||1,x=this.canvasFactory.create(y,b),S=x.context,C=h,w=g;S.translate(-C,-w),S.transform(...p);let T=null;if(!d){let e=this._scaleImage(f.canvas,V(S));d=e.img,T=e.tmpCanvas,d!==f.canvas&&(this.canvasFactory.destroy(f),f=null),l&&s&&(l.set(u,d),T=null,f=null)}S.imageSmoothingEnabled=zn(B(S),t.interpolate),Nn(S,d,0,0,d.width,d.height,0,0,i,a),T&&this.canvasFactory.destroy(T),f&&this.canvasFactory.destroy(f),S.globalCompositeOperation=`source-in`;let E=I.transform(V(S),[1,0,0,1,-C,-w]);return S.fillStyle=s?o.getPattern(n,this,E,Y.FILL,e):o,S.fillRect(0,0,i,a),l&&!s&&l.set(u,x.canvas),this.dependencyTracker?.recordDependencies(e,G.transformAndFill),{canvas:x.canvas,canvasEntry:l&&!s?null:x,offsetX:Math.round(C),offsetY:Math.round(w)}}setLineWidth(e,t){this.dependencyTracker?.recordSimpleData(`lineWidth`,e),t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(e,t){this.dependencyTracker?.recordSimpleData(`lineCap`,e),this.ctx.lineCap=Bn[t]}setLineJoin(e,t){this.dependencyTracker?.recordSimpleData(`lineJoin`,e),this.ctx.lineJoin=Vn[t]}setMiterLimit(e,t){this.dependencyTracker?.recordSimpleData(`miterLimit`,e),this.ctx.miterLimit=t}setDash(e,t,n){this.dependencyTracker?.recordSimpleData(`dash`,e);let r=this.ctx;r.setLineDash!==void 0&&(r.setLineDash(t),r.lineDashOffset=n)}setRenderingIntent(e,t){}setFlatness(e,t){}setGState(e,t){for(let[n,r]of t)switch(n){case`LW`:this.setLineWidth(e,r);break;case`LC`:this.setLineCap(e,r);break;case`LJ`:this.setLineJoin(e,r);break;case`ML`:this.setMiterLimit(e,r);break;case`D`:this.setDash(e,r[0],r[1]);break;case`RI`:this.setRenderingIntent(e,r);break;case`FL`:this.setFlatness(e,r);break;case`Font`:this.setFont(e,r[0],r[1]);break;case`CA`:this.dependencyTracker?.recordSimpleData(`strokeAlpha`,e),this.current.strokeAlpha=r;break;case`ca`:this.dependencyTracker?.recordSimpleData(`fillAlpha`,e),this.ctx.globalAlpha=this.current.fillAlpha=r;break;case`BM`:this.dependencyTracker?.recordSimpleData(`globalCompositeOperation`,e),this.ctx.globalCompositeOperation=r;break;case`SMask`:this.dependencyTracker?.recordSimpleData(`SMask`,e),this.current.activeSMask=r?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(e);break;case`TR`:this.dependencyTracker?.recordSimpleData(`filter`,e),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(r)}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&=(this.canvasFactory.destroy(this.smaskPreparedEntry),null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(e){e!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(e))}checkSMaskState(e){let t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode(e):!this.current.activeSMask&&t?this.endSMaskMode():this.current.activeSMask&&t&&this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(e){let{canvas:t,subtype:n,backdrop:r,transferMap:i}=e,a=n===`Luminosity`||n===`Alpha`&&i;if(!a&&!(n===`Luminosity`&&r)){this.smaskPreparedFor=e;return}let o;if(n===`Luminosity`&&r){let[e,t,n]=Me(r),a=Math.round(.3*e+.59*t+.11*n);o=i?.[a]??a}else o=i?.[0]??0;let{width:s,height:c}=this.ctx.canvas,l=t.width*t.height,u=s*c<4*l,d=a?{url:n===`Alpha`?this.filterFactory.addAlphaFilter(i):this.filterFactory.addLuminosityFilter(i),subtype:n,transferMap:i}:null,f=n===`Luminosity`?r:null,p,m,h;u?(p=this._bakeSMaskCanvas(t,e.offsetX,e.offsetY,s,c,f,d),m=0,h=0):(p=this._bakeSMaskCanvas(t,0,0,t.width,t.height,f,d),m=e.offsetX,h=e.offsetY),this.smaskPreparedEntry=p,this.smaskPreparedFor=e,this.smaskPreparedOffsetX=m,this.smaskPreparedOffsetY=h,this.smaskPreparedOOBAlpha=!u&&o!==0?o:null}_bakeSMaskCanvas(e,t,n,r,i,a,o){!a&&!o&&E(`_bakeSMaskCanvas with neither backdrop nor filter`);let s=this.canvasFactory.create(r,i),c=s.context;if(c.drawImage(e,t,n),a&&(c.globalCompositeOperation=`destination-atop`,c.fillStyle=a,c.fillRect(0,0,r,i)),!o)return s;let l=this.canvasFactory.create(r,i),u=l.context;u.filter=o.url;let d=F.isCanvasFilterSupported&&u.filter!==`none`&&u.filter!==``;if(u.drawImage(s.canvas,0,0),F.isCanvasFilterSupported&&(u.filter=`none`),!d){let e=u.getImageData(0,0,r,i),{data:t}=e,{transferMap:n}=o;if(o.subtype===`Luminosity`)for(let e=0,r=t.length;ethis.filterFactory.addKnockoutFilter(n))),!s||c!==`none`)return t&&(o.save(),o.setTransform(1,0,0,1,0,0),o.clearRect(0,0,r,i),o.restore()),o.filter=c,o.drawImage(e,0,0),o.filter=`none`,a;let l=e.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,r,i),u=o.createImageData(r,i),d=l.data,f=u.data,p=n>0?1/n:1e6;for(let e=3,t=d.length;e0||!this.contentVisible)return!1;this.#n++,this.#s=e;let t=this.#u.at(-1),{canvas:n}=this.ctx,r=this.#m(t,`knockoutTempEntry`,n.width,n.height);this.#r=r;let i=r.context;return i.save(),i.setTransform(this.ctx.getTransform()),Ln(this.ctx,i),this.#o=i.globalCompositeOperation,i.globalCompositeOperation=`source-over`,Mn(i,this.ctx),this.#l=t,this.#i=this.ctx,this.#a=this.suspendedCtx,this.ctx=i,this.inSMaskMode&&(this.suspendedCtx=i),!0}#_(e){if(!e)return;let t=this.#r,n=this.#i,r=this.#a,i=t.context;this.#r=null,this.#i=null,this.#a=null,this.inSMaskMode&&this.suspendedCtx===i&&this.ctx!==i&&this.endSMaskMode(),this.inSMaskMode&&(this.suspendedCtx=r),this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=this.#o,this.#o=null,Ln(this.ctx,n),this.ctx=n;let a=this.#l;this.#l=null;let o=this.#s;this.#s=1;try{this.#h(r??n,t.canvas,{backdropCanvas:a?.backdropCtx?.canvas??null,backdropOffset:a?.backdropCtx?[a.offsetX,a.offsetY]:[0,0],reuseMaskEntry:a?.knockoutMaskEntry??null,poolMeta:a,knockoutAlpha:o})}finally{i.restore(),this.#n--,a||this.canvasFactory.destroy(t)}}compose(e){if(!this.current.activeSMask)return;e=e?[Math.floor(e[0]),Math.floor(e[1]),Math.ceil(e[2]),Math.ceil(e[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let t=this.current.activeSMask,n=this.suspendedCtx,r=this.#n>0&&n===this.ctx;this.composeSMask(r?null:n,t,this.ctx,e),!r&&(this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore())}composeSMask(e,t,n,r){let i=r[0],a=r[1],o=r[2]-i,s=r[3]-a;if(o===0||s===0)return;let c=this.smaskPreparedEntry;if(c){let e=i,r=a,l=o,u=s,d=this.smaskPreparedOOBAlpha,f=d!==null;if(f){e=Math.max(i,t.offsetX),r=Math.max(a,t.offsetY);let n=Math.min(i+o,t.offsetX+t.canvas.width),c=Math.min(a+s,t.offsetY+t.canvas.height);l=n-e,u=c-r}if(l>0&&u>0){let t=e-this.smaskPreparedOffsetX,i=r-this.smaskPreparedOffsetY;n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0);let a=new Path2D;a.rect(e,r,l,u),n.clip(a),n.globalCompositeOperation=`destination-in`,n.drawImage(c.canvas,t,i,l,u,e,r,l,u),n.restore()}f&&d<255&&this._applySMaskOOBAlpha(n,i,a,o,s,e,r,e+l,r+u,d)}else this.genericComposeSMask(t,n,o,s,i,a);e&&(e.save(),e.globalAlpha=1,e.globalCompositeOperation=t.blendMode||`source-over`,e.setTransform(1,0,0,1,0,0),e.drawImage(n.canvas,i,a,o,s,i,a,o,s),e.restore())}_applySMaskOOBAlpha(e,t,n,r,i,a,o,s,c,l){let u=ao.measureText(t))),(d===p.STROKE||d===p.FILL_STROKE)&&(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(e,o,c,u,n,r,()=>o.measureText(t)).recordDependencies(e,G.stroke),o.strokeText(t,n,r));f&&((this.pendingTextPaths||=[]).push({transform:B(o),x:n,y:r,fontSize:u,path:g}),this.dependencyTracker?.recordCharacterBBox(e,o,c,u,n,r))}get isFontSubpixelAAEnabled(){let e=this.canvasFactory.create(10,10),t=e.context;t.scale(1.5,1),t.fillText(`I`,0,10);let n=t.getImageData(0,0,10,10).data;this.canvasFactory.destroy(e);let r=!1;for(let e=3;e0&&n[e]<255){r=!0;break}return M(this,`isFontSubpixelAAEnabled`,r)}showText(e,t){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(e,G.showText).resetBBox(e),this.current.textRenderingMode&p.ADD_TO_PATH_FLAG&&this.dependencyTracker.recordFutureForcedDependency(`textClip`,e).inheritPendingDependenciesAsFutureForcedDependencies());let n=this.current,r=n.font;if(r.isType3Font){let r=this.#g(n.fillAlpha);this.showType3Text(e,t),this.dependencyTracker?.recordShowTextOperation(e),this.#_(r);return}let i=n.fontSize;if(i===0){this.dependencyTracker?.recordOperation(e);return}let a=this.#g(n.fillAlpha),o=this.ctx,s=n.fontSizeScale,c=n.charSpacing,l=n.wordSpacing,u=n.fontDirection,d=n.textHScale*u,f=t.length,m=r.vertical,h=m?1:-1,g=r.defaultVMetrics,_=i*n.fontMatrix[0],v=n.textRenderingMode===p.FILL&&!r.disableFontFace&&!n.patternFill;o.save(),n.textMatrix&&o.transform(...n.textMatrix),o.translate(n.x,n.y+n.textRise),u>0?o.scale(d,-1):o.scale(d,1);let y,b,x=n.textRenderingMode&p.FILL_STROKE_MASK,S=x===p.FILL||x===p.FILL_STROKE,C=x===p.STROKE||x===p.FILL_STROKE,w=n.lineWidth,T=n.textMatrixScale;if(T===0||w===0?C&&(w=this.getSinglePixelWidth()):w/=T,s!==1&&(o.scale(s,s),w/=s),o.lineWidth=w,S&&n.patternFill){o.save();let t=n.fillColor.getPattern(o,this,V(o),Y.FILL,e);y=B(o),o.restore(),o.fillStyle=t}if(C&&n.patternStroke){o.save();let t=n.strokeColor.getPattern(o,this,V(o),Y.STROKE,e);b=B(o),o.restore(),o.strokeStyle=t}if(r.isInvalidPDFjsFont){let r=[],i=0;for(let e of t)r.push(e.unicode),i+=e.width;let s=r.join(``);if(o.fillText(s,0,0),this.dependencyTracker!==null){let t=o.measureText(s);this.dependencyTracker.recordBBox(e,this.ctx,-t.actualBoundingBoxLeft,t.actualBoundingBoxRight,-t.actualBoundingBoxAscent,t.actualBoundingBoxDescent).recordShowTextOperation(e)}n.x+=i*_*d,o.restore(),this.compose(),this.#_(a);return}let E=0,D;for(D=0;D0){w=o.measureText(f);let e=w.width*1e3/i*s;if(Cw??o.measureText(f));else if(this.paintChar(e,f,x,S,y,b),p){let t=x+i*p.offset.x/s,n=S-i*p.offset.y/s;this.paintChar(e,p.fontChar,t,n,y,b)}}let T=m?C*_-d*u:C*_+d*u;E+=T,a&&o.restore()}m?n.y-=E:n.x+=E*d,o.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(e),this.#_(a)}showType3Text(e,t){let n=this.ctx,r=this.current,a=r.font,o=r.fontSize,s=r.fontDirection,c=a.vertical?1:-1,l=r.charSpacing,u=r.wordSpacing,d=r.textHScale*s,f=r.fontMatrix||i,m=t.length,h=r.textRenderingMode===p.INVISIBLE,g,_,y,b;if(h||o===0)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,n.save(),r.textMatrix&&n.transform(...r.textMatrix),n.translate(r.x,r.y+r.textRise),n.scale(d,s);let x=this.dependencyTracker;for(this.dependencyTracker=x?new Ot(x,e):null,g=0;gnew e(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new Ot(this.dependencyTracker,n,!0):null)},t)}else r=this._getPattern(t,n[1],n[2]);return r}setStrokeColorN(e,...t){this.dependencyTracker?.recordSimpleData(`strokeColor`,e),this.current.strokeColor=this.getColorN_Pattern(e,t),this.current.patternStroke=!0}setFillColorN(e,...t){this.dependencyTracker?.recordSimpleData(`fillColor`,e);let n=this.current.fillColor=this.getColorN_Pattern(e,t);this.current.patternFill=!0,this.current.tilingPatternDims=n instanceof Dn?[0,0,0,0]:null}setStrokeRGBColor(e,t){this.dependencyTracker?.recordSimpleData(`strokeColor`,e),this.ctx.strokeStyle=this.current.strokeColor=t,this.current.patternStroke=!1}setStrokeTransparent(e){this.dependencyTracker?.recordSimpleData(`strokeColor`,e),this.ctx.strokeStyle=this.current.strokeColor=`transparent`,this.current.patternStroke=!1}setFillRGBColor(e,t){this.dependencyTracker?.recordSimpleData(`fillColor`,e),this.ctx.fillStyle=this.current.fillColor=t,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(e){this.dependencyTracker?.recordSimpleData(`fillColor`,e),this.ctx.fillStyle=this.current.fillColor=`transparent`,this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(e,t,n=null){let r=this.cachedPatterns.getOrInsertComputed(t,()=>Tn(this.getObject(e,t)));return n&&(r.matrix=n),r}shadingFill(e,t){if(!this.contentVisible)return;let n=this.#g(this.current.fillAlpha),i=this.ctx;this.save(e),i.fillStyle=this._getPattern(e,t).getPattern(i,this,V(i),Y.SHADING,e);let a=V(i);if(a){let{width:e,height:t}=i.canvas,n=r.slice();I.axialAlignedBoundingBox([0,0,e,t],a,n);let[o,s,c,l]=n;this.ctx.fillRect(o,s,c-o,l-s)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(e).recordFullPageBBox(e).recordDependencies(e,G.transform).recordDependencies(e,G.fill).recordOperation(e),this.compose(this.current.getClippedPathBoundingBox()),this.restore(e),this.#_(n)}beginInlineImage(){E(`Should not call beginInlineImage`)}beginImageData(){E(`Should not call beginImageData`)}paintFormXObjectBegin(e,t,n){if(this.contentVisible&&(this.save(e),this.baseTransformStack.push(this.baseTransform),t&&this.transform(e,...t),this.baseTransform=B(this.ctx),n)){I.axialAlignedBoundingBox(n,this.baseTransform,this.current.minMax);let[t,r,i,a]=n,o=new Path2D;o.rect(t,r,i-t,a-r),this.ctx.clip(o),this.dependencyTracker?.recordClipBox(e,this.ctx,t,i,r,a),this.endPath(e)}}paintFormXObjectEnd(e){this.contentVisible&&(this.restore(e),this.baseTransform=this.baseTransformStack.pop())}beginGroup(e,t){if(!this.contentVisible)return;this.save(e);let{inSMaskMode:n}=this;n&&(this.endSMaskMode(),this.current.activeSMask=null);let i=this.ctx;if((!t.needsIsolation||!t.isolated&&!t.hasSoftMask)&&!t.knockout&&!t.isGray&&this.#t===0&&i.globalAlpha===1&&i.globalCompositeOperation===`source-over`&&!n){if(t.bbox){let e=new Path2D,[n,r,a,o]=t.bbox;if(e.rect(n,r,a-n,o-r),t.matrix){let n=new Path2D;n.addPath(e,new DOMMatrix(t.matrix)),e=n}i.clip(e)}this.groupStack.push(null),this.#u.push(null),this.groupLevel++;return}!t.isolated&&!t.knockout&&this.#t===0&&w(`TODO: Fully support non-isolated non-knockout groups.`);let a=B(i);t.matrix&&i.transform(...t.matrix);let o=[0,0,i.canvas.width,i.canvas.height],s;t.bbox?(s=r.slice(),I.axialAlignedBoundingBox(t.bbox,B(i),s),s=I.intersect(s,o)||[0,0,0,0]):s=o;let c=Math.floor(s[0]),l=Math.floor(s[1]),u=Math.max(Math.ceil(s[2])-c,1),d=Math.max(Math.ceil(s[3])-l,1);this.current.startNewPathAndClipBox([0,0,u,d]);let f=this.canvasFactory.create(u,d);t.smask&&this.smaskGroupCanvases.push(f);let p=f.context,m=t.knockout&&!t.isolated?i:null,h=!t.isolated&&!t.knockout&&!t.smask&&t.needsIsolation&&this.#t>0,g=t.knockout?this.canvasFactory.create(u,d):null,_=this.#t;t.knockout?this.#t++:this.#t=0,p.translate(-c,-l),p.transform(...a);let v=!t.isolated&&!t.smask&&t.needsIsolation,y=v&&!n&&_===0&&!t.knockout&&!t.isGray&&t.hasSoftMask&&i.globalAlpha===1&&i.globalCompositeOperation===`source-over`&&this.current.transferMaps===`none`;if(v&&(n||y)&&(p.save(),p.setTransform(1,0,0,1,0,0),p.drawImage(i.canvas,-c,-l),p.restore()),t.bbox){let e=new Path2D,[n,r,i,a]=t.bbox;if(e.rect(n,r,i-n,a-r),t.matrix){let n=new Path2D;n.addPath(e,new DOMMatrix(t.matrix)),e=n}p.clip(e)}t.smask&&this.smaskStack.push({canvas:f.canvas,context:p,offsetX:c,offsetY:l,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null}),(!t.smask||this.dependencyTracker)&&(i.setTransform(1,0,0,1,0,0),i.translate(c,l),i.save()),Ln(i,p),this.ctx=p,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies([`fillAlpha`,`strokeAlpha`,`globalCompositeOperation`]).pushBaseTransform(i),this.setGState(e,[[`BM`,`source-over`],[`ca`,1],[`CA`,1],[`TR`,null]]),this.groupStack.push(i),this.#u.push({backdropCtx:m,savedKnockoutLevel:_,offsetX:c,offsetY:l,hasInnerBackdrop:h,replaceBackdrop:y,knockoutMaskEntry:g,knockoutTempEntry:null,knockoutBackdropEntry:null}),this.groupLevel++}endGroup(e,t){if(!this.contentVisible)return;this.groupLevel--;let n=this.ctx,i=this.groupStack.pop(),a=this.#u.pop();if(a&&(this.#t=a.savedKnockoutLevel),i===null){this.restore(e);return}if(t.isGray&&this.#y(n),this.ctx=i,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),t.smask)this.tempSMask=this.smaskStack.pop(),this.restore(e),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())),this.#b(a);else{this.ctx.restore();let t=B(this.ctx);this.restore(e),this.ctx.save(),this.ctx.setTransform(...t);let o=r.slice();I.axialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],t,o);let s=this.#u.at(-1);if(this.#t>0){if(a.hasInnerBackdrop){let{width:e,height:r}=n.canvas,o=this.canvasFactory.create(e,r),s=o.context;s.drawImage(i.canvas,a.offsetX,a.offsetY,e,r,0,0,e,r),s.globalCompositeOperation=`source-over`,s.drawImage(n.canvas,0,0);let c=this.#p(n.canvas);s.globalCompositeOperation=`destination-in`,s.drawImage(c.canvas,0,0);let l=this.ctx.globalCompositeOperation,u=this.ctx.globalAlpha,d=this.ctx.filter;this.ctx.save(),this.ctx.setTransform(...t),this.ctx.globalAlpha=1,F.isCanvasFilterSupported&&(this.ctx.filter=`none`),this.ctx.globalCompositeOperation=`destination-out`,this.ctx.drawImage(c.canvas,0,0),this.ctx.globalCompositeOperation=l,this.ctx.globalAlpha=u,F.isCanvasFilterSupported&&(this.ctx.filter=d??`none`),this.ctx.drawImage(o.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(c),this.canvasFactory.destroy(o)}else{let e=s?.backdropCtx??null;this.#h(this.ctx,n.canvas,{backdropCanvas:e?.canvas??null,destTransform:t,backdropOffset:e?[s.offsetX+a.offsetX,s.offsetY+a.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}}else{if(a.replaceBackdrop){let e=new Path2D;e.rect(0,0,n.canvas.width,n.canvas.height),this.ctx.clip(e),this.ctx.globalCompositeOperation=`copy`}this.ctx.drawImage(n.canvas,0,0)}this.ctx.restore(),this.canvasFactory.destroy({canvas:n.canvas,context:n}),this.#b(a),this.compose(o)}}#y(e){let{canvas:t}=e,{width:n,height:r}=t;if(F.isCanvasFilterSupported){e.save(),e.setTransform(1,0,0,1,0,0),e.filter=`grayscale(1)`,e.globalAlpha=1,e.globalCompositeOperation=`copy`,e.drawImage(t,0,0),e.restore();return}let i=e.getImageData(0,0,n,r),{data:a}=i;for(let e=0,t=a.length;ee.getAttribute(`data-canvas-name`)===o);n===-1?e.push(l):e[n]=l}else this.annotationCanvasMap.set(t,l);this.annotationCanvas.savedCtx=this.ctx,this.ctx=u,this.ctx.save(),this.ctx.setTransform(Z[0],0,0,-Z[1],0,s*Z[1]),Rn(this.ctx)}else{Rn(this.ctx),this.endPath(e);let t=new Path2D;t.rect(n[0],n[1],i,s),this.ctx.clip(t)}}this.current=new Pn(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(e,...r),this.transform(e,...i),this.baseTransform=B(this.ctx)}endAnnotation(e){this.annotationCanvas&&(this.ctx.restore(),this.#f(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(e,t){if(!this.contentVisible)return;let n=t.count;t=this.getObject(e,t.data,t),t.count=n;let r=this.#g(this.current.fillAlpha),i=this.ctx,a=this._createMaskCanvas(e,t),o=a.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(o,a.offsetX,a.offsetY),this.dependencyTracker?.resetBBox(e).recordBBox(e,this.ctx,a.offsetX,a.offsetX+o.width,a.offsetY,a.offsetY+o.height).recordOperation(e),i.restore(),a.canvasEntry&&this.canvasFactory.destroy(a.canvasEntry),this.compose(),this.#_(r)}paintImageMaskXObjectRepeat(e,t,n,r=0,i=0,a,o){if(!this.contentVisible)return;t=this.getObject(e,t.data,t);let s=this.#g(this.current.fillAlpha),c=this.ctx;c.save();let l=B(c);c.transform(n,r,i,a,0,0);let u=this._createMaskCanvas(e,t);c.setTransform(1,0,0,1,u.offsetX-l[4],u.offsetY-l[5]),this.dependencyTracker?.resetBBox(e);for(let t=0,s=o.length;tt?l/t:1,o=c>t?c/t:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t,n){let{ctx:r,current:{lineWidth:i}}=this,[a,o]=this.getScaleForStroking();if(a===o){r.lineWidth=(i||1)*a,r.stroke(t);return}let s=e.#e??=new DOMMatrix,c=r.getLineDash();n&&r.save(),r.scale(a,o),s.a=1/a,s.d=1/o;let l=new Path2D;if(l.addPath(t,s),c.length>0){let e=Math.max(a,o);r.setLineDash(c.map(t=>t/e)),r.lineDashOffset/=e}r.lineWidth=i||1,r.stroke(l),n&&r.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}};for(let e in v)Wn.prototype[e]!==void 0&&(Wn.prototype[v[e]]=Wn.prototype[e]);var Gn=class{#e=null;#t=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(e,t,n){this._source=e,this.#e=t,this.#t=n}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){return D(!this._fullReader,`BasePDFStream.getFullReader can only be called once.`),this._fullReader=new this.#e(this)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new this.#t(this,e,t);return this._rangeReaders.add(n),n}cancelAllRequests(e){this._fullReader?.cancel(e);for(let t of new Set(this._rangeReaders))t.cancel(e)}},Kn=class{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(e){this._stream=e}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){E("Abstract method `read` called")}cancel(e){E("Abstract method `cancel` called")}},qn=class{_stream=null;constructor(e,t,n){this._stream=e}async read(){E("Abstract method `read` called")}cancel(e){E("Abstract method `cancel` called")}};function Jn(e){let t=!0,n=r(`filename\\*`,`i`).exec(e);if(n){n=n[1];let e=s(n);return e=unescape(e),e=c(e),e=l(e),a(e)}if(n=o(e),n)return a(l(n));if(n=r(`filename`,`i`).exec(e),n){n=n[1];let e=s(n);return e=l(e),a(e)}function r(e,t){return RegExp(`(?:^|;)\\s*`+e+`\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)`,t)}function i(e,n){if(e){if(!/^[\x00-\xFF]+$/.test(n))return n;try{let r=new TextDecoder(e,{fatal:!0}),i=oe(n);n=r.decode(i),t=!1}catch{}}return n}function a(e){return t&&/[\x80-\xff]/.test(e)&&(e=i(`utf-8`,e),t&&(e=i(`iso-8859-1`,e))),e}function o(e){let t=[],n,i=r(`filename\\*((?!0\\d)\\d+)(\\*?)`,`ig`);for(;(n=i.exec(e))!==null;){let[,e,r,i]=n;if(e=parseInt(e,10),e in t){if(e===0)break;continue}t[e]=[r,i]}let a=[];for(let e=0;e0&&e[t-1]!==` `&&/\s/.test(e[t-1]);)t--;return e.slice(0,t)}function Zn(e){return URL.parse(e)?.origin??null}function Qn({responseHeaders:e,isHttp:t,rangeChunkSize:n,disableRange:r}){let i={contentLength:0,isRangeSupported:!1},a=parseInt(e.get(`Content-Length`),10);return!Number.isInteger(a)||(i.contentLength=a,a<=2*n)||r||!t||e.get(`Accept-Ranges`)!==`bytes`||(e.get(`Content-Encoding`)||`identity`)===`identity`&&(i.isRangeSupported=!0),i}function $n(e){let t=e.get(`Content-Disposition`);if(t){let e=Jn(t);if(e.includes(`%`))try{e=decodeURIComponent(e)}catch{}if(Ee(e))return e}return null}function er(e,t){return new re(`Unexpected server response (${e}) while retrieving PDF "${t.href}".`,e,e===404||e===0&&t.protocol===`file:`)}function tr(e,t){if(e!==t)throw Error(`Expected range response-origin "${e}" to match "${t}".`)}function nr(e,t,n,r){return fetch(e,{method:`GET`,headers:t,signal:r.signal,mode:`cors`,credentials:n?`include`:`same-origin`,redirect:`follow`})}function rr(e,t){if(e!==200&&e!==206)throw er(e,t)}function ir(e){if(e instanceof Uint8Array)return e.buffer;if(e instanceof ArrayBuffer)return e;throw Error(`getArrayBuffer - unexpected data: ${e}`)}var ar=class extends Gn{_responseOrigin=null;constructor(e){super(e,or,sr);let{httpHeaders:t,url:n}=e;D(/https?:/.test(n.protocol),`PDFFetchStream only supports http(s):// URLs.`),this.headers=Yn(!0,t)}},or=class extends Kn{_abortController=new AbortController;_reader=null;constructor(e){super(e);let{disableRange:t,disableStream:n,rangeChunkSize:r,url:i,withCredentials:a}=e._source;this._isStreamingSupported=!n,nr(i,new Headers(e.headers),a,this._abortController).then(n=>{e._responseOrigin=Zn(n.url),rr(n.status,i),this._reader=n.body.getReader();let a=n.headers,{contentLength:o,isRangeSupported:s}=Qn({responseHeaders:a,isHttp:!0,rangeChunkSize:r,disableRange:t});this._contentLength=o,this._isRangeSupported=s,this._filename=$n(a),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new P(`Streaming is disabled.`)),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,this._callOnProgress(),{value:ir(e),done:!1})}cancel(e){this._reader?.cancel(e),this._abortController.abort()}},sr=class extends qn{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(e,t,n){super(e,t,n);let{url:r,withCredentials:i}=e._source,a=new Headers(e.headers);a.append(`Range`,`bytes=${t}-${n-1}`),nr(r,a,i,this._abortController).then(t=>{tr(Zn(t.url),e._responseOrigin),rr(t.status,r),this._reader=t.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:{value:ir(e),done:!1}}cancel(e){this._reader?.cancel(e),this._abortController.abort()}};function cr(e){return e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function lr(){for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}var ur=class extends Gn{_progressiveDone=!1;_queuedChunks=[];constructor(e){super(e,dr,fr);let{pdfDataRangeTransport:t}=e,{initialData:n,progressiveDone:r}=t;if(n?.length>0){let e=cr(n);this._queuedChunks.push(e)}this._progressiveDone=r,t.transportReady(e=>{switch(e.type){case`range`:case`progressiveRead`:this.#e(e.begin,e.chunk);break;case`progressiveDone`:this._fullReader?.progressiveDone(),this._progressiveDone=!0}})}#e(e,t){let n=cr(t);if(e===void 0)this._fullReader?this._fullReader._enqueue(n):this._queuedChunks.push(n);else{let t=this._rangeReaders.keys().find(t=>t._begin===e);D(t,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),t._enqueue(n)}}getFullReader(){let e=super.getFullReader();return this._queuedChunks=null,e}getRangeReader(e,t){let n=super.getRangeReader(e,t);return n&&(n.onDone=()=>this._rangeReaders.delete(n),this._source.pdfDataRangeTransport.requestDataRange(e,t)),n}cancelAllRequests(e){super.cancelAllRequests(e),this._source.pdfDataRangeTransport.abort()}},dr=class extends Kn{#e=lr.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(e){super(e);let{pdfDataRangeTransport:t,disableRange:n,disableStream:r}=e._source,{length:i,contentDispositionFilename:a}=t;this._queuedChunks=e._queuedChunks||[];for(let e of this._queuedChunks)this._loaded+=e.byteLength;this._done=e._progressiveDone,this._contentLength=i,this._isStreamingSupported=!r,this._isRangeSupported=!n,Ee(a)&&(this._filename=a),this._headersCapability.resolve();let o=this._loaded;Promise.resolve().then(()=>{o>0&&this._loaded===o&&this._callOnProgress()})}_enqueue(e){this._done||(this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunks.push(e),this._loaded+=e.byteLength,this._callOnProgress())}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this.#e()}progressiveDone(){this._done||=!0,this._queuedChunks.length===0&&this.#e()}},fr=class extends qn{#e=lr.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(e,t,n){super(e,t,n),this._begin=t}_enqueue(e){this._done||(this._requests.length===0?this._queuedChunk=e:(this._requests.shift().resolve({value:e,done:!1}),this.#e()),this._done=!0,this.onDone?.())}async read(){if(this._queuedChunk){let e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this.#e(),this.onDone?.()}},pr=200,mr=206;function hr(e){return typeof e==`string`?oe(e).buffer:e}var gr=class extends Gn{#e=new WeakMap;_responseOrigin=null;constructor(e){super(e,_r,vr);let{httpHeaders:t,url:n}=e;this.url=n,this.isHttp=/https?:/.test(n.protocol),this.headers=Yn(this.isHttp,t)}_request(e){let t=new XMLHttpRequest,n={validateStatus:null,onHeadersReceived:e.onHeadersReceived,onDone:e.onDone,onError:e.onError,onProgress:e.onProgress};this.#e.set(t,n),t.open(`GET`,this.url),t.withCredentials=this._source.withCredentials;for(let[e,n]of this.headers)t.setRequestHeader(e,n);return this.isHttp&&`begin`in e&&`end`in e?(t.setRequestHeader(`Range`,`bytes=${e.begin}-${e.end-1}`),n.validateStatus=e=>e===mr||e===pr):n.validateStatus=e=>e===pr,t.responseType=`arraybuffer`,D(e.onError,"Expected `onError` callback to be provided."),t.onerror=()=>e.onError(t.status),t.onreadystatechange=this.#n.bind(this,t),t.onprogress=this.#t.bind(this,t),t.send(null),t}#t(e,t){this.#e.get(e)?.onProgress?.(t)}#n(e,t){let n=this.#e.get(e);if(!n||(e.readyState>=2&&n.onHeadersReceived&&(n.onHeadersReceived(),delete n.onHeadersReceived),e.readyState!==4)||!this.#e.has(e))return;if(this.#e.delete(e),e.status===0&&this.isHttp){n.onError(e.status);return}let r=e.status||pr;if(!n.validateStatus(r)){n.onError(e.status);return}let i=hr(e.response);if(r===mr){let t=e.getResponseHeader(`Content-Range`);/bytes \d+-\d+\/\d+/.test(t)?n.onDone(i):(T(`Missing or invalid "Content-Range" header.`),n.onError(0))}else i?n.onDone(i):n.onError(e.status)}_abortRequest(e){this.#e.has(e)&&(this.#e.delete(e),e.abort())}getRangeReader(e,t){let n=super.getRangeReader(e,t);return n&&(n.onClosed=()=>this._rangeReaders.delete(n)),n}},_r=class extends Kn{#e=lr.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(e){super(e),this._fullRequestXhr=e._request({onHeadersReceived:this.#t.bind(this),onDone:this.#n.bind(this),onError:this.#r.bind(this),onProgress:this.#i.bind(this)})}#t(){let e=this._stream,{disableRange:t,rangeChunkSize:n}=e._source,r=this._fullRequestXhr;e._responseOrigin=Zn(r.responseURL);let i=r.getAllResponseHeaders(),a=new Headers(i?Xn(i.trimStart()).split(/[\r\n]+/).map(e=>{let[t,...n]=e.split(`: `);return[t,n.join(`: `)]}):[]),{contentLength:o,isRangeSupported:s}=Qn({responseHeaders:a,isHttp:e.isHttp,rangeChunkSize:n,disableRange:t});this._contentLength=o,this._isRangeSupported=s,this._filename=$n(a),this._isRangeSupported&&e._abortRequest(r),this._headersCapability.resolve()}#n(e){this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._cachedChunks.push(e),this._done=!0,this._cachedChunks.length===0&&this.#e()}#r(e){this._storedError=er(e,this._stream.url),this._headersCapability.reject(this._storedError);for(let e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}#i(e){this.onProgress?.({loaded:e.loaded,total:e.lengthComputable?e.total:this._contentLength})}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this._headersCapability.reject(e),this.#e(),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}},vr=class extends qn{#e=lr.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(e,t,n){super(e,t,n),this._requestXhr=e._request({begin:t,end:n,onHeadersReceived:this.#t.bind(this),onDone:this.#n.bind(this),onError:this.#r.bind(this),onProgress:null})}#t(){let e=Zn(this._requestXhr?.responseURL);try{tr(e,this._stream._responseOrigin)}catch(e){this._storedError=e,this.#r(0)}}#n(e){this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0,this.#e(),this.onClosed?.()}#r(e){this._storedError??=er(e,this._stream.url);for(let e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this.#e(),this._stream._abortRequest(this._requestXhr),this.onClosed?.()}};function yr(e,t=null){let n=process.getBuiltinModule(`fs`),{Readable:r}=process.getBuiltinModule(`stream`),i=n.createReadStream(e,t);return r.toWeb(i)}var br=class extends Gn{constructor(e){super(e,xr,Sr);let{url:t}=e;D(t.protocol===`file:`,`PDFNodeStream only supports file:// URLs.`)}},xr=class extends Kn{_reader=null;constructor(e){super(e);let{disableRange:t,disableStream:n,rangeChunkSize:r,url:i}=e._source;this._isStreamingSupported=!n,process.getBuiltinModule(`fs/promises`).lstat(i).then(e=>{let n=yr(i);this._reader=n.getReader();let{size:a}=e;this._contentLength=a,this._isRangeSupported=!t&&a>2*r,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new P(`Streaming is disabled.`)),this._headersCapability.resolve()}).catch(e=>{e.code===`ENOENT`&&(e=er(0,i)),this._headersCapability.reject(e)})}async read(){await this._headersCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,this._callOnProgress(),{value:ir(e),done:!1})}cancel(e){this._reader?.cancel(e)}},Sr=class extends qn{_readCapability=Promise.withResolvers();_reader=null;constructor(e,t,n){super(e,t,n);let{url:r}=e._source;try{let e=yr(r,{start:t,end:n-1});this._reader=e.getReader(),this._readCapability.resolve()}catch(e){this._readCapability.reject(e)}}async read(){await this._readCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:{value:ir(e),done:!1}}cancel(e){this._reader?.cancel(e)}};function Cr(e){return Ae(e)?ar:t?br:gr}var wr=class{static#e=null;static#t=``;static get workerPort(){return this.#e}static set workerPort(e){if(!(typeof Worker<`u`&&e instanceof Worker)&&e!==null)throw Error("Invalid `workerPort` type.");this.#e=e}static get workerSrc(){return this.#t}static set workerSrc(e){if(typeof e!=`string`)throw Error("Invalid `workerSrc` type.");this.#t=e}},Tr=class{#e;#t;constructor({parsedData:e,rawData:t}){this.#e=e,this.#t=t}getRaw(){return this.#t}get(e){return this.#e.get(e)??null}[Symbol.iterator](){return this.#e.entries()}},Er=Symbol(`INTERNAL`),Dr=class{#e=!1;#t=!1;#n=!1;#r=!0;constructor(e,{name:t,intent:n,usage:r,rbGroups:i}){this.#e=!!(e&o.DISPLAY),this.#t=!!(e&o.PRINT),this.name=t,this.intent=n,this.usage=r,this.rbGroups=i}get visible(){if(this.#n)return this.#r;if(!this.#r)return!1;let{print:e,view:t}=this.usage;return this.#e?t?.viewState!==`OFF`:!this.#t||e?.printState!==`OFF`}_setVisible(e,t,n=!1){e!==Er&&E("Internal method `_setVisible` called."),this.#n=n,this.#r=t}get serializable(){return{userSet:this.#n,visible:this.#r}}},Or=class e{#e=null;#t=new Map;#n=null;#r=null;#i;creator=null;name=null;constructor(e,t=o.DISPLAY,n=null){if(this.#i=e,this.renderingIntent=t,e!==null){this.name=e.name,this.creator=e.creator,this.#r=e.order;for(let n of e.groups)this.#t.set(n.id,new Dr(t,n));if(n){n.size!==this.#t.size&&E(`Incorrect serialized groupState.`);for(let[e,t]of n)this.#t.get(e)._setVisible(Er,t.visible,t.userSet)}else{if(e.baseState===`OFF`)for(let e of this.#t.values())e._setVisible(Er,!1);for(let t of e.on)this.#t.get(t)._setVisible(Er,!0);for(let t of e.off)this.#t.get(t)._setVisible(Er,!1)}this.#n=this.getHash()}}#a(e){let t=e.length;if(t<2)return!0;let n=e[0];for(let r=1;re===t+1)&&(this.#e=null)}deletePages(e){this.#a();let t=this.#e,n=this.#o();this.#i={pageNumberToId:t.slice(),pagesNumber:this.#n,prevPageNumbers:this.#t.slice()};let r=this.#n-e.length;this.#n=r;let i=this.#e=new Uint32Array(r);this.#t=new Int32Array(r);let a=0,o=0;for(let n of e){let e=n-1;e!==a&&(i.set(t.subarray(a,e),o),o+=e-a),a=e+1}athis.#e[e-1])}}cancelCopy(){this.#r=null}pastePages(e){this.#a();let t=this.#e,n=this.#o(),{pageNumbers:r,pageIds:i}=this.#r,a=this.#n+r.length;this.#n=a;let o=this.#e=new Uint32Array(a);this.#t=new Int32Array(a),o.set(t.subarray(0,e),0),o.set(i,e),o.set(t.subarray(e),e+r.length),this.#s(n,null,e,r),this.#r=null}#s(e,t=null,n=-1,r=null){let i=this.#t,a=this.#e,o=n+(r?.length??0),s=new Map;for(let c=0,l=this.#n;c=n&&ce[0]-t[0]);for(let n=0,r=e.length;ne-t);let t=new Map;for(let n=0,r=e.length;n({...Promise.withResolvers(),data:Ar}),Mr=class{#e=new Map;get(e,t=null){if(t){let n=this.#e.getOrInsertComputed(e,jr);return n.promise.then(()=>t(n.data)),null}let n=this.#e.get(e);if(!n||n.data===Ar)throw Error(`Requesting object that isn't resolved yet ${e}.`);return n.data}has(e){let t=this.#e.get(e);return!!t&&t.data!==Ar}delete(e){let t=this.#e.get(e);return!t||t.data===Ar?!1:(this.#e.delete(e),!0)}resolve(e,t=null){let n=this.#e.getOrInsertComputed(e,jr);if(n.data!==Ar)throw Error(`Object already resolved ${e}.`);n.data=t,n.resolve()}clear(){for(let{data:e}of this.#e.values())e?.bitmap?.close();this.#e.clear()}*[Symbol.iterator](){for(let[e,{data:t}]of this.#e)t!==Ar&&(yield[e,t])}},Nr=1e5,Pr=30,Fr=class e{#e=Promise.withResolvers();#t=null;#n=!1;#r=!!globalThis.FontInspector?.enabled;#i=null;#a=null;#o=null;#s=0;#c=0;#l=null;#u=null;#d=0;#f=0;#p=Object.create(null);#m=[];#h=null;#g=[];#_=new WeakMap;#v=null;static#y=new Map;static#b=new Map;static#x=new WeakMap;static#S=null;static#C=new Set;constructor({textContentSource:t,images:n,container:r,viewport:i}){if(t instanceof ReadableStream)this.#h=t;else if(typeof t==`object`)this.#h=new ReadableStream({start(e){e.enqueue(t),e.close()}});else throw Error(`No "textContentSource" parameter specified.`);this.#t=this.#u=r,this.#i=n,this.#f=i.scale*Ie.pixelRatio,this.#d=i.rotation,this.#o={div:null,properties:null,ctx:null};let{pageWidth:a,pageHeight:o,pageX:s,pageY:c}=i.rawDims;this.#v=[1,0,0,-1,-s,c+o],this.#c=a,this.#s=o,e.#k(),r.style.setProperty(`--min-font-size`,e.#S),Fe(r,i),this.#e.promise.finally(()=>{e.#C.delete(this),this.#o=null,this.#p=null}).catch(()=>{})}static get fontFamilyMap(){let{isWindows:e,isFirefox:t}=F.platform;return M(this,`fontFamilyMap`,new Map([[`sans-serif`,`${e&&t?`Calibri, `:``}sans-serif`],[`monospace`,`${e&&t?`Lucida Console, `:``}monospace`]]))}render(){this.#i&&this.#t.append(this.#i.render());let t=()=>{this.#l.read().then(({value:e,done:n})=>{if(n){this.#e.resolve();return}this.#a??=e.lang,Object.assign(this.#p,e.styles),this.#w(e.items),t()},this.#e.reject)};return this.#l=this.#h.getReader(),e.#C.add(this),t(),this.#e.promise}update({viewport:t,onBefore:n=null}){let r=t.scale*Ie.pixelRatio,i=t.rotation;if(i!==this.#d&&(n?.(),this.#d=i,Fe(this.#u,{rotation:i})),r!==this.#f){n?.(),this.#f=r;let t={div:null,properties:null,ctx:e.#D(this.#a)};for(let e of this.#g)t.properties=this.#_.get(e),t.div=e,this.#E(t)}}cancel(){let e=new P(`TextLayer task cancelled.`);this.#l?.cancel(e).catch(()=>{}),this.#l=null,this.#e.reject(e)}get textDivs(){return this.#g}get textContentItemsStr(){return this.#m}#w(t){if(this.#n)return;this.#o.ctx??=e.#D(this.#a);let n=this.#g,r=this.#m;for(let e of t){if(n.length>Nr){T(`Ignoring additional textDivs for performance reasons.`),this.#n=!0;return}if(e.str===void 0){if(e.type===`beginMarkedContentProps`||e.type===`beginMarkedContent`){let t=this.#t;this.#t=document.createElement(`span`),this.#t.classList.add(`markedContent`),e.id&&this.#t.setAttribute(`id`,e.id),e.tag===`Artifact`&&(this.#t.ariaHidden=!0),t.append(this.#t)}else e.type===`endMarkedContent`&&(this.#t=this.#t.parentNode);continue}r.push(e.str),this.#T(e)}}#T(t){let n=document.createElement(`span`),r={angle:0,canvasWidth:0,hasText:t.str!==``,hasEOL:t.hasEOL,fontSize:0};this.#g.push(n);let i=I.transform(this.#v,t.transform),a=Math.atan2(i[1],i[0]),o=this.#p[t.fontName];o.vertical&&(a+=Math.PI/2);let s=this.#r&&o.fontSubstitution||o.fontFamily;s=e.fontFamilyMap.get(s)||s;let c=Math.hypot(i[2],i[3]),l=c*e.#A(s,o,this.#a),u,d;a===0?(u=i[4],d=i[5]-l):(u=i[4]+l*Math.sin(a),d=i[5]-l*Math.cos(a));let f=n.style;f.left=`${(100*u/this.#c).toFixed(2)}%`,f.top=`${(100*d/this.#s).toFixed(2)}%`,f.setProperty(`--font-height`,`${c.toFixed(2)}px`),f.fontFamily=s,r.fontSize=c,n.setAttribute(`role`,`presentation`),n.textContent=t.str,n.dir=t.dir,this.#r&&(n.dataset.fontName=o.fontSubstitutionLoadedName||t.fontName),a!==0&&(r.angle=180/Math.PI*a);let p=!1;if(t.str.length>1)p=!0;else if(t.str!==` `&&t.transform[0]!==t.transform[3]){let e=Math.abs(t.transform[0]),n=Math.abs(t.transform[3]);e!==n&&Math.max(e,n)/Math.min(e,n)>1.5&&(p=!0)}if(p&&(r.canvasWidth=o.vertical?t.height:t.width),this.#_.set(n,r),this.#o.div=n,this.#o.properties=r,this.#E(this.#o),r.hasText&&this.#t.append(n),r.hasEOL){let e=document.createElement(`br`);e.setAttribute(`role`,`presentation`),this.#t.append(e)}}#E(t){let{div:n,properties:r,ctx:i}=t,{style:a}=n;if(r.canvasWidth!==0&&r.hasText){let{fontFamily:t}=a,{canvasWidth:o,fontSize:s}=r;e.#O(i,s*this.#f,t);let{width:c}=i.measureText(n.textContent);c>0&&a.setProperty(`--scale-x`,o*this.#f/c)}r.angle!==0&&a.setProperty(`--rotate`,`${r.angle}deg`)}static cleanup(){if(!(this.#C.size>0)){this.#y.clear();for(let{canvas:e}of this.#b.values())e.remove();this.#b.clear()}}static#D(e=null){let t=this.#b.get(e||=``);if(!t){let n=document.createElement(`canvas`);n.style.cssText=`position:absolute;top:0;left:0;width:0;height:0;display:none;letter-spacing:normal;word-spacing:normal`,n.lang=e,document.body.append(n),t=n.getContext(`2d`,{alpha:!1,willReadFrequently:!0}),this.#b.set(e,t),this.#x.set(t,{size:0,family:``})}return t}static#O(e,t,n){let r=this.#x.get(e);(t!==r.size||n!==r.family)&&(e.font=`${t}px ${n}`,r.size=t,r.family=n)}static#k(){if(this.#S!==null)return;let e=document.createElement(`div`);e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize=`1px`,e.style.position=`absolute`,e.textContent=`X`,document.body.append(e),this.#S=e.getBoundingClientRect().height,e.remove()}static#A(e,t,n){let r=this.#y.get(e);if(r)return r;let i=this.#D(n);i.canvas.width=i.canvas.height=Pr,this.#O(i,Pr,e);let a=i.measureText(``),o=a.fontBoundingBoxAscent,s=Math.abs(a.fontBoundingBoxDescent);i.canvas.width=i.canvas.height=0;let c=.8;return o?c=o/(o+s):(F.platform.isFirefox&&T("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),t.ascent?c=t.ascent:t.descent&&(c=1+t.descent)),this.#y.set(e,c),c}},Ir=100;function Lr(e={}){let n=new Rr,{docId:r}=n,i=e.url?Wt(e.url):null,a=e.data?Gt(e.data):null,o=e.httpHeaders||null,s=e.withCredentials===!0,c=e.password??null,l=e.range instanceof zr?e.range:null,u=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:2**16,d=e.worker instanceof Hr?e.worker:null,f=e.verbosity,p=typeof e.docBaseUrl==`string`&&!Te(e.docBaseUrl)?e.docBaseUrl:null,m=Kt(e.cMapUrl),h=e.cMapPacked!==!1,g=Kt(e.iccUrl),_=Kt(e.standardFontDataUrl),v=Kt(e.wasmUrl),y=e.stopAtErrors!==!0,b=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,x=typeof e.isOffscreenCanvasSupported==`boolean`?e.isOffscreenCanvasSupported:!t,C=typeof e.isImageDecoderSupported==`boolean`?e.isImageDecoderSupported:!t,w=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,T=typeof e.disableFontFace==`boolean`?e.disableFontFace:t,E=e.fontExtraProperties===!0,D=e.enableXfa===!0,O=e.ownerDocument||globalThis.document,k=e.disableRange===!0,A=e.disableStream===!0,j=e.disableAutoFetch===!0,M=e.pdfBug===!0,N=e.CanvasFactory||(t?ln:nn),ee=e.FilterFactory||(t?cn:an),te=e.BinaryDataFactory||(t?un:en),ne=e.enableHWA===!0,re=e.enableWebGPU===!0?hn():Promise.resolve(!1),ie=e.useWasm!==!1,P=e.pagesMapper||new kr,ae=typeof e.useSystemFonts==`boolean`?e.useSystemFonts:!t&&!T,oe=typeof e.useWorkerFetch==`boolean`?e.useWorkerFetch:!!(te===en&&m&&h&&_&&v&&Ae(m,document.baseURI)&&Ae(_,document.baseURI)&&Ae(v,document.baseURI));S(f);let F={canvasFactory:new N({ownerDocument:O,enableHWA:ne}),filterFactory:new ee({docId:r,ownerDocument:O}),binaryDataFactory:oe?null:new te({cMapUrl:m,standardFontDataUrl:_,wasmUrl:v})};d||(d=Hr.create({verbosity:f,port:wr.workerPort}),n._worker=d);let I={docId:r,apiVersion:`6.3.289`,data:a,password:c,disableAutoFetch:j,rangeChunkSize:u,docBaseUrl:p,enableXfa:D,evaluatorOptions:{maxImageSize:b,disableFontFace:T,ignoreErrors:y,isOffscreenCanvasSupported:x,isImageDecoderSupported:C,canvasMaxAreaInBytes:w,fontExtraProperties:E,useSystemFonts:ae,useWasm:ie,useWorkerFetch:oe,cMapUrl:m,cMapPacked:h,iccUrl:g,standardFontDataUrl:_,wasmUrl:v,hasGPU:!1}},se={ownerDocument:O,pdfBug:M,styleElement:null,enableHWA:ne,loadingParams:{disableAutoFetch:j,enableXfa:D}};return Promise.all([d.promise,re]).then(function([,e]){if(d.destroyed)throw Error(`Worker was destroyed`);I.evaluatorOptions.hasGPU=e;let t=d.messageHandler.sendWithPromise(`GetDocRequest`,I,a?[a.buffer]:null),c;if(!a){if(l)c=new ur({pdfDataRangeTransport:l,disableRange:k,disableStream:A});else if(i)c=new(Cr(i))({url:i,httpHeaders:o,withCredentials:s,rangeChunkSize:u,disableRange:k,disableStream:A});else throw Error("getDocument - expected either `data`, `range`, or `url` parameter.")}return t.then(e=>{if(d.destroyed)throw Error(`Worker was destroyed`);let t=new Qt(r,e,d.port),i=new Ur(t,n,c,se,F,P);if(n._transport=i,n.destroyed)throw Error(`Loading aborted`);t.send(`Ready`,null)})}).catch(n._capability.reject).finally(n._setupCapability.resolve),n}var Rr=class e{static#e=0;_capability=Promise.withResolvers();_setupCapability=Promise.withResolvers();_transport=null;_worker=null;docId=`d${e.#e++}`;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0,this._capability.promise.catch(()=>{});try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._setupCapability.promise,await this._transport?.destroy()}catch(e){throw this._worker?.port&&delete this._worker._pendingDestroy,e}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}},zr=class{#e=Promise.withResolvers();#t=null;constructor(e,t,n=!1,r=null){this.length=e,this.initialData=t,this.progressiveDone=n,this.contentDispositionFilename=r}onDataRange(e,t){this.#t({type:`range`,begin:e,chunk:t})}onDataProgressiveRead(e){this.#e.promise.then(()=>{this.#t({type:`progressiveRead`,chunk:e})})}onDataProgressiveDone(){this.#e.promise.then(()=>{this.#t({type:`progressiveDone`})})}transportReady(e){this.#t=e,this.#e.resolve()}requestDataRange(e,t){E(`Abstract method PDFDataRangeTransport.requestDataRange`)}abort(){}},Br=class{constructor(e,t){this._pdfInfo=e,this._transport=t}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return M(this,`isPureXfa`,!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAttachmentContent(e){return this._transport.getAttachmentContent(e)}getAnnotationsByType(e,t){return this._transport.getAnnotationsByType(e,t)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:e=`display`}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(t)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(e,t=null){return this._transport.extractPages(e,t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}getSignatures(){return this._transport.getSignatures()}getSignatureData(e){return this._transport.getSignatureData(e)}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}},Vr=class e{#e=!1;#t=null;constructor(e,t,n,r,i=!1){this._pageIndex=e,this._pageInfo=t,this._transport=n,this._stats=i?new ke:null,this._pdfBug=i,this.commonObjs=n.commonObjs,this.objs=new Mr,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,this.#t=r,this.imageCoordinates=null}clone(t){let n=new e(t,this._pageInfo,this._transport,this.#t,this._pdfBug);return n.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(n),n}get pageNumber(){return this._pageIndex+1}set pageNumber(e){this._pageIndex=e-1,this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:e,rotation:t=this.rotate,offsetX:n=0,offsetY:r=0,dontFlip:i=!1}={}){return new _e({viewBox:this.view,userUnit:this.userUnit,scale:e,rotation:t,offsetX:n,offsetY:r,dontFlip:i})}getAnnotations({intent:e=`display`}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,t)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return M(this,`isPureXfa`,!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:e,canvas:t=e.canvas,viewport:n,intent:r=`display`,annotationMode:i=s.ENABLE,transform:a=null,background:c=null,optionalContentConfigPromise:l=null,annotationCanvasMap:u=null,pageColors:d=null,printAnnotationStorage:f=null,isEditing:p=!1,recordImages:m=!1,recordOperations:h=!1,operationsFilter:g=null}){this._stats?.time(`Overall`);let _=this._transport.getRenderingIntent(r,i,f,p),{renderingIntent:v,cacheKey:y}=_;this.#e=!1,l||=this._transport.getOptionalContentConfig(v);let b=this._intentStates.getOrInsertComputed(y,he);b.streamReaderCancelTimeout&&=(clearTimeout(b.streamReaderCancelTimeout),null);let x=!!(v&o.PRINT);b.displayReadyCapability||(b.displayReadyCapability=Promise.withResolvers(),b.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time(`Page Request`),this._pumpOperatorList(_));let S=!!(this._pdfBug&&globalThis.StepperManager?.enabled),C=!!t&&!this.recordedBBoxes&&(h||S),w=!!t&&!this.imageCoordinates&&m,T=e=>{if(b.renderTasks.delete(O),C){let e=O.gfx?.dependencyTracker.take();e&&(O.stepper?.setOperatorBBoxes(e,O.gfx.dependencyTracker.takeDebugMetadata()),h&&(this.recordedBBoxes=e))}w&&!e&&(this.imageCoordinates=O.gfx?.imagesTracker.take()),x&&(this.#e=!0),this.#n(),e?(O.capability.reject(e),this._abortOperatorList({intentState:b,reason:e instanceof Error?e:Error(e)})):O.capability.resolve(),this._stats&&(this._stats.timeEnd(`Rendering`),this._stats.timeEnd(`Overall`),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},E=null,D=null;(C||w)&&(D=new Et(t,b.operatorList.length)),C&&(E=new Dt(D,S));let O=new Gr({callback:T,params:{canvas:t,canvasContext:e,dependencyTracker:E??D,imagesTracker:w?new kt(t):null,viewport:n,transform:a,background:c},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:u,operatorList:b.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!x,pdfBug:this._pdfBug,pageColors:d,enableHWA:this._transport.enableHWA,operationsFilter:g});(b.renderTasks||=new Set).add(O);let k=O.task;return Promise.all([b.displayReadyCapability.promise,l]).then(([e,t])=>{if(this.destroyed){T();return}if(this._stats?.time(`Rendering`),!(t.renderingIntent&v))throw Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");O.initializeGraphics({transparency:e,optionalContentConfig:t}),O.operatorListChanged()}).catch(T),k}getOperatorList({intent:e=`display`,annotationMode:t=s.ENABLE,printAnnotationStorage:n=null,isEditing:r=!1}={}){function i(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(c))}let a=this._transport.getRenderingIntent(e,t,n,r,!0),o=this._intentStates.getOrInsertComputed(a.cacheKey,he),c;return o.opListReadCapability||(c=Object.create(null),c.operatorListChanged=i,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(c),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time(`Page Request`),this._pumpOperatorList(a)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:t=!1}={}){return this._transport.messageHandler.sendWithStream(`GetTextContent`,{pageId:this.#t.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:t===!0},{highWaterMark:100,size(e){return e.items.length}})}async getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then(e=>ve.textContent(e));let t=this.streamTextContent(e),n={items:[],styles:Object.create(null),lang:null};for await(let e of t)n.lang??=e.lang,Object.assign(n.styles,e.styles),n.items.push(...e.items);return n}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let e=[];for(let t of this._intentStates.values())if(this._abortOperatorList({intentState:t,reason:Error(`Page was destroyed.`),force:!0}),!t.opListReadCapability)for(let n of t.renderTasks)e.push(n.completed),n.cancel();return this.objs.clear(),this.#e=!1,Promise.all(e)}cleanup(e=!1){this.#e=!0;let t=this.#n();return e&&t&&(this._stats&&=new ke),t}#n(){if(!this.#e||this.destroyed)return!1;for(let{renderTasks:e,operatorList:t}of this._intentStates.values())if(e.size>0||!t.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}_startRenderPage(e,t){let n=this._intentStates.get(t);n&&(this._stats?.timeEnd(`Page Request`),n.displayReadyCapability?.resolve(e))}_renderPageChunk(e,t){for(let n=0,r=e.length;n{o.read().then(({value:e,done:t})=>{if(t){s.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(e,s),c())},e=>{if(s.streamReader=null,!this._transport.destroyed){if(s.operatorList){s.operatorList.lastChunk=!0;for(let e of s.renderTasks)e.operatorListChanged();this.#n()}if(s.displayReadyCapability)s.displayReadyCapability.reject(e);else if(s.opListReadCapability)s.opListReadCapability.reject(e);else throw e}})};c()}_abortOperatorList({intentState:e,reason:t,force:n=!1}){if(e.streamReader){if(e.streamReaderCancelTimeout&&=(clearTimeout(e.streamReaderCancelTimeout),null),!n){if(e.renderTasks.size>0)return;if(t instanceof we){let n=Ir;t.extraDelay>0&&t.extraDelay<1e3&&(n+=t.extraDelay),e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:t,force:!0})},n);return}}if(e.streamReader.cancel(new P(t.message)).catch(()=>{}),e.streamReader=null,!this._transport.destroyed){for(let[t,n]of this._intentStates)if(n===e){this._intentStates.delete(t);break}this.cleanup()}}}get stats(){return this._stats}},Hr=class n{#e=Promise.withResolvers();#t=null;#n=null;#r=null;static#i=0;static#a=!1;static#o=new WeakMap;static{t&&(this.#a=!0,wr.workerSrc||=`./pdf.worker.mjs`),this._isSameOrigin=(e,t)=>{let n=URL.parse(e);if(!n?.origin||n.origin===`null`)return!1;let r=new URL(t,n);return n.origin===r.origin},this._createCDNWrapper=e=>{let t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:`text/javascript`}))}}constructor({name:e=null,port:t=null,verbosity:r=C()}={}){if(this.name=e,this.destroyed=!1,this.verbosity=r,t){if(n.#o.has(t))throw Error(`Cannot use more than one PDFWorker per port.`);n.#o.set(t,this),this.#c(t)}else this.#l()}get promise(){return this.#e.promise}#s(){this.#e.resolve(),this.#t.send(`configure`,{verbosity:this.verbosity})}get port(){return this.#n}get messageHandler(){return this.#t}#c(e){this.#n=e,this.#t=new Qt(`main`,`worker`,e),this.#t.on(`ready`,()=>{}),this.#s()}#l(){if(n.#a||n.#d){this.#u();return}let{workerSrc:e}=n;try{n._isSameOrigin(window.location,e)||(e=n._createCDNWrapper(new URL(e,window.location).href));let t=new Worker(e,{type:`module`}),r=new Qt(`main`,`worker`,t),i=()=>{a.abort(),r.destroy(),t.terminate(),this.destroyed?this.#e.reject(Error(`Worker was destroyed`)):this.#u()},a=new AbortController;t.addEventListener(`error`,()=>{this.#r||i()},{signal:a.signal}),r.on(`test`,e=>{if(a.abort(),this.destroyed||!e){i();return}this.#t=r,this.#n=t,this.#r=t,this.#s()}),r.on(`ready`,e=>{if(a.abort(),this.destroyed){i();return}try{o()}catch{this.#u()}});let o=()=>{let e=new Uint8Array;r.send(`test`,e,[e.buffer])};o();return}catch{w(`The worker has been disabled.`)}this.#u()}#u(){n.#a||=(T(`Setting up fake worker.`),!0),n._setupFakeWorkerGlobal.then(e=>{if(this.destroyed){this.#e.reject(Error(`Worker was destroyed`));return}let t=new Yt;this.#n=t;let r=`fake${n.#i++}`,i=new Qt(r+`_worker`,r,t);e.setup(i,t),this.#t=new Qt(r,r+`_worker`,t),this.#s()}).catch(e=>{this.#e.reject(Error(`Setting up fake worker failed: "${e.message}".`))})}destroy(){this.destroyed=!0,this.#r?.terminate(),this.#r=null,n.#o.delete(this.#n),this.#n=null,this.#t?.destroy(),this.#t=null}static create(e){let t=this.#o.get(e?.port);if(t){if(t._pendingDestroy)throw Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return t}return new n(e)}static get workerSrc(){if(wr.workerSrc)return wr.workerSrc;throw Error(`No "GlobalWorkerOptions.workerSrc" specified.`)}static get#d(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return M(this,`_setupFakeWorkerGlobal`,(async()=>this.#d?this.#d:(await e(()=>import(this.workerSrc),[],import.meta.url)).WorkerMessageHandler)())}},Ur=class{downloadInfoCapability=Promise.withResolvers();#e=null;#t=new Map;#n=null;#r=new Map;#i=new Map;#a=new Map;#o=null;constructor(e,t,n,r,i,a){this.messageHandler=e,this.loadingTask=t,this.#n=n,this.commonObjs=new Mr,this.fontLoader=new Nt({ownerDocument:r.ownerDocument,styleElement:r.styleElement}),this.enableHWA=r.enableHWA,this.loadingParams=r.loadingParams,this._params=r,this.canvasFactory=i.canvasFactory,this.filterFactory=i.filterFactory,this.binaryDataFactory=i.binaryDataFactory,this.pagesMapper=a,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(e){let{_pageIndex:t}=e;this.#r.set(t,e),this.#i.set(t,Promise.resolve(e))}#s(e,t=null){return this.#t.getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,t))}#c({loaded:e,total:t}){this.loadingTask.onProgress?.({loaded:e,total:t,percent:t?L(Math.round(e/t*100),0,100):NaN})}get annotationStorage(){return M(this,`annotationStorage`,new gt)}getRenderingIntent(e,t=s.ENABLE,n=null,r=!1,i=!1){let a=o.DISPLAY,c=ht;switch(e){case`any`:a=o.ANY;break;case`display`:break;case`print`:a=o.PRINT;break;default:T(`getRenderingIntent - invalid intent: ${e}`)}let l=a&o.PRINT&&n instanceof _t?n:this.annotationStorage;switch(t){case s.DISABLE:a+=o.ANNOTATIONS_DISABLE;break;case s.ENABLE:break;case s.ENABLE_FORMS:a+=o.ANNOTATIONS_FORMS;break;case s.ENABLE_STORAGE:a+=o.ANNOTATIONS_STORAGE,c=l.serializable;break;default:T(`getRenderingIntent - invalid annotationMode: ${t}`)}r&&(a+=o.IS_EDITING),i&&(a+=o.OPLIST);let{ids:u,hash:d}=l.modifiedIds,f=[a,c.hash,d];return{renderingIntent:a,cacheKey:f.join(`_`),annotationStorageSerializable:c,modifiedIds:u}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#o?.reject(Error(`Worker was destroyed during onPassword callback`));let e=[];for(let t of this.#r.values())e.push(t._destroy());this.#r.clear(),this.#i.clear(),this.#a.clear(),Object.hasOwn(this,`annotationStorage`)&&this.annotationStorage.resetModified();let t=this.messageHandler.sendWithPromise(`Terminate`,null);return e.push(t),Promise.all(e).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),Fr.cleanup(),this.#n?.cancelAllRequests(new P(`Worker was terminated.`)),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:e,loadingTask:t}=this;e.on(`GetReader`,(e,t)=>{D(this.#n,"GetReader - no `BasePDFStream` instance available."),this.#e=this.#n.getFullReader(),this.#e.onProgress=e=>this.#c(e),t.onPull=()=>{this.#e.read().then(function({value:e,done:n}){if(n){t.close();return}D(e instanceof ArrayBuffer,`GetReader - expected an ArrayBuffer.`),t.enqueue(new Uint8Array(e),1,[e])}).catch(e=>{t.error(e)})},t.onCancel=e=>{this.#e.cancel(e),t.ready.catch(e=>{if(!this.destroyed)throw e})}}),e.on(`ReaderHeadersReady`,async e=>{await this.#e.headersReady;let{isStreamingSupported:t,isRangeSupported:n,contentLength:r}=this.#e;return t&&n&&(this.#e.onProgress=null),{isStreamingSupported:t,isRangeSupported:n,contentLength:r}}),e.on(`GetRangeReader`,(e,t)=>{D(this.#n,"GetRangeReader - no `BasePDFStream` instance available.");let n=this.#n.getRangeReader(e.begin,e.end);if(!n){t.close();return}t.onPull=()=>{n.read().then(function({value:e,done:n}){if(n){t.close();return}D(e instanceof ArrayBuffer,`GetRangeReader - expected an ArrayBuffer.`),t.enqueue(new Uint8Array(e),1,[e])}).catch(e=>{t.error(e)})},t.onCancel=e=>{n.cancel(e),t.ready.catch(e=>{if(!this.destroyed)throw e})}}),e.on(`GetDoc`,({pdfInfo:e})=>{this.pagesMapper.pagesNumber=e.numPages,this._numPages=e.numPages,this._htmlForXfa=e.htmlForXfa,delete e.htmlForXfa,t._capability.resolve(new Br(e,this))}),e.on(`DocException`,e=>{t._capability.reject(J(e))}),e.on(`PasswordRequest`,e=>{this.#o=Promise.withResolvers();try{if(!t.onPassword)throw J(e);t.onPassword(e=>{e instanceof Error?this.#o.reject(e):this.#o.resolve({password:e})},e.code)}catch(e){this.#o.reject(e)}return this.#o.promise}),e.on(`DataLoaded`,e=>{this.#c({loaded:e.length,total:e.length}),this.downloadInfoCapability.resolve(e)}),e.on(`StartRenderPage`,e=>{this.destroyed||this.#r.get(e.pageIndex)._startRenderPage(e.transparency,e.cacheKey)}),e.on(`commonobj`,([t,n,r])=>{if(this.destroyed||this.commonObjs.has(t))return null;switch(n){case`Font`:if(`error`in r){let e=r.error;T(`Error during font loading: ${e}`),this.commonObjs.resolve(t,e);break}let i=new Pt(new Vt(r),this._params.pdfBug&&globalThis.FontInspector?.enabled?(e,t)=>globalThis.FontInspector.fontAdded(e,t):null,r.charProcOperatorList,r.extra);this.fontLoader.bind(i).catch(()=>e.sendWithPromise(`FontFallback`,{id:t})).finally(()=>{i.fontExtraProperties||i.clearData(),this.commonObjs.resolve(t,i)});break;case`CopyLocalImage`:let{imageRef:a}=r;D(a,`The imageRef must be defined.`);for(let e of this.#r.values())for(let[,n]of e.objs){if(n?.ref!==a)continue;if(!n.dataLen)return null;let e=structuredClone(n);return this.commonObjs.resolve(t,e),n.dataLen}break;case`FontPath`:this.commonObjs.resolve(t,new Ut(r));break;case`Image`:this.commonObjs.resolve(t,r);break;case`Pattern`:let o=new Ht(r);this.commonObjs.resolve(t,o.getIR());break;default:throw Error(`Got unknown common object type ${n}`)}return null}),e.on(`obj`,([e,t,n,r])=>{if(this.destroyed)return;let i=this.#r.get(t);if(!i.objs.has(e)){if(i._intentStates.size===0){r?.bitmap?.close();return}switch(n){case`Image`:case`Pattern`:i.objs.resolve(e,r);break;default:throw Error(`Got unknown object type ${n}`)}}}),e.on(`DocProgress`,e=>{this.destroyed||this.#c(e)}),e.on(`FetchBinaryData`,async e=>{if(this.destroyed)throw Error(`Worker was destroyed.`);if(!this.binaryDataFactory)throw Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(e)})}getData(){return this.messageHandler.sendWithPromise(`GetData`,null)}saveDocument(){this.annotationStorage.size<=0&&T("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:e,transfer:t}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise(`SaveDocument`,{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:this.#e?.filename??null},t).finally(()=>{this.annotationStorage.resetModified()})}extractPages(e,t=null){let n={pageInfos:e},r,i=globalThis.ImageBitmap;if(typeof i==`function`){let t=Array.isArray(e)?e:[e];for(let e of t)e?.image instanceof i&&(r||=[]).push(e.image)}if(this.annotationStorage.size>0){let e=this.annotationStorage.serializable,{map:i}=e;e.transfer?.length&&(r?r.push(...e.transfer):r=e.transfer);let a=this.pagesMapper.getMapping();if(a){let e=new Map;for(let[n,r]of i){if(r?.pageIndex!==void 0&&r.pageIndex>=0&&r.pageIndex{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this.pagesMapper.pagesNumber)return Promise.reject(Error(`Invalid page request.`));let t=e-1,n=this.pagesMapper.getPageId(e)-1,r=this.#i.get(t);if(r)return r;let i=this.messageHandler.sendWithPromise(`GetPage`,{pageIndex:n}).then(e=>{if(this.destroyed)throw Error(`Transport destroyed`);e.refStr&&this.#a.set(e.refStr,n);let r=new Vr(t,e,this,this.pagesMapper,this._params.pdfBug);return this.#r.set(t,r),r});return this.#i.set(t,i),i}async getPageIndex(e){if(!qt(e))throw Error(`Invalid pageIndex request.`);let t=await this.messageHandler.sendWithPromise(`GetPageIndex`,{num:e.num,gen:e.gen}),n=this.pagesMapper.getPageNumber(t+1);if(n===0)throw Error(`GetPageIndex: page has been removed.`);return n-1}getAnnotations(e,t){return this.messageHandler.sendWithPromise(`GetAnnotations`,{pageIndex:this.pagesMapper.getPageId(e+1)-1,intent:t})}getFieldObjects(){return this.#s(`GetFieldObjects`)}getSignatures(){return this.#s(`GetSignatures`)}getSignatureData(e){return this.messageHandler.sendWithPromise(`GetSignatureData`,e)}hasJSActions(){return this.#s(`HasJSActions`)}getCalculationOrderIds(){return this.messageHandler.sendWithPromise(`GetCalculationOrderIds`,null)}getDestinations(){return this.messageHandler.sendWithPromise(`GetDestinations`,null)}getDestination(e){return typeof e==`string`?this.messageHandler.sendWithPromise(`GetDestination`,{id:e}):Promise.reject(Error(`Invalid destination request.`))}getPageLabels(){return this.messageHandler.sendWithPromise(`GetPageLabels`,null)}getPageLayout(){return this.messageHandler.sendWithPromise(`GetPageLayout`,null)}getPageMode(){return this.messageHandler.sendWithPromise(`GetPageMode`,null)}getViewerPreferences(){return this.messageHandler.sendWithPromise(`GetViewerPreferences`,null)}getOpenAction(){return this.messageHandler.sendWithPromise(`GetOpenAction`,null)}getAttachments(){return this.messageHandler.sendWithPromise(`GetAttachments`,null)}getAttachmentContent(e){return this.messageHandler.sendWithPromise(`GetAttachmentContent`,e)}getAnnotationsByType(e,t){return this.messageHandler.sendWithPromise(`GetAnnotationsByType`,{types:e,pageIndexesToSkip:t})}getDocJSActions(){return this.#s(`GetDocJSActions`)}getPageJSActions(e){return this.messageHandler.sendWithPromise(`GetPageJSActions`,{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getStructTree(e){return this.messageHandler.sendWithPromise(`GetStructTree`,{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getOutline(){return this.messageHandler.sendWithPromise(`GetOutline`,null)}getOptionalContentConfig(e){return this.#s(`GetOptionalContentConfig`).then(t=>new Or(t,e))}getPermissions(){return this.messageHandler.sendWithPromise(`GetPermissions`,null)}getMetadata(){let e=`GetMetadata`;return this.#t.getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,null).then(e=>({info:e[0],metadata:e[1]?new Tr(e[1]):null,contentDispositionFilename:this.#e?.filename??null,contentLength:this.#e?.contentLength??null,hasStructTree:e[2]})))}getMarkInfo(){return this.messageHandler.sendWithPromise(`GetMarkInfo`,null)}async startCleanup(e=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise(`Cleanup`,null);for(let e of this.#r.values())if(!e.cleanup())throw Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),Fr.cleanup()}}cachedPageNumber(e){if(!qt(e))return null;let t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`,n=this.#a.get(t);if(n>=0){let e=this.pagesMapper.getPageNumber(n+1);if(e!==0)return e}return null}},Wr=class{_internalRenderTask=null;onContinue=null;onError=null;constructor(e){this._internalRenderTask=e}get promise(){return this._internalRenderTask.capability.promise}cancel(e=0){this._internalRenderTask.cancel(null,e)}get separateAnnots(){let{separateAnnots:e}=this._internalRenderTask.operatorList;if(!e)return!1;let{annotationCanvasMap:t}=this._internalRenderTask;return e.form||e.canvas&&t?.size>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}},Gr=class e{#e=null;static#t=new WeakSet;constructor({callback:e,params:t,objs:n,commonObjs:r,annotationCanvasMap:i,operatorList:a,pageIndex:o,canvasFactory:s,filterFactory:c,useRequestAnimationFrame:l=!1,pdfBug:u=!1,pageColors:d=null,enableHWA:f=!1,operationsFilter:p=null}){this.callback=e,this.params=t,this.objs=n,this.commonObjs=r,this.annotationCanvasMap=i,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=o,this.canvasFactory=s,this.filterFactory=c,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=l===!0&&typeof window<`u`,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new Wr(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=t.canvas,this._canvasContext=t.canvas?null:t.canvasContext,this._enableHWA=f,this._dependencyTracker=t.dependencyTracker,this._imagesTracker=t.imagesTracker,this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:n}){if(this.cancelled)return;if(this._canvas){if(e.#t.has(this._canvas))throw Error(`Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.`);e.#t.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{viewport:r,transform:i,background:a,dependencyTracker:o,imagesTracker:s}=this.params,c=this._canvasContext||this._canvas.getContext(`2d`,{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new Wn(c,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:n},this.annotationCanvasMap,this.pageColors,o,s),this.gfx.beginDrawing({transform:i,viewport:r,transparency:t,background:a}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,n=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#e&&=(window.cancelAnimationFrame(this.#e),null),e.#t.delete(this._canvas),t||=new we(`Rendering cancelled, page ${this._pageIndex+1}`,n),this.callback(t),this.task.onError?.(t)}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#e=window.requestAnimationFrame(()=>{this.#e=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),e.#t.delete(this._canvas),this.callback())))}},Kr=`6.3.289`,qr=`1c8020a7d`,Jr=class e{#e=null;#t=null;#n;#r=null;#i=!1;#a=!1;#o=null;#s;#c=null;#l=null;static#u=null;static get _keyboardManager(){return M(this,`_keyboardManager`,new nt([[[`Escape`],e.prototype._hideDropdownFromKeyboard],[[`Space`],e.prototype._colorSelectFromKeyboard],[[`ArrowDown`,`ArrowRight`],e.prototype._moveToNext],[[`ArrowUp`,`ArrowLeft`],e.prototype._moveToPrevious],[[`Home`],e.prototype._moveToBeginning],[[`End`],e.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:n=null}){t?(this.#a=!1,this.#o=t):this.#a=!0,this.#l=t?._uiManager||n,this.#s=this.#l._eventBus,this.#n=t?.color?.toUpperCase()||this.#l?.highlightColors.values().next().value||`#FFFF98`,e.#u||=Object.freeze({blue:`pdfjs-editor-colorpicker-blue`,green:`pdfjs-editor-colorpicker-green`,pink:`pdfjs-editor-colorpicker-pink`,red:`pdfjs-editor-colorpicker-red`,yellow:`pdfjs-editor-colorpicker-yellow`})}renderButton(){let e=this.#e=document.createElement(`button`);e.className=`colorPicker`,e.tabIndex=`0`,e.setAttribute(`data-l10n-id`,`pdfjs-editor-colorpicker-button`),e.ariaHasPopup=`true`,this.#o&&(e.ariaControls=`${this.#o.id}_colorpicker_dropdown`);let t=this.#l._signal;e.addEventListener(`click`,this.#m.bind(this),{signal:t}),e.addEventListener(`keydown`,this.#p.bind(this),{signal:t});let n=this.#t=document.createElement(`span`);return n.className=`swatch`,n.ariaHidden=`true`,n.style.backgroundColor=this.#n,e.append(n),e}renderMainDropdown(){let e=this.#r=this.#d();return e.ariaOrientation=`horizontal`,e.ariaLabelledBy=`highlightColorPickerLabel`,e}#d(){let t=document.createElement(`div`),n=this.#l._signal;t.addEventListener(`contextmenu`,R,{signal:n}),t.className=`dropdown`,t.role=`listbox`,t.ariaMultiSelectable=`false`,t.ariaOrientation=`vertical`,t.setAttribute(`data-l10n-id`,`pdfjs-editor-colorpicker-dropdown`),this.#o&&(t.id=`${this.#o.id}_colorpicker_dropdown`);for(let[r,i]of this.#l.highlightColors){let a=document.createElement(`button`);a.tabIndex=`0`,a.role=`option`,a.setAttribute(`data-color`,i),a.title=r,a.setAttribute(`data-l10n-id`,e.#u[r]);let o=document.createElement(`span`);a.append(o),o.className=`swatch`,o.style.backgroundColor=i,a.ariaSelected=i===this.#n,a.addEventListener(`click`,this.#f.bind(this,i),{signal:n}),t.append(a)}return t.addEventListener(`keydown`,this.#p.bind(this),{signal:n}),t}#f(e,t){t.stopPropagation(),this.#s.dispatch(`switchannotationeditorparams`,{source:this,type:d.HIGHLIGHT_COLOR,value:e}),this.update(e)}_colorSelectFromKeyboard(e){if(e.target===this.#e){this.#m(e);return}let t=e.target.getAttribute(`data-color`);t&&this.#f(t,e)}_moveToNext(e){if(!this.#g){this.#m(e);return}if(e.target===this.#e){this.#r.firstElementChild?.focus();return}e.target.nextSibling?.focus()}_moveToPrevious(e){if(e.target===this.#r?.firstElementChild||e.target===this.#e){this.#g&&this._hideDropdownFromKeyboard();return}this.#g||this.#m(e),e.target.previousSibling?.focus()}_moveToBeginning(e){if(!this.#g){this.#m(e);return}this.#r.firstElementChild?.focus()}_moveToEnd(e){if(!this.#g){this.#m(e);return}this.#r.lastElementChild?.focus()}#p(t){e._keyboardManager.exec(this,t)}#m(e){if(this.#g){this.hideDropdown();return}if(this.#i=e.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener(`pointerdown`,this.#h.bind(this),{signal:this.#l.combinedSignal(this.#c)})),this.#e.ariaExpanded=`true`,this.#r){this.#r.classList.remove(`hidden`);return}let t=this.#r=this.#d();this.#e.append(t)}#h(e){this.#r?.contains(e.target)||this.hideDropdown()}hideDropdown(){this.#r?.classList.add(`hidden`),this.#e.ariaExpanded=`false`,this.#c?.abort(),this.#c=null}get#g(){return this.#r&&!this.#r.classList.contains(`hidden`)}_hideDropdownFromKeyboard(){if(!this.#a){if(!this.#g){this.#o?.unselect();return}this.hideDropdown(),this.#e.focus({preventScroll:!0,focusVisible:this.#i})}}update(e){if(this.#t&&(this.#t.style.backgroundColor=e),!this.#r)return;let t=this.#l.highlightColors.values();for(let n of this.#r.children)n.ariaSelected=t.next().value===e.toUpperCase()}destroy(){this.#e?.remove(),this.#e=null,this.#t=null,this.#r?.remove(),this.#r=null}},Yr=class e{#e=null;#t=!1;#n=null;#r=null;static#i=null;constructor(t){this.#n=t,this.#r=t._uiManager,e.#i||=Object.freeze({freetext:`pdfjs-editor-color-picker-free-text-input`,ink:`pdfjs-editor-color-picker-ink-input`})}renderButton(){if(this.#e)return this.#e;let{editorType:t,colorType:n,colorAndOpacityType:r,opacityType:i,color:a,opacity:o}=this.#n,s=this.#t=F.isAlphaColorInputSupported&&i!==void 0,c=this.#e=document.createElement(`input`);if(c.type=`color`,s){c.setAttribute(`alpha`,``);let e=I.hexNums[Math.round((o??1)*255)];c.value=(a||`#000000`)+e}else c.value=a||`#000000`;return c.className=`basicColorPicker`,c.tabIndex=0,c.setAttribute(`data-l10n-id`,e.#i[t]),c.addEventListener(`input`,()=>{if(s){let e=Me(c.value);if(!e)return;let[t,a,o,s]=e,l=I.makeHexColor(t,a,o);r===void 0?(this.#r.updateParams(n,l),this.#r.updateParams(i,s)):this.#r.updateParams(r,{color:l,opacity:s})}else this.#r.updateParams(n,c.value)},{signal:this.#r._signal}),c}update(e){if(this.#e){if(this.#t){let t=I.hexNums[Math.round(this.#n.opacity*255)];this.#e.value=e+t}else this.#e.value=e}}updateOpacity(e){if(!this.#e||!this.#t)return;let t=I.hexNums[Math.round(e*255)];this.#e.value=this.#n.color+t}destroy(){this.#e?.remove(),this.#e=null}hideDropdown(){}};function Xr(e){return Math.floor(L(e,0,1)*255).toString(16).padStart(2,`0`)}function Zr(e){return L(e,0,1)*255}var Qr=class{static CMYK_G([e,t,n,r]){return[`G`,1-Math.min(1,.3*e+.59*n+.11*t+r)]}static G_CMYK([e]){return[`CMYK`,0,0,0,1-e]}static G_RGB([e]){return[`RGB`,e,e,e]}static G_rgb([e]){return e=Zr(e),[e,e,e]}static G_HTML([e]){let t=Xr(e);return`#${t}${t}${t}`}static RGB_G([e,t,n]){return[`G`,.3*e+.59*t+.11*n]}static RGB_rgb(e){return e.map(Zr)}static RGB_HTML(e){return`#${e.map(Xr).join(``)}`}static T_HTML(){return`#00000000`}static T_rgb(){return[null]}static CMYK_RGB([e,t,n,r]){return[`RGB`,1-Math.min(1,e+r),1-Math.min(1,n+r),1-Math.min(1,t+r)]}static CMYK_rgb([e,t,n,r]){return[Zr(1-Math.min(1,e+r)),Zr(1-Math.min(1,n+r)),Zr(1-Math.min(1,t+r))]}static CMYK_HTML(e){let t=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(t)}static RGB_CMYK([e,t,n]){let r=1-e,i=1-t,a=1-n;return[`CMYK`,r,i,a,Math.min(r,i,a)]}},$r=class{create(e,t,n=!1){if(e<=0||t<=0)throw Error(`Invalid SVG dimensions`);let r=this._createSVG(`svg:svg`);return r.setAttribute(`version`,`1.1`),n||(r.setAttribute(`width`,`${e}px`),r.setAttribute(`height`,`${t}px`)),r.setAttribute(`preserveAspectRatio`,`none`),r.setAttribute(`viewBox`,`0 0 ${e} ${t}`),r}createElement(e){if(typeof e!=`string`)throw Error(`Invalid SVG element type`);return this._createSVG(e)}_createSVG(e){E("Abstract method `_createSVG` called.")}},ei=class extends $r{_createSVG(e){return document.createElementNS(a,e)}},ti=9,ni=new WeakSet,ri=new Date().getTimezoneOffset()*60*1e3,ii=class{static create(e){switch(e.data.annotationType){case h.LINK:return new oi(e);case h.TEXT:return new si(e);case h.WIDGET:switch(e.data.fieldType){case`Tx`:return new li(e);case`Btn`:return e.data.radioButton?new fi(e):e.data.checkBox?new di(e):new pi(e);case`Ch`:return new mi(e);case`Sig`:return new ui(e)}return new ci(e);case h.POPUP:return new hi(e);case h.FREETEXT:return new _i(e);case h.LINE:return new vi(e);case h.SQUARE:return new yi(e);case h.CIRCLE:return new bi(e);case h.POLYLINE:return new xi(e);case h.CARET:return new Ci(e);case h.INK:return new wi(e);case h.POLYGON:return new Si(e);case h.HIGHLIGHT:return new Ti(e);case h.UNDERLINE:return new Ei(e);case h.SQUIGGLY:return new Di(e);case h.STRIKEOUT:return new Oi(e);case h.STAMP:return new ki(e);case h.FILEATTACHMENT:return new Ai(e);case h.RICHMEDIA:case h.SCREEN:case h.SOUND:return new ji(e);default:return new Q(e)}}},Q=class e{#e=null;#t=!1;#n=null;constructor(e,{isRenderable:t=!1,ignoreBorder:n=!1,createQuadrilaterals:r=!1}={}){this.isRenderable=t,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableComment=e.enableComment,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,this.hasOwnCommentButton=!1,t&&(this.contentElement=this.container=this._createContainer(n)),r&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:e,richText:t}){return!!(e?.str||t?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return e._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){let{data:e}=this,t=this.annotationStorage?.getEditor(e.id);return t?t.getData():e}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){let e=this.annotationStorage?.getEditor(this.data.id);if(e)return e.commentButtonPositionInPage;let{quadPoints:t,inkLists:n,rect:r}=this.data,i=-1/0,a=-1/0;if(t?.length>=8){for(let e=0;ea?(a=t[e+1],i=t[e+2]):t[e+1]===a&&(i=Math.max(i,t[e+2]));return[i,a]}if(n?.length>=1){for(let e of n)for(let t=0,n=e.length;ta?(a=e[t+1],i=e[t]):e[t+1]===a&&(i=Math.max(i,e[t]));if(i!==1/0)return[i,a]}return r?[r[2],r[3]]:null}_normalizePoint(e){let{page:{view:t},viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:i,pageY:a}}}=this.parent;return e[1]=t[3]-e[1]+t[1],e[0]=100*(e[0]-i)/n,e[1]=100*(e[1]-a)/r,e}get commentText(){let{data:e}=this;return this.annotationStorage.getRawValue(`${l}${e.id}`)?.popup?.contents||e.contentsObj?.str||``}set commentText(e){let{data:t}=this,n={deleted:!e,contents:e||``};this.annotationStorage.updateEditor(t.id,{popup:n})||this.annotationStorage.setValue(`${l}${t.id}`,{id:t.id,annotationType:t.annotationType,page:this.parent.page,popup:n,popupRef:t.popupRef,modificationDate:new Date}),e||this.removePopup()}removePopup(){(this.#n?.popup||this.popup)?.remove(),this.#n=this.popup=null}updateEdited(e){if(!this.container)return;e.rect&&(this.#e||={rect:this.data.rect.slice(0)});let{rect:t,popup:n}=e;t&&this.#r(t);let r=this.#n?.popup||this.popup;!r&&n?.text&&(this._createPopup(n),r=this.#n.popup),r&&(r.updateEdited(e),n?.deleted&&(r.remove(),this.#n=null,this.popup=null))}resetEdited(){this.#e&&=(this.#r(this.#e.rect),this.#n?.popup.resetEdited(),null)}#r(e){let{container:{style:t},data:{rect:n,rotation:r},parent:{viewport:{rawDims:{pageWidth:i,pageHeight:a,pageX:o,pageY:s}}}}=this;n?.splice(0,4,...e),t.left=`${100*(e[0]-o)/i}%`,t.top=`${100*(a-e[3]+s)/a}%`,r===0?(t.width=`${100*(e[2]-e[0])/i}%`,t.height=`${100*(e[3]-e[1])/a}%`):this.setRotation(r)}_createContainer(e){let{data:t,parent:{page:n,viewport:r}}=this,i=document.createElement(`section`);i.setAttribute(`data-annotation-id`,t.id),!(this instanceof ci)&&!(this instanceof oi)&&!(this instanceof ji)&&(i.tabIndex=0);let{style:a}=i;if(a.zIndex=this.parent.zIndex,this.parent.zIndex+=2,t.alternativeText&&(i.title=t.alternativeText),t.noRotate&&i.classList.add(`norotate`),!t.rect||this instanceof hi){let{rotation:e}=t;return!t.hasOwnCanvas&&e!==0&&this.setRotation(e,i),i}let{width:o,height:s}=this;if(!e&&t.borderStyle.width>0){a.borderWidth=`${t.borderStyle.width}px`;let e=t.borderStyle.horizontalCornerRadius,n=t.borderStyle.verticalCornerRadius;switch((e>0||n>0)&&(a.borderRadius=`calc(${e}px * var(--total-scale-factor)) / calc(${n}px * var(--total-scale-factor))`),t.borderStyle.style){case g.SOLID:a.borderStyle=`solid`;break;case g.DASHED:a.borderStyle=`dashed`;break;case g.BEVELED:T(`Unimplemented border style: beveled`);break;case g.INSET:T(`Unimplemented border style: inset`);break;case g.UNDERLINE:a.borderBottomStyle=`solid`}let r=t.borderColor||null;r?(this.#t=!0,a.borderColor=I.makeHexColor(...r)):a.borderWidth=0}let c=I.normalizeRect([t.rect[0],n.view[3]-t.rect[1]+n.view[1],t.rect[2],n.view[3]-t.rect[3]+n.view[1]]),{pageWidth:l,pageHeight:u,pageX:d,pageY:f}=r.rawDims;a.left=`${100*(c[0]-d)/l}%`,a.top=`${100*(c[1]-f)/u}%`;let{rotation:p}=t;return t.hasOwnCanvas||p===0?(a.width=`${100*o/l}%`,a.height=`${100*s/u}%`):this.setRotation(p,i),i}setRotation(e,t=this.container){if(!this.data.rect)return;let{pageWidth:n,pageHeight:r}=this.parent.viewport.rawDims,{width:i,height:a}=this;e%180!=0&&([i,a]=[a,i]),t.style.width=`${100*i/n}%`,t.style.height=`${100*a/r}%`,t.setAttribute(`data-main-rotation`,(360-e)%360)}get _commonActions(){let e=(e,t,n)=>{let r=n.detail[e],i=r[0],a=r.slice(1);n.target.style[t]=Qr[`${i}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[t]:Qr[`${i}_rgb`](a)})};return M(this,`_commonActions`,{display:e=>{let{display:t}=e.detail,n=t%2==1;this.container.style.visibility=n?`hidden`:`visible`,this.annotationStorage.setValue(this.data.id,{noView:n,noPrint:t===1||t===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{let{hidden:t}=e.detail;this.container.style.visibility=t?`hidden`:`visible`,this.annotationStorage.setValue(this.data.id,{noPrint:t,noView:t})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:t=>{e(`bgColor`,`backgroundColor`,t)},fillColor:t=>{e(`fillColor`,`backgroundColor`,t)},fgColor:t=>{e(`fgColor`,`color`,t)},textColor:t=>{e(`textColor`,`color`,t)},borderColor:t=>{e(`borderColor`,`borderColor`,t)},strokeColor:t=>{e(`strokeColor`,`borderColor`,t)},rotation:e=>{let t=e.detail.rotation;this.setRotation(t),this.annotationStorage.setValue(this.data.id,{rotation:t})}})}_dispatchEventFromSandbox(e,t){let n=this._commonActions;for(let r of Object.keys(t.detail))(e[r]||n[r])?.(t)}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;let t=this.annotationStorage.getRawValue(this.data.id);if(!t)return;let n=this._commonActions;for(let[r,i]of Object.entries(t)){let a=n[r];a&&(a({detail:{[r]:i},target:e}),delete t[r])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:e}=this.data;if(!e)return;let[t,n,r,i]=this.data.rect.map(Math.fround);if(e.length===8){let[a,o,s,c]=e.subarray(2,6);if(r===a&&i===o&&t===s&&n===c)return}let{style:o}=this.container,s;if(this.#t){let{borderColor:e,borderWidth:t}=o;o.borderWidth=0,s=[`url('data:image/svg+xml;utf8,`,``,``],this.container.classList.add(`hasBorder`)}let c=r-t,l=i-n,{svgFactory:u}=this,d=u.createElement(`svg`);d.classList.add(`quadrilateralsContainer`),d.setAttribute(`width`,0),d.setAttribute(`height`,0),d.role=`none`;let f=u.createElement(`defs`);d.append(f);let p=u.createElement(`clipPath`),m=`clippath_${this.data.id}`;p.setAttribute(`id`,m),p.setAttribute(`clipPathUnits`,`objectBoundingBox`),f.append(p);for(let n=2,r=e.length;n`)}this.#t&&(s.push(`')`),o.backgroundImage=s.join(``)),this.container.append(d),this.container.style.clipPath=`url(#${m})`}_createPopup(e=null){let{data:t}=this,n,r;e?(n={str:e.text},r=e.date):(n=t.contentsObj,r=t.modificationDate),this.#n=new hi({data:{color:t.color,titleObj:t.titleObj,modificationDate:r,contentsObj:n,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#n||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#n}render(){E("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,t=null){let n=[];if(this._fieldObjects){let r=this._fieldObjects.get(e)||[];for(let{page:e,id:i,exportValues:a}of r){if(e===-1||i===t)continue;let r=typeof a==`string`?a:null,o=document.querySelector(`[data-element-id="${i}"]`);if(o&&!ni.has(o)){T(`_getElementsByName - element not allowed: ${i}`);continue}n.push({id:i,exportValue:r,domElement:o})}return n}for(let r of document.getElementsByName(e)){let{exportValue:e}=r,i=r.getAttribute(`data-element-id`);i!==t&&ni.has(r)&&n.push({id:i,exportValue:e,domElement:r})}return n}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(let t of e)t.classList.add(`highlightArea`);else e.classList.add(`highlightArea`)}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:e,data:{id:t}}=this;this.container.addEventListener(`dblclick`,()=>{this.linkService.eventBus?.dispatch(`switchannotationeditormode`,{source:this,mode:e,editId:t,mustEnterInEditMode:!0})})}updateOC(e){!this.data.oc||!e||(e.isVisible(this.data.oc)?this.show():this.hide())}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}_setBackgroundColor(e){let t=this.data.backgroundColor||null;e.style.backgroundColor=t===null?`transparent`:I.makeHexColor(...t)}},ai=class extends Q{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.editor=e.editor}render(){return this.container.className=`editorAnnotation`,this.container}createOrUpdatePopup(){let{editor:e}=this;e.hasComment&&this._createPopup(e.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(e){this.editor.comment=e,e||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}},oi=class extends Q{constructor(e,t=null){super(e,{isRenderable:!0,ignoreBorder:!!t?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=e.data.isTooltipOnly}render(){let{data:e,linkService:t}=this,n=document.createElement(`a`);n.setAttribute(`data-element-id`,e.id);let r=!1;return e.url?(t.addLinkAttributes(n,e.url,e.newWindow),r=!0):e.action?(this._bindNamedAction(n,e.action,e.overlaidText),r=!0):e.attachment?(this.#t(n,e.attachmentId,e.attachment,e.overlaidText,e.attachmentDest),r=!0):e.setOCGState?(this.#n(n,e.setOCGState,e.overlaidText),r=!0):e.dest?(this._bindLink(n,e.dest,e.overlaidText),r=!0):(e.actions&&(e.actions.has(`Action`)||e.actions.has(`Mouse Up`)||e.actions.has(`Mouse Down`))&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(n,e),r=!0),e.resetForm?(this._bindResetFormAction(n,e.resetForm),r=!0):this.isTooltipOnly&&!r&&(this._bindLink(n,``),r=!0)),this.container.classList.add(`linkAnnotation`),r&&(this.contentElement=n,this.container.append(n)),this.container}#e(){this.container.setAttribute(`data-internal-link`,``)}_bindLink(e,t,n=``){e.href=this.linkService.getDestinationHash(t),e.onclick=()=>(t&&this.linkService.goToDestination(t),!1),(t||t===``)&&this.#e(),n&&(e.title=n)}_bindNamedAction(e,t,n=``){e.href=this.linkService.getAnchorUrl(``),e.onclick=()=>(this.linkService.executeNamedAction(t),!1),n&&(e.title=n),this.#e()}#t(e,t,n,r=``,i=null){e.href=this.linkService.getAnchorUrl(``),n.description?e.title=n.description:r&&(e.title=r);let a=async()=>{let e=await this.linkService.getAttachmentContent(t);e&&this.downloadManager?.openOrDownloadData(e,n.filename,i)};e.onclick=()=>(a(),!1),this.#e()}#n(e,t,n=``){e.href=this.linkService.getAnchorUrl(``),e.onclick=()=>(this.linkService.executeSetOCGState(t),!1),n&&(e.title=n),this.#e()}_bindJSAction(e,{actions:t,id:n,overlaidText:r}){e.href=this.linkService.getAnchorUrl(``);let i=new Map([[`Action`,`onclick`],[`Mouse Up`,`onmouseup`],[`Mouse Down`,`onmousedown`]]);for(let r of t.keys()){let t=i.get(r);t&&(e[t]=()=>(this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:n,name:r}}),!1))}r&&(e.title=r),e.onclick||=()=>!1,this.#e()}_bindResetFormAction(e,t){let n=e.onclick;if(n||(e.href=this.linkService.getAnchorUrl(``)),this.#e(),!this._fieldObjects){T('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),n||(e.onclick=()=>!1);return}e.onclick=()=>{n?.();let{fields:e,refs:r,include:i}=t,a=[];if(e.length!==0||r.length!==0){let t=new Set(r);for(let n of e){let e=this._fieldObjects.get(n)||[];for(let{id:n}of e)t.add(n)}for(let e of this._fieldObjects.values())for(let n of e)t.has(n.id)===i&&a.push(n)}else for(let e of this._fieldObjects.values())a.push(...e);let o=this.annotationStorage,s=[];for(let e of a){let{id:t}=e;switch(s.push(t),e.type){case`text`:{let n=e.defaultValue||``;o.setValue(t,{value:n});break}case`checkbox`:case`radiobutton`:{let n=e.defaultValue===e.exportValues;o.setValue(t,{value:n});break}case`combobox`:case`listbox`:{let n=e.defaultValue||``;o.setValue(t,{value:n});break}default:continue}let n=document.querySelector(`[data-element-id="${t}"]`);if(n){if(!ni.has(n)){T(`_bindResetFormAction - element not allowed: ${t}`);continue}n.dispatchEvent(new Event(`resetform`))}}return this.enableScripting&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:`app`,ids:s,name:`ResetForm`}}),!1}}},si=class extends Q{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add(`textAnnotation`);let e=document.createElement(`img`);return e.src=this.imageResourcesPath+`annotation-`+this.data.name.toLowerCase()+`.svg`,e.setAttribute(`data-l10n-id`,`pdfjs-text-annotation-type`),e.setAttribute(`data-l10n-args`,JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(e),this.container}},ci=class extends Q{render(){return this.container}_getKeyModifier(e){return F.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,t,n,r,i){n.includes(`mouse`)?e.addEventListener(n,e=>{this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:this.data.id,name:r,value:i(e),shift:e.shiftKey,modifier:this._getKeyModifier(e)}})}):e.addEventListener(n,e=>{if(n===`blur`){if(!t.focused||!e.relatedTarget)return;t.focused=!1}else if(n===`focus`){if(t.focused)return;t.focused=!0}i&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:this.data.id,name:r,value:i(e)}})})}_setEventListeners(e,t,n,r){let{actions:i}=this.data;for(let[a,o]of n)(o===`Action`||i?.has(o))&&((o===`Focus`||o===`Blur`)&&(t||={focused:!1}),this._setEventListener(e,t,a,o,r),o===`Focus`&&!i?.has(`Blur`)?this._setEventListener(e,t,`blur`,`Blur`,null):o===`Blur`&&!i?.has(`Focus`)&&this._setEventListener(e,t,`focus`,`Focus`,null))}_setTextStyle(e){let t=[`left`,`center`,`right`],{fontColor:n}=this.data.defaultAppearanceData,r=this.data.defaultAppearanceData.fontSize||ti,i=e.style,a,o=e=>Math.round(10*e)/10;if(this.data.multiLine){let e=Math.abs(this.data.rect[3]-this.data.rect[1]-2),t=e/(Math.round(e/(1.35*r))||1);a=Math.min(r,o(t/1.35))}else{let e=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(r,o(e/1.35))}i.fontSize=`calc(${a}px * var(--total-scale-factor))`,i.color=I.makeHexColor(...n),this.data.textAlignment!==null&&!this.data.comb&&(i.textAlign=t[this.data.textAlignment])}_setRequired(e,t){t?e.setAttribute(`required`,!0):e.removeAttribute(`required`),e.setAttribute(`aria-required`,t)}},li=class extends ci{constructor(e){let t=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:t})}setPropertyOnSiblings(e,t,n,r){let i=this.annotationStorage;for(let a of this._getElementsByName(e.name,e.id))a.domElement&&(a.domElement[t]=n),i.setValue(a.id,{[r]:n})}render(){let e=this.annotationStorage,t=this.data.id;this.container.classList.add(`textWidgetAnnotation`);let n=null;if(this.renderForms){let r=e.getValue(t,{value:this.data.fieldValue}),i=r.value||``,a=e.getValue(t,{charLimit:this.data.maxLen}).charLimit;a&&i.length>a&&(i=i.slice(0,a));let o=r.formattedValue||this.data.textContent?.join(` +`)||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,``));let s={userValue:i,formattedValue:o,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(n=document.createElement(`textarea`),n.textContent=o??i,this.data.doNotScroll&&(n.style.overflowY=`hidden`)):(n=document.createElement(`input`),n.type=this.data.password?`password`:`text`,n.setAttribute(`value`,o??i),this.data.doNotScroll&&(n.style.overflowX=`hidden`)),this.data.hasOwnCanvas&&(this.container.classList.add(`hasOwnCanvas`),e.has(t)&&this.container.classList.add(`sandboxModified`)),ni.add(n),this.contentElement=n,n.setAttribute(`data-element-id`,t),n.disabled=this.data.readOnly,n.name=this.data.fieldName,n.tabIndex=0;let{datetimeFormat:c,datetimeType:l,timeStep:u}=this.data,d=!!l&&this.enableScripting;c&&(n.title=c),this._setRequired(n,this.data.required),a&&(n.maxLength=a),n.addEventListener(`input`,r=>{e.setValue(t,{value:r.target.value}),this.setPropertyOnSiblings(n,`value`,r.target.value,`value`),s.formattedValue=null}),n.addEventListener(`resetform`,e=>{let t=this.data.defaultFieldValue??``;n.value=s.userValue=t,s.formattedValue=null});let f=e=>{let{formattedValue:t}=s;t!=null&&(e.target.value=t),e.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){n.addEventListener(`focus`,e=>{if(s.focused)return;let{target:t}=e;if(d&&(t.type=l,u&&(t.step=u)),s.userValue){let e=s.userValue;if(d){if(l===`time`){let n=new Date(e);t.value=[n.getHours(),n.getMinutes(),n.getSeconds()].map(e=>e.toString().padStart(2,`0`)).join(`:`)}else t.value=new Date(e-ri).toISOString().split(l===`date`?`T`:`.`,1)[0]}else t.value=e}s.lastCommittedValue=t.value,s.commitKey=1,this.data.actions?.has(`Focus`)||(s.focused=!0)}),n.addEventListener(`updatefromsandbox`,n=>{this.container.classList.add(`sandboxModified`),this._dispatchEventFromSandbox({value(n){s.userValue=n.detail.value??``,d||e.setValue(t,{value:s.userValue.toString()}),n.target.value=s.userValue},formattedValue(n){let{formattedValue:r}=n.detail;s.formattedValue=r,r!=null&&n.target!==document.activeElement&&(n.target.value=r);let i={formattedValue:r};d&&(i.value=r),e.setValue(t,i)},selRange(e){e.target.setSelectionRange(...e.detail.selRange)},charLimit:n=>{let{charLimit:r}=n.detail,{target:i}=n;if(r===0){i.removeAttribute(`maxLength`);return}i.setAttribute(`maxLength`,r);let a=s.userValue;!a||a.length<=r||(a=a.slice(0,r),i.value=s.userValue=a,e.setValue(t,{value:a}),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:a,willCommit:!0,commitKey:1,selStart:i.selectionStart,selEnd:i.selectionEnd}}))}},n)}),n.addEventListener(`keydown`,e=>{s.commitKey=1;let n=-1;if(e.key===`Escape`?n=0:e.key===`Enter`&&!this.data.multiLine?n=2:e.key===`Tab`&&(s.commitKey=3),n===-1)return;let{value:r}=e.target;s.lastCommittedValue!==r&&(s.lastCommittedValue=r,s.userValue=r,this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:r,willCommit:!0,commitKey:n,selStart:e.target.selectionStart,selEnd:e.target.selectionEnd}}))});let r=f;f=null,n.addEventListener(`blur`,e=>{if(!s.focused||!e.relatedTarget)return;this.data.actions?.has(`Blur`)||(s.focused=!1);let{target:n}=e,{value:i}=n;if(d){if(i&&l===`time`){let e=i.split(`:`).map(e=>parseInt(e,10));i=new Date(2e3,0,1,e[0],e[1],e[2]||0).valueOf(),n.step=``}else i.includes(`T`)||(i=`${i}T00:00`),i=new Date(i).valueOf();n.type=`text`}s.userValue=i,s.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:i,willCommit:!0,commitKey:s.commitKey,selStart:e.target.selectionStart,selEnd:e.target.selectionEnd}}),r(e)}),this.data.actions?.has(`Keystroke`)&&n.addEventListener(`beforeinput`,e=>{s.lastCommittedValue=null;let{data:n,target:r}=e,{value:i,selectionStart:a,selectionEnd:o}=r,c=a,l=o;switch(e.inputType){case`deleteWordBackward`:{let e=/\w/;for(;c>0&&!e.test(i[c-1]);)c--;for(;c>0&&e.test(i[c-1]);)c--;break}case`deleteWordForward`:{let e=i.substring(a).match(/^\W*\w*/);e&&(l+=e[0].length);break}case`deleteContentBackward`:a===o&&--c;break;case`deleteContentForward`:a===o&&(l+=1)}e.preventDefault(),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:i,change:n||``,willCommit:!1,selStart:c,selEnd:l}})}),this._setEventListeners(n,s,[[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.value)}if(f&&n.addEventListener(`blur`,f),this.data.comb){let e=(this.data.rect[2]-this.data.rect[0])/a;n.classList.add(`comb`),n.style.setProperty(`--comb-width`,`calc(${e}px * var(--total-scale-factor))`);let t=this.data.textAlignment;if(t===1||t===2){let e=()=>{let e=a-n.value.length;n.style.setProperty(`--comb-offset`,`${t===1?e>>1:e}`)};e();for(let t of[`input`,`blur`,`resetform`,`updatefromsandbox`])n.addEventListener(t,e)}}}else n=document.createElement(`div`),n.textContent=this.data.fieldValue,n.style.verticalAlign=`middle`,n.style.display=`table-cell`,this.data.hasOwnCanvas&&(n.hidden=!0);return this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}},ui=class extends ci{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}},di=class extends ci{constructor(e){super(e,{isRenderable:e.renderForms})}render(){let e=this.annotationStorage,t=this.data,n=t.id,r=e.getValue(n,{value:t.exportValue===t.fieldValue}).value;typeof r==`string`&&(r=r!==`Off`,e.setValue(n,{value:r})),this.container.classList.add(`buttonWidgetAnnotation`,`checkBox`);let i=document.createElement(`input`);return ni.add(i),i.setAttribute(`data-element-id`,n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type=`checkbox`,i.name=t.fieldName,r&&i.setAttribute(`checked`,!0),i.setAttribute(`exportValue`,t.exportValue),i.tabIndex=0,i.addEventListener(`change`,r=>{let{name:i,checked:a}=r.target;for(let r of this._getElementsByName(i,n)){let n=a&&r.exportValue===t.exportValue;r.domElement&&(r.domElement.checked=n),e.setValue(r.id,{value:n})}e.setValue(n,{value:a})}),i.addEventListener(`resetform`,e=>{let n=t.defaultFieldValue||`Off`;e.target.checked=n===t.exportValue}),this.enableScripting&&this.hasJSActions&&(i.addEventListener(`updatefromsandbox`,t=>{this._dispatchEventFromSandbox({value(t){t.target.checked=t.detail.value!==`Off`,e.setValue(n,{value:t.target.checked})}},t)}),this._setEventListeners(i,null,[[`change`,`Validate`],[`change`,`Action`],[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.checked)),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},fi=class extends ci{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add(`buttonWidgetAnnotation`,`radioButton`);let e=this.annotationStorage,t=this.data,n=t.id,r=e.getValue(n,{value:t.buttonValue!==null&&t.fieldValue===t.buttonValue}).value;if(typeof r==`string`&&(r=r!==t.buttonValue,e.setValue(n,{value:r})),r)for(let r of this._getElementsByName(t.fieldName,n))e.setValue(r.id,{value:!1});let i=document.createElement(`input`);if(ni.add(i),i.setAttribute(`data-element-id`,n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type=`radio`,i.name=t.fieldName,r&&i.setAttribute(`checked`,!0),i.tabIndex=0,i.addEventListener(`change`,t=>{let{name:r,checked:i}=t.target;for(let t of this._getElementsByName(r,n))e.setValue(t.id,{value:!1});e.setValue(n,{value:i})}),i.addEventListener(`resetform`,e=>{let n=t.defaultFieldValue;e.target.checked=n!=null&&n===t.buttonValue}),this.enableScripting&&this.hasJSActions){let r=t.buttonValue;i.addEventListener(`updatefromsandbox`,t=>{this._dispatchEventFromSandbox({value:t=>{let i=r===t.detail.value;for(let r of this._getElementsByName(t.target.name)){let t=i&&r.id===n;r.domElement&&(r.domElement.checked=t),e.setValue(r.id,{value:t})}}},t)}),this._setEventListeners(i,null,[[`change`,`Validate`],[`change`,`Action`],[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.checked)}return this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},pi=class extends oi{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){let e=super.render();e.classList.add(`buttonWidgetAnnotation`,`pushButton`);let t=e.lastChild;return this.enableScripting&&this.hasJSActions&&t&&(this._setDefaultPropertiesFromJS(t),t.addEventListener(`updatefromsandbox`,e=>{this._dispatchEventFromSandbox({},e)})),e}},mi=class extends ci{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add(`choiceWidgetAnnotation`);let e=this.annotationStorage,t=this.data.id,n=e.getValue(t,{value:this.data.fieldValue}),r=document.createElement(`select`);ni.add(r),r.setAttribute(`data-element-id`,t),r.disabled=this.data.readOnly,this._setRequired(r,this.data.required),r.name=this.data.fieldName,r.tabIndex=0;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(r.size=this.data.options.length,this.data.multiSelect&&(r.multiple=!0)),r.addEventListener(`resetform`,e=>{let t=this.data.defaultFieldValue;for(let e of r.options)e.selected=e.value===t});let a=(e,t)=>{let n=t.replaceAll(` `,`\xA0`);e.textContent=n,n!==t&&e.setAttribute(`display-value`,t)};for(let e of this.data.options){let t=document.createElement(`option`);a(t,e.displayValue),t.value=e.exportValue,n.value.includes(e.exportValue)&&(t.setAttribute(`selected`,!0),i=!1),r.append(t)}let o=null;if(i){let e=document.createElement(`option`);e.value=` `,e.setAttribute(`hidden`,!0),e.setAttribute(`selected`,!0),r.prepend(e),o=()=>{e.remove(),r.removeEventListener(`input`,o),o=null},r.addEventListener(`input`,o)}let s=e=>{let t=e?`value`:`textContent`,{options:n,multiple:i}=r;return i?Array.prototype.filter.call(n,e=>e.selected).map(e=>e[t]):n.selectedIndex===-1?null:n[n.selectedIndex][t]},c=s(!1),l=e=>{let t=e.target.options;return Array.prototype.map.call(t,e=>({displayValue:e.getAttribute(`display-value`)||e.textContent,exportValue:e.value}))};return this.enableScripting&&this.hasJSActions?(r.addEventListener(`updatefromsandbox`,n=>{this._dispatchEventFromSandbox({value(n){o?.();let i=n.detail.value,a=new Set(Array.isArray(i)?i:[i]);for(let e of r.options)e.selected=a.has(e.value);e.setValue(t,{value:s(!0)}),c=s(!1)},multipleSelection(e){r.multiple=!0},remove(n){let i=r.options,a=n.detail.remove;i[a].selected=!1,r.remove(a),i.length>0&&Array.prototype.findIndex.call(i,e=>e.selected)===-1&&(i[0].selected=!0),e.setValue(t,{value:s(!0),items:l(n)}),c=s(!1)},clear(n){for(;r.length!==0;)r.remove(0);e.setValue(t,{value:null,items:[]}),c=s(!1)},insert(n){let{index:i,displayValue:o,exportValue:u}=n.detail.insert,d=r.children[i],f=document.createElement(`option`);a(f,o),f.value=u,d?d.before(f):r.append(f),e.setValue(t,{value:s(!0),items:l(n)}),c=s(!1)},items(n){let{items:i}=n.detail;for(;r.length!==0;)r.remove(0);for(let e of i){let{displayValue:t,exportValue:n}=e,i=document.createElement(`option`);a(i,t),i.value=n,r.append(i)}r.options.length>0&&(r.options[0].selected=!0),e.setValue(t,{value:s(!0),items:l(n)}),c=s(!1)},indices(n){let r=new Set(n.detail.indices);for(let e of n.target.options)e.selected=r.has(e.index);e.setValue(t,{value:s(!0)}),c=s(!1)},editable(e){e.target.disabled=!e.detail.editable}},n)}),r.addEventListener(`input`,n=>{let r=s(!0),i=s(!1);e.setValue(t,{value:r}),n.preventDefault(),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:c,change:i,changeEx:r,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(r,null,[[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`],[`input`,`Action`],[`input`,`Validate`]],e=>e.target.value)):r.addEventListener(`input`,function(n){e.setValue(t,{value:s(!0)})}),this.data.combo&&this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}},hi=class extends Q{constructor(e){let{data:t,elements:n,parent:r}=e,i=!!r._commentManager;if(super(e,{isRenderable:!i&&Q._hasPopupData(t)}),this.elements=n,i&&Q._hasPopupData(t)){let e=this.popup=this.#e();for(let t of n)t.popup=e}else this.popup=null}#e(){return new gi({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){let{container:e}=this;e.classList.add(`popupAnnotation`),e.role=`comment`;let t=this.popup=this.#e(),n=[];for(let e of this.elements)e.popup=t,e.container.ariaHasPopup=`dialog`,n.push(e.data.id),e.addHighlightArea();return this.container.setAttribute(`aria-controls`,n.map(e=>`${c}${e}`).join(`,`)),this.container}},gi=class{#e=null;#t=this.#P.bind(this);#n=this.#R.bind(this);#r=this.#L.bind(this);#i=this.#I.bind(this);#a=null;#o=null;#s=null;#c=null;#l=null;#u=null;#d=null;#f=!1;#p=null;#m=null;#h=null;#g=null;#_=null;#v=null;#y=null;#b=null;#x=null;#S=null;#C=!1;#w=null;#T=null;constructor({container:e,color:t,elements:n,titleObj:r,modificationDate:i,contentsObj:a,richText:o,parent:s,rect:c,parentRect:l,open:u,commentManager:d=null}){this.#o=e,this.#x=r,this.#s=a,this.#b=o,this.#u=s,this.#a=t,this.#y=c,this.#d=l,this.#l=n,this.#e=d,this.#w=n[0],this.#c=je.toDateObject(i),this.trigger=n.flatMap(e=>e.getElementsToTriggerPopup()),d||(this.#E(),this.#o.hidden=!0,u&&this.#I())}#E(){if(this.#m)return;this.#m=new AbortController;let{signal:e}=this.#m;for(let t of this.trigger)t.addEventListener(`click`,this.#i,{signal:e}),t.addEventListener(`pointerenter`,this.#r,{signal:e}),t.addEventListener(`pointerleave`,this.#n,{signal:e}),t.classList.add(`popupTriggerArea`);for(let t of this.#l)t.container?.addEventListener(`keydown`,this.#t,{signal:e})}#D(){let e=this.#l.find(e=>e.hasCommentButton);e&&(this.#_=e._normalizePoint(e.commentButtonPosition))}renderCommentButton(){if(this.#g){this.#g.parentNode||this.#w.container.after(this.#g);return}if(this.#_||this.#D(),!this.#_)return;let{signal:e}=this.#m=new AbortController,t=this.#w.hasOwnCommentButton,n=()=>{this.#e.toggleCommentPopup(this,!0,void 0,!t)},r=()=>{this.#e.toggleCommentPopup(this,!1,!0,!t)},i=()=>{this.#e.toggleCommentPopup(this,!1,!1)};if(t){this.#g=this.#w.container;for(let t of this.trigger)t.ariaHasPopup=`dialog`,t.ariaControls=`commentPopup`,t.addEventListener(`keydown`,this.#t,{signal:e}),t.addEventListener(`click`,n,{signal:e}),t.addEventListener(`pointerenter`,r,{signal:e}),t.addEventListener(`pointerleave`,i,{signal:e}),t.classList.add(`popupTriggerArea`)}else{let t=this.#g=document.createElement(`button`);t.className=`annotationCommentButton`;let a=this.#w.container;t.style.zIndex=parseInt(a.style.zIndex,10)+1,t.tabIndex=0,t.ariaHasPopup=`dialog`,t.ariaControls=`commentPopup`,t.setAttribute(`data-l10n-id`,`pdfjs-show-comment-button`),this.#k(),this.#O(),t.addEventListener(`keydown`,this.#t,{signal:e}),t.addEventListener(`click`,n,{signal:e}),t.addEventListener(`pointerenter`,r,{signal:e}),t.addEventListener(`pointerleave`,i,{signal:e}),a.after(t)}}#O(){if(this.#w.extraPopupElement&&!this.#w.editor)return;this.#g||this.renderCommentButton();let[e,t]=this.#_,{style:n}=this.#g;n.left=`calc(${e}%)`,n.top=`calc(${t}% - var(--comment-button-dim))`}#k(){this.#w.extraPopupElement||(this.#g||this.renderCommentButton(),this.#g.style.backgroundColor=this.commentButtonColor||``)}get commentButtonColor(){let{color:e,opacity:t}=this.#w.commentData;return e?this.#u._commentManager.makeCommentColor(e,t):null}focusCommentButton(){setTimeout(()=>{this.#g?.focus()},0)}getData(){let{richText:e,color:t,opacity:n,creationDate:r,modificationDate:i}=this.#w.commentData;return{contentsObj:{str:this.comment},richText:e,color:t,opacity:n,creationDate:r,modificationDate:i}}get elementBeforePopup(){return this.#g}get comment(){return this.#T||=this.#w.commentText,this.#T}set comment(e){e!==this.comment&&(this.#w.commentText=this.#T=e)}focus(){this.#w.container?.focus()}get parentBoundingClientRect(){return this.#w.layer.getBoundingClientRect()}setCommentButtonStates({selected:e,hasPopup:t}){this.#g&&(this.#g.classList.toggle(`selected`,e),this.#g.ariaExpanded=t)}setSelectedCommentButton(e){this.#g.classList.toggle(`selected`,e)}get commentPopupPosition(){if(this.#v)return this.#v;let{x:e,y:t,height:n}=this.#g.getBoundingClientRect(),{x:r,y:i,width:a,height:o}=this.#w.layer.getBoundingClientRect();return[(e-r)/a,(t+n-i)/o]}set commentPopupPosition(e){this.#v=e}hasDefaultPopupPosition(){return this.#v===null}get commentButtonPosition(){return this.#_}get commentButtonWidth(){return this.#g.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(e){let[t,n]=this.#v||this.commentButtonPosition.map(e=>e/100),r=this.parentBoundingClientRect,{x:i,y:a,width:o,height:s}=r;this.#e.showDialog(null,this,i+t*o,a+n*s,{...e,parentDimensions:r})}render(){if(this.#p)return;let e=this.#p=document.createElement(`div`);if(e.className=`popup`,this.#a){let t=e.style.outlineColor=I.makeHexColor(...this.#a);e.style.backgroundColor=`color-mix(in srgb, ${t} 30%, white)`}let t=document.createElement(`span`);if(t.className=`header`,this.#x?.str){let e=document.createElement(`span`);e.className=`title`,t.append(e),{dir:e.dir,str:e.textContent}=this.#x}if(e.append(t),this.#c){let e=document.createElement(`time`);e.className=`popupDate`,e.setAttribute(`data-l10n-id`,`pdfjs-annotation-date-time-string`),e.setAttribute(`data-l10n-args`,JSON.stringify({dateObj:this.#c.valueOf()})),e.dateTime=this.#c.toISOString(),t.append(e)}qe({html:this.#A||this.#s.str,dir:this.#s?.dir,className:`popupContent`},e),this.#o.append(e)}get#A(){let e=this.#b,t=this.#s;return e?.str&&(!t?.str||t.str===e.str)&&this.#b.html||null}get#j(){return this.#A?.attributes?.style?.fontSize||0}get#M(){return this.#A?.attributes?.style?.color||null}#N(e){let t=[],n={str:e,html:{name:`div`,attributes:{dir:`auto`},children:[{name:`p`,children:t}]}},r={style:{color:this.#M,fontSize:this.#j?`calc(${this.#j}px * var(--total-scale-factor))`:``}};for(let n of e.split(` +`))t.push({name:`span`,value:n,attributes:r});return n}#P(e){e.altKey||e.shiftKey||e.ctrlKey||e.metaKey||(e.key===`Enter`||e.key===`Escape`&&this.#f)&&this.#I()}updateEdited({rect:e,popup:t,deleted:n}){if(this.#e){n?(this.remove(),this.#T=null):t&&(t.deleted?this.remove():(this.#k(),this.#T=t.text)),e&&(this.#_=null,this.#D(),this.#O());return}if(n||t?.deleted){this.remove();return}this.#E(),this.#S||={contentsObj:this.#s,richText:this.#b},e&&(this.#h=null),t&&t.text&&(this.#b=this.#N(t.text),this.#c=je.toDateObject(t.date),this.#s=null),this.#p?.remove(),this.#p=null}resetEdited(){this.#S&&({contentsObj:this.#s,richText:this.#b}=this.#S,this.#S=null,this.#p?.remove(),this.#p=null,this.#h=null)}remove(){if(this.#m?.abort(),this.#m=null,this.#p?.remove(),this.#p=null,this.#C=!1,this.#f=!1,this.#g?.remove(),this.#g=null,this.trigger)for(let e of this.trigger)e.classList.remove(`popupTriggerArea`)}#F(){if(this.#h!==null)return;let{page:{view:e},viewport:{rawDims:{pageWidth:t,pageHeight:n,pageX:r,pageY:i}}}=this.#u,a=!!this.#d,o=a?this.#d:this.#y;for(let e of this.#l)if(!o||I.intersect(e.data.rect,o)!==null){o=e.data.rect,a=!0;break}let s=I.normalizeRect([o[0],e[3]-o[1]+e[1],o[2],e[3]-o[3]+e[1]]),c=a?o[2]-o[0]+5:0,l=s[0]+c,u=s[1];this.#h=[100*(l-r)/t,100*(u-i)/n];let{style:d}=this.#o;d.left=`${this.#h[0]}%`,d.top=`${this.#h[1]}%`}#I(){if(this.#e){this.#e.toggleCommentPopup(this,!1);return}this.#f=!this.#f,this.#f?(this.#L(),this.#o.addEventListener(`click`,this.#i),this.#o.addEventListener(`keydown`,this.#t)):(this.#R(),this.#o.removeEventListener(`click`,this.#i),this.#o.removeEventListener(`keydown`,this.#t))}#L(){this.#p||this.render(),this.isVisible?this.#f&&this.#o.classList.add(`focused`):(this.#F(),this.#o.hidden=!1,this.#o.style.zIndex=parseInt(this.#o.style.zIndex,10)+1e3)}#R(){this.#o.classList.remove(`focused`),!(this.#f||!this.isVisible)&&(this.#o.hidden=!0,this.#o.style.zIndex=parseInt(this.#o.style.zIndex,10)-1e3)}forceHide(){this.#C=this.isVisible,this.#C&&(this.#o.hidden=!0)}maybeShow(){this.#e||(this.#E(),this.#C&&(this.#p||this.#L(),this.#C=!1,this.#o.hidden=!1))}get isVisible(){return!this.#e&&this.#o.hidden===!1}},_i=class extends Q{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=u.FREETEXT}render(){if(this.container.classList.add(`freeTextAnnotation`),this.textContent){let e=this.contentElement=document.createElement(`div`);e.classList.add(`annotationTextContent`),e.setAttribute(`role`,`comment`);for(let t of this.textContent){let n=document.createElement(`span`);n.textContent=t,e.append(n)}this.container.append(e)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}},vi=class extends Q{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`lineAnnotation`);let{data:e,width:t,height:n}=this,r=this.svgFactory.create(t,n,!0),i=this.#e=this.svgFactory.createElement(`svg:line`);return i.setAttribute(`x1`,e.rect[2]-e.lineCoordinates[0]),i.setAttribute(`y1`,e.rect[3]-e.lineCoordinates[1]),i.setAttribute(`x2`,e.rect[2]-e.lineCoordinates[2]),i.setAttribute(`y2`,e.rect[3]-e.lineCoordinates[3]),i.setAttribute(`stroke-width`,e.borderStyle.width||1),i.setAttribute(`stroke`,`transparent`),i.setAttribute(`fill`,`transparent`),r.append(i),this.container.append(r),!e.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},yi=class extends Q{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`squareAnnotation`);let{data:e,width:t,height:n}=this,r=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,a=this.#e=this.svgFactory.createElement(`svg:rect`);return a.setAttribute(`x`,i/2),a.setAttribute(`y`,i/2),a.setAttribute(`width`,t-i),a.setAttribute(`height`,n-i),a.setAttribute(`stroke-width`,i||1),a.setAttribute(`stroke`,`transparent`),a.setAttribute(`fill`,`transparent`),r.append(a),this.container.append(r),!e.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},bi=class extends Q{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`circleAnnotation`);let{data:e,width:t,height:n}=this,r=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,a=this.#e=this.svgFactory.createElement(`svg:ellipse`);return a.setAttribute(`cx`,t/2),a.setAttribute(`cy`,n/2),a.setAttribute(`rx`,t/2-i/2),a.setAttribute(`ry`,n/2-i/2),a.setAttribute(`stroke-width`,i||1),a.setAttribute(`stroke`,`transparent`),a.setAttribute(`fill`,`transparent`),r.append(a),this.container.append(r),!e.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},xi=class extends Q{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName=`polylineAnnotation`,this.svgElementName=`svg:polyline`}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,vertices:t,borderStyle:n,popupRef:r},width:i,height:a}=this;if(!t)return this.container;let o=this.svgFactory.create(i,a,!0),s=[];for(let n=0,r=t.length;n=0&&i.setAttribute(`stroke-width`,t||1),n)for(let e=0,t=this.#t.length;e{e.key===`Enter`&&(r?e.metaKey:e.ctrlKey)&&this.#t()}),!t.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):n.classList.add(`popupTriggerArea`),e.append(n),e}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}async#t(){let{fileId:e,filename:t,content:n}=this,r=await this.linkService.getAttachmentContent(e)||n;r&&this.downloadManager?.openOrDownloadData(r,t)}},ji=class extends Q{#e=new AbortController;#t=null;#n=null;constructor(e){super(e,{isRenderable:!!e.data.richMedia})}render(){this.container.classList.add(`mediaAnnotation`);let{filename:e}=this.data.richMedia,t=document.createElement(`button`);return t.className=`mediaPlayButton`,t.type=`button`,t.title=t.ariaLabel=e,t.addEventListener(`click`,()=>this.#r(t),{signal:this.#e.signal}),this.container.append(t),this.container}async#r(e){let{fileId:t,filename:n,contentType:r}=this.data.richMedia;e.disabled=!0;let i;try{i=await this.linkService.getAttachmentContent(t)}catch{return}finally{e.disabled=!1}if(!i||!e.isConnected)return;let{signal:a}=this.#e,o=URL.createObjectURL(new Blob([i],{type:r}));this.#t=o;let s=r.startsWith(`audio/`),c=document.createElement(s?`audio`:`video`);if(this.#n=c,c.className=`mediaContent`,this._setBackgroundColor(c),c.src=o,c.title=n,c.controls=!0,c.autoplay=!0,c.tabIndex=0,s){let e=!1,t=!1,n=()=>{c.controls=e||t};this.container.addEventListener(`pointerenter`,()=>{e=!0,n()},{signal:a}),this.container.addEventListener(`pointerleave`,()=>{e=!1,n()},{signal:a}),this.container.addEventListener(`focusin`,()=>{t=!0,n()},{signal:a}),this.container.addEventListener(`focusout`,()=>{t=!1,n()},{signal:a})}c.addEventListener(`emptied`,()=>this.#i(o),{once:!0,signal:a}),e.replaceWith(c),c.play().catch(()=>{})}#i(e=this.#t){e&&e===this.#t&&(URL.revokeObjectURL(e),this.#t=null)}destroy(){this.#e.abort(),this.#n&&=(this.#n.pause(),this.#n.removeAttribute(`src`),this.#n.load(),null),this.#i()}},Mi=class e{#e=null;#t=null;#n=null;#r=new Map;#i=null;#a=null;#o=[];#s=!1;zIndex=0;constructor({div:e,accessibilityManager:t,annotationCanvasMap:n,annotationEditorUIManager:r,page:i,viewport:a,structTreeLayer:o,commentManager:s,linkService:c,annotationStorage:l}){this.div=e,this.#e=t,this.#t=n,this.#i=o||null,this.#a=c||null,this.#n=l||new gt,this.page=i,this.viewport=a,this._annotationEditorUIManager=r,this._commentManager=s||null}hasEditableAnnotations(){return this.#r.size>0}async render(e){let{annotations:t,optionalContentConfig:n}=e,r=this.div;Fe(r,this.viewport);let i=new Map,a=[],o={data:null,layer:r,linkService:this.#a,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||``,renderForms:e.renderForms!==!1,svgFactory:new ei,annotationStorage:this.#n,enableComment:e.enableComment===!0,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(let e of t){if(e.noHTML)continue;let t=e.annotationType===h.POPUP;if(t){let t=i.get(e.id);if(!t)continue;if(!this._commentManager){a.push(e);continue}o.elements=t}else if(e.rect[2]===e.rect[0]||e.rect[3]===e.rect[1])continue;o.data=e;let r=ii.create(o);if(!r.isRenderable)continue;t||(this.#o.push(r),e.popupRef&&i.getOrInsertComputed(e.popupRef,pe).push(r));let s=r.render();e.hidden&&(s.style.visibility=`hidden`),r.updateOC(n),r._isEditable&&(this.#r.set(r.data.id,r),this._annotationEditorUIManager?.renderAnnotationElement(r))}await this.#c();for(let e of a){let t=o.elements=i.get(e.id);o.data=e;let n=ii.create(o);if(!n.isRenderable)continue;let r=n.render();n.contentElement.id=`${c}${e.id}`,e.hidden&&(r.style.visibility=`hidden`),t.at(-1).container.after(r)}this.#l()}async#c(){if(this.#o.length===0)return;this.div.replaceChildren();let e=[];if(!this.#s){this.#s=!0;for(let{contentElement:t,data:{hidden:n,id:r,oc:i}}of this.#o){let a=t.id=`${c}${r}`,o=t.localName===`a`&&!n&&!i;e.push(this.#i?.getAriaAttributes(a,{enableLinkOwnership:o}).then(e=>{if(e)for(let[n,r]of e)t.setAttribute(n,r)}))}}this.#o.sort(({data:{rect:[e,t,n,r]}},{data:{rect:[i,a,o,s]}})=>{if(e===n&&t===r)return 1;if(i===o&&a===s)return-1;let c=r,l=t,u=(t+r)/2,d=s,f=a,p=(a+s)/2;return u>=d&&p<=l?-1:p>=c&&u<=f?1:(e+n)/2-(i+o)/2});let t=document.createDocumentFragment();for(let e of this.#o)t.append(e.container),this._commentManager?(e.extraPopupElement?.popup||e.popup)?.renderCommentButton():e.extraPopupElement&&t.append(e.extraPopupElement.render());if(this.div.append(t),await Promise.all(e),this.#e){let e=await this.#i?.getAnnotationIds();for(let{contentElement:t}of this.#o)e?.has(t.id)||this.#e.addPointerInTextLayer(t,!1)}}async addLinkAnnotations(t){let n={data:null,layer:this.div,linkService:this.#a,svgFactory:new ei,parent:this};for(let r of t){r.borderStyle||=e._defaultBorderStyle,n.data=r;let t=ii.create(n);t.isRenderable&&(t.render(),t.contentElement.id=`${c}${r.id}`,this.#o.push(t))}await this.#c()}update({viewport:e,optionalContentConfig:t}){let n=this.div;this.viewport=e,Fe(n,{rotation:e.rotation});for(let e of this.#o)e.updateOC(t);this.#l(),n.hidden=!1}destroy(){for(let e of this.#o)e.destroy?.(),this.#e?.removePointerInTextLayer(e.contentElement);this.#o.length=0,this.#r.clear(),this.div.replaceChildren()}#l(){if(!this.#t)return;let e=this.div;for(let[t,n]of this.#t){let r=e.querySelector(`[data-annotation-id="${t}"]`);if(!r)continue;if(Array.isArray(n))for(let e of n)e.className=`annotationContent`,e.ariaHidden=!0;else n.className=`annotationContent`,n.ariaHidden=!0;let i=[];for(let e of r.children)e.nodeName===`CANVAS`&&i.push(e);for(let e of i)e.remove();let a=Array.isArray(n)?n[0]:n,{firstChild:o}=r;if(o?o.classList.contains(`annotationContent`)?o.after(a):o.before(a):r.append(a),Array.isArray(n)){let e=a;for(let t=1,r=n.length;tt.data.id===e);if(t<0)return;let[n]=this.#o.splice(t,1);this.#e?.removePointerInTextLayer(n.contentElement)}updateFakeAnnotations(e){if(e.length!==0){for(let t of e)t.updateFakeAnnotationElement(this);this.#c()}}togglePointerEvents(e=!1){this.div.classList.toggle(`disabled`,!e)}static get _defaultBorderStyle(){return M(this,`_defaultBorderStyle`,Object.freeze({width:1,rawWidth:1,style:g.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}},Ni=/\r\n?|\n/g,Pi=class e extends U{#e=``;#t=`${this.id}-editor`;#n=null;#r;_colorPicker=null;static _freeTextDefaultContent=``;static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.isEmpty(),r=it.TRANSLATE_SMALL,i=it.TRANSLATE_BIG;return M(this,`_keyboardManager`,new nt([[[`ctrl+s`,`mac+meta+s`,`ctrl+p`,`mac+meta+p`],t.commitOrRemove,{bubbles:!0}],[[`ctrl+Enter`,`mac+meta+Enter`],t.commitOrRemove],[[`Escape`],t.commitOrRemove],[[`ArrowLeft`],t._translateEmpty,{args:[-r,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t._translateEmpty,{args:[-i,0],checker:n}],[[`ArrowRight`],t._translateEmpty,{args:[r,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t._translateEmpty,{args:[i,0],checker:n}],[[`ArrowUp`],t._translateEmpty,{args:[0,-r],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t._translateEmpty,{args:[0,-i],checker:n}],[[`ArrowDown`],t._translateEmpty,{args:[0,r],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t._translateEmpty,{args:[0,i],checker:n}]]))}static _type=`freetext`;static _editorType=u.FREETEXT;constructor(t){super({...t,name:`freeTextEditor`}),this.color=t.color||e._defaultColor||U._defaultLineColor,this.#r=t.fontSize||e._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert(U._l10nAlert.freetext),this.canAddComment=!1}static initialize(e,t){U.initialize(e,t);let n=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(n.getPropertyValue(`--freetext-padding`))}static updateDefaultParams(t,n){switch(t){case d.FREETEXT_SIZE:e._defaultFontSize=n;break;case d.FREETEXT_COLOR:e._defaultColor=n}}updateParams(e,t){switch(e){case d.FREETEXT_SIZE:this.#i(t);break;case d.FREETEXT_COLOR:this.#a(t)}}static get defaultPropertiesToUpdate(){return[[d.FREETEXT_SIZE,e._defaultFontSize],[d.FREETEXT_COLOR,e._defaultColor||U._defaultLineColor]]}get propertiesToUpdate(){return[[d.FREETEXT_SIZE,this.#r],[d.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new Yr(this),[[`colorPicker`,this._colorPicker]]}get colorType(){return d.FREETEXT_COLOR}#i(e){let t=e=>{this.editorDiv.style.fontSize=`calc(${e}px * var(--total-scale-factor))`,this.translate(0,-(e-this.#r)*this.parentScale),this.#r=e,this.#s()},n=this.#r;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#a(e){let t=e=>{this.color=e,this.onUpdatedColor()},n=this.color;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(e,t){this._uiManager.translateSelectedEditors(e,t,!0)}getInitialTranslation(){let t=this.parentScale;return[-e._internalPadding*t,-(e._internalPadding+this.#r)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove(`enabled`),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute(`aria-activedescendant`),this.#n=new AbortController;let e=this._uiManager.combinedSignal(this.#n);return this.editorDiv.addEventListener(`keydown`,this.editorDivKeydown.bind(this),{signal:e}),this.editorDiv.addEventListener(`focus`,this.editorDivFocus.bind(this),{signal:e}),this.editorDiv.addEventListener(`blur`,this.editorDivBlur.bind(this),{signal:e}),this.editorDiv.addEventListener(`input`,this.editorDivInput.bind(this),{signal:e}),this.editorDiv.addEventListener(`paste`,this.editorDivPaste.bind(this),{signal:e}),!0}disableEditMode(){return super.disableEditMode()?(this.overlayDiv.classList.add(`enabled`),this.editorDiv.contentEditable=!1,this.div.setAttribute(`aria-activedescendant`,this.#t),this._isDraggable=!0,this.#n?.abort(),this.#n=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add(`freetextEditing`),!0):!1}focusin(e){this._focusEventsAllowed&&(super.focusin(e),e.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(e){this.width||(this.enableEditMode(),e&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===``}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add(`freetextEditing`)),super.remove()}#o(){let t=[];this.editorDiv.normalize();let n=null;for(let r of this.editorDiv.childNodes)(n?.nodeType!==Node.TEXT_NODE||r.nodeName!==`BR`)&&(t.push(e.#c(r)),n=r);return t.join(` +`)}#s(){let[e,t]=this.parentDimensions,n;if(this.isAttachedToDOM)n=this.div.getBoundingClientRect();else{let{currentLayer:e,div:t}=this,r=t.style.display,i=t.classList.contains(`hidden`);t.classList.remove(`hidden`),t.style.display=`hidden`,e.div.append(this.div),n=t.getBoundingClientRect(),t.remove(),t.style.display=r,t.classList.toggle(`hidden`,i)}this.rotation%180==this.parentRotation%180?(this.width=n.width/e,this.height=n.height/t):(this.width=n.height/e,this.height=n.width/t),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let e=this.#e,t=this.#e=this.#o().trimEnd();if(e===t)return;let n=e=>{if(this.#e=e,!e){this.remove();return}this.#l(),this._uiManager.rebuild(this),this.#s()};this.addCommands({cmd:()=>{n(t)},undo:()=>{n(e)},mustExec:!1}),this.#s()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(e){e.target===this.div&&e.key===`Enter`&&(this.enterInEditMode(),e.preventDefault())}editorDivKeydown(t){e._keyboardManager.exec(this,t)}editorDivFocus(e){this.isEditing=!0}editorDivBlur(e){this.isEditing=!1}editorDivInput(e){this.parent.div.classList.toggle(`freetextEditing`,this.isEmpty())}disableEditing(){this.editorDiv.setAttribute(`role`,`comment`),this.editorDiv.removeAttribute(`aria-multiline`)}enableEditing(){this.editorDiv.setAttribute(`role`,`textbox`),this.editorDiv.setAttribute(`aria-multiline`,!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let e,t;(this._isCopy||this.annotationElementId)&&(e=this.x,t=this.y),super.render(),this.editorDiv=document.createElement(`div`),this.editorDiv.className=`internal`,this.editorDiv.setAttribute(`id`,this.#t),this.editorDiv.setAttribute(`data-l10n-id`,`pdfjs-free-text2`),this.editorDiv.setAttribute(`data-l10n-attrs`,`default-content`),this.enableEditing(),this.editorDiv.contentEditable=!0;let{style:n}=this.editorDiv;if(n.fontSize=`calc(${this.#r}px * var(--total-scale-factor))`,n.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement(`div`),this.overlayDiv.classList.add(`overlay`,`enabled`),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){let[n,r]=this.parentDimensions;if(this.annotationElementId){let{position:i}=this._initialData,[a,o]=this.getInitialTranslation();[a,o]=this.pageTranslationToScreen(a,o);let[s,c]=this.pageDimensions,[l,u]=this.pageTranslation,d,f;switch(this.rotation){case 0:d=e+(i[0]-l)/s,f=t+this.height-(i[1]-u)/c;break;case 90:d=e+(i[0]-l)/s,f=t-(i[1]-u)/c,[a,o]=[o,-a];break;case 180:d=e-this.width+(i[0]-l)/s,f=t-(i[1]-u)/c,[a,o]=[-a,-o];break;case 270:d=e+(i[0]-l-this.height*c)/s,f=t+(i[1]-u-this.width*s)/c,[a,o]=[-o,a]}this.setAt(d*n,f*r,a,o)}else this._moveAfterPaste(e,t);this.#l(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#c(e){return(e.nodeType===Node.TEXT_NODE?e.nodeValue:e.innerText).replaceAll(Ni,``)}editorDivPaste(t){let n=t.clipboardData||window.clipboardData,{types:r}=n;if(r.length===1&&r[0]===`text/plain`)return;t.preventDefault();let i=e.#d(n.getData(`text`)||``).replaceAll(Ni,` +`);if(!i)return;let a=window.getSelection();if(!a.rangeCount)return;this.editorDiv.normalize(),a.deleteFromDocument();let o=a.getRangeAt(0);if(!i.includes(` +`)){o.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),a.collapseToStart();return}let{startContainer:s,startOffset:c}=o,l=[],u=[];if(s.nodeType===Node.TEXT_NODE){let t=s.parentElement;if(u.push(s.nodeValue.slice(c).replaceAll(Ni,``)),t!==this.editorDiv){let n=l;for(let r of this.editorDiv.childNodes){if(r===t){n=u;continue}n.push(e.#c(r))}}l.push(s.nodeValue.slice(0,c).replaceAll(Ni,``))}else if(s===this.editorDiv){let t=l,n=0;for(let r of this.editorDiv.childNodes)n++===c&&(t=u),t.push(e.#c(r))}this.#e=`${l.join(` +`)}${i}${u.join(` +`)}`,this.#l();let d=new Range,f=Math.sumPrecise(l.map(e=>e.length));for(let{firstChild:e}of this.editorDiv.childNodes)if(e.nodeType===Node.TEXT_NODE){let t=e.nodeValue.length;if(f<=t){d.setStart(e,f),d.setEnd(e,f);break}f-=t}a.removeAllRanges(),a.addRange(d)}#l(){if(this.editorDiv.replaceChildren(),this.#e)for(let e of this.#e.split(` +`)){let t=document.createElement(`div`);t.append(e?document.createTextNode(e):document.createElement(`br`)),this.editorDiv.append(t)}}#u(){return this.#e.replaceAll(`\xA0`,` `)}static#d(e){return e.replaceAll(` `,`\xA0`)}get contentDiv(){return this.editorDiv}getPDFRect(){let t=e._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,n,r){let i=null;if(t instanceof _i){let{data:{defaultAppearanceData:{fontSize:e,fontColor:n},rect:r,rotation:a,id:o,popupRef:s,richText:c,contentsObj:l,creationDate:d,modificationDate:f},textContent:p,textPosition:m,parent:{page:{pageNumber:h}}}=t;if(!p?.length)return null;i=t={annotationType:u.FREETEXT,color:Array.from(n),fontSize:e,value:p.join(` +`),position:m,pageIndex:h-1,rect:r.slice(0),rotation:a,annotationElementId:o,id:o,deleted:!1,popupRef:s,comment:l?.str||null,richText:c,creationDate:d,modificationDate:f}}let a=await super.deserialize(t,n,r);return a.#r=t.fontSize,a.color=I.makeHexColor(...t.color),a.#e=e.#d(t.value),a._initialData=i,t.comment&&a.setCommentData(t),a}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let t=U._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),n=Object.assign(super.serialize(e),{color:t,fontSize:this.#r,value:this.#u()});return this.addComment(n),e?(n.isCopy=!0,n):this.annotationElementId&&!this.#f(n)?null:(n.id=this.annotationElementId,n)}#f(e){let{value:t,fontSize:n,color:r,pageIndex:i}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||e.value!==t||e.fontSize!==n||e.color.some((e,t)=>e!==r[t])||e.pageIndex!==i}renderAnnotationElement(e){let t=super.renderAnnotationElement(e);if(!t)return null;let{style:n}=t;n.fontSize=`calc(${this.#r}px * var(--total-scale-factor))`,n.color=this.color,t.replaceChildren();for(let e of this.#e.split(` +`)){let n=document.createElement(`div`);n.append(e?document.createTextNode(e):document.createElement(`br`)),t.append(n)}return e.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#e}}),t}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}},Fi=class{#e=Object.create(null);updateProperty(e,t){this[e]=t,this.updateSVGProperty(e,t)}updateProperties(e){if(e)for(let[t,n]of Object.entries(e))t.startsWith(`_`)||this.updateProperty(t,n)}updateSVGProperty(e,t){this.#e[e]=t}toSVGProperties(){let e=this.#e;return this.#e=Object.create(null),{root:e}}reset(){this.#e=Object.create(null)}updateAll(e=this){this.updateProperties(e)}clone(){E(`Not implemented`)}},Ii=class e extends U{#e=null;#t;_clipPathId=null;_colorPicker=null;_drawId=null;_drawOutlines=null;_focusDrawId=null;static _currentDrawId=-1;static _currentParent=null;static#n=null;static#r=null;static#i=null;static#a=null;static _INNER_MARGIN=3;constructor(e){super(e),this.#t=e.mustBeCommitted||!1,this._addOutlines(e)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(e){e.drawOutlines&&(this.#o(e),this.#m())}#o({drawOutlines:e,drawId:t,drawingOptions:n,clipPathId:r}){this._drawOutlines=e,this._drawingOptions||=n,this.annotationElementId||this._uiManager.a11yAlert(U._l10nAlert[this.editorType]),t>=0?(this._drawId=t,this._clipPathId=r??null,this.parent.drawLayer.finalizeDraw(t,e.defaultProperties),this.#c(this.parent)):this._drawId=this.#s(e,this.parent),this.#_(e.box)}#s(t,n){let{id:r,clipPathId:i}=n.drawLayer.draw(e._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,this.constructor._hasClipPath);return this.constructor._hasClipPath&&(this._clipPathId=i),this.#c(n),r}#c(e){let t=this._drawOutlines.getFocusSVGProperties(this.#f);t&&(this._focusDrawId=e.drawLayer.drawOutline(t,this._drawOutlines.focusMustRemoveSelfIntersections))}#l(e=this.#f){this._focusDrawId!==null&&this.parent?.drawLayer.updateProperties(this._focusDrawId,this._drawOutlines.getFocusSVGProperties(e))}#u(e){this._focusDrawId!==null&&this.parent?.drawLayer.updateProperties(this._focusDrawId,{rootClass:e})}#d(){let{parent:e,_drawId:t,_focusDrawId:n,_isVisible:r}=this;if(!e||t===null)return;let i={hidden:!r};e.drawLayer.updateProperties(t,{rootClass:i}),n!==null&&e.drawLayer.updateProperties(n,{rootClass:i})}static _mergeSVGProperties(e,t){let n=new Set(Object.keys(e));for(let[r,i]of Object.entries(t))n.has(r)?Object.assign(e[r],i):e[r]=i;return e}static getDefaultDrawingOptions(e){E(`Not implemented`)}static get typesMap(){E(`Not implemented`)}static get isDrawer(){return!0}static get _hasClipPath(){return!1}static get _hasDrawClass(){return!0}static get supportMultipleDrawings(){return!1}get _drawRotation(){return this.rotation}get _opacityName(){return this.constructor.typesMap.get(this.opacityType)}get#f(){return(this.parentRotation-this._drawRotation+360)%360}static updateDefaultParams(t,n){let r=this.typesMap.get(t);r&&this._defaultDrawingOptions.updateProperty(r,n),this._currentParent&&(e.#n.updateProperty(r,n),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(e,t){let n=this.constructor.typesMap.get(e);n&&this._updateProperty(e,n,t)}static get defaultPropertiesToUpdate(){let e=[],t=this._defaultDrawingOptions;for(let[n,r]of this.typesMap)e.push([n,t[r]]);return e}get propertiesToUpdate(){let e=[],{_drawingOptions:t}=this;for(let[n,r]of this.constructor.typesMap)e.push([n,t[r]]);return e}_updateProperty(e,t,n){let r=this._drawingOptions,i=r[t],a=n=>{r.updateProperty(t,n);let i=this._drawOutlines.updateProperty(t,n);i&&this.#_(i),this.parent?.drawLayer.updateProperties(this._drawId,r.toSVGProperties()),e===this.colorType?this.onUpdatedColor():e===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:a.bind(this,n),undo:a.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:e,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(e,t,n=this.colorAndOpacityType){let r=this.constructor.typesMap.get(this.colorType),i=this._opacityName,a=this._drawingOptions,o=a[r],s=a[i],c=(e,t)=>{a.updateProperty(r,e),a.updateProperty(i,t),this._drawOutlines.updateProperty(r,e),this._drawOutlines.updateProperty(i,t),this.parent?.drawLayer.updateProperties(this._drawId,a.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:c.bind(this,e,t),undo:c.bind(this,o,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:n,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this._drawOutlines.getPathResizingSVGProperties(this.#g()),{bbox:this.#v()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this._drawOutlines.getPathResizedSVGProperties(this.#g()),{bbox:this.#v()})),this.#l()}_onTranslating(e,t){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#v()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this._drawOutlines.getPathTranslatedSVGProperties(this.#g(),this.parentDimensions),{bbox:this.#v()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}get _mustBeDisabledOnCommit(){return!0}commit(){super.commit(),this._mustBeDisabledOnCommit&&(this.disableEditMode(),this.disableEditing())}disableEditing(){super.disableEditing(),this.div.classList.toggle(`disabled`,!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle(`disabled`,!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#t&&(this.#t=!1,this.commit(),this.parent.setSelected(this),e&&this.isOnScreen&&this.div.focus())}remove(){this._uiManager.removeShouldRescale(this),this.#p(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#m(),this.#_(this._drawOutlines.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){let t=!1;this.parent&&!e?(this._uiManager.removeShouldRescale(this),this.#p()):e&&(this._uiManager.addShouldRescale(this),this.#m(e),t=!this.parent&&this.div?.classList.contains(`selectedEditor`)),super.setParent(e),this.#d(),t&&this.select()}#p(){if(this._drawId===null||!this.parent)return;let{drawLayer:e}=this.parent;e.remove(this._drawId),this._drawId=null,this._focusDrawId!==null&&(e.remove(this._focusDrawId),this._focusDrawId=null),this._drawingOptions.reset()}#m(e=this.parent){if(this._drawId===null||this.parent!==e){if(this._drawId!==null){let{drawLayer:t}=this.parent;t.updateParent(this._drawId,e.drawLayer),this._focusDrawId!==null&&t.updateParent(this._focusDrawId,e.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#s(this._drawOutlines,e),this._clipPathId&&this.#e&&(this.#e.style.clipPath=this._clipPathId)}}#h([e,t,n,r]){let{parentDimensions:[i,a],_drawRotation:o}=this;switch(o){case 90:return[t,1-e,a/i*n,i/a*r];case 180:return[1-e,1-t,n,r];case 270:return[1-t,e,a/i*n,i/a*r];default:return[e,t,n,r]}}#g(){let{x:e,y:t,width:n,height:r,parentDimensions:[i,a],_drawRotation:o}=this;switch(o){case 90:return[1-t,e,i/a*n,a/i*r];case 180:return[1-e,1-t,n,r];case 270:return[t,1-e,i/a*n,a/i*r];default:return[e,t,n,r]}}#_(e){[this.x,this.y,this.width,this.height]=this.#h(e),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#v(e=this.parentRotation){let{x:t,y:n,width:r,height:i,_drawRotation:a,parentDimensions:[o,s]}=this;switch((a*4+e)/90){case 1:return[1-n-i,t,i,r];case 2:return[1-t-r,1-n-i,r,i];case 3:return[n,1-t-r,i,r];case 4:return[t,n-o/s*r,s/o*i,o/s*r];case 5:return[1-n,t,o/s*r,s/o*i];case 6:return[1-t-s/o*i,1-n,s/o*i,o/s*r];case 7:return[n-o/s*r,1-t-s/o*i,o/s*r,s/o*i];case 8:return[t-r,n-i,r,i];case 9:return[1-n,t-r,i,r];case 10:return[1-t,1-n,r,i];case 11:return[n-i,1-t,i,r];case 12:return[t-s/o*i,n,s/o*i,o/s*r];case 13:return[1-n-o/s*r,t-s/o*i,o/s*r,s/o*i];case 14:return[1-t,1-n-o/s*r,s/o*i,o/s*r];case 15:return[n,1-t,o/s*r,s/o*i];default:return[t,n,r,i]}}rotate(t=this.parentRotation){if(!this.parent||this._drawId===null)return;let n=(t-this._drawRotation+360)%360;this.parent.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties({bbox:this.#v(t)},this._drawOutlines.updateRotation(n))),this.#l(n)}show(e=this._isVisible){super.show(e),this.#d()}select(){super.select(),this.#u({hovered:!1,selected:!0})}unselect(){super.unselect(),this.#u({selected:!1})}pointerover(){this.isSelected||this.#u({hovered:!0})}pointerleave(){this.isSelected||this.#u({hovered:!1})}onScaleChanging(){if(!this.parent)return;let e=this._drawOutlines.updateParentDimensions(this.parentDimensions,this.parent.scale);e&&this.#_(e)}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let e,t;this._isCopy&&(e=this.x,t=this.y);let n=super.render();this.constructor._hasDrawClass&&n.classList.add(`draw`);let r=this.#e=document.createElement(`div`);return n.append(r),r.setAttribute(`aria-hidden`,`true`),r.className=`internal`,this._clipPathId&&(r.style.clipPath=this._clipPathId),Qe(this,r,[`pointerover`,`pointerleave`]),this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(e,t),n}static createDrawerInstance(e){E(`Not implemented`)}static _getDrawingTarget(e,{target:t}){return t}static _getPointerCoords({offsetX:e,offsetY:t,clientX:n,clientY:r},i=null){if(!i)return[e,t];let a=n-i.clientX,o=r-i.clientY;switch(this._currentParent.viewport.rotation){case 90:[a,o]=[o,-a];break;case 180:[a,o]=[-a,-o];break;case 270:[a,o]=[-o,a]}return[i.offsetX+a,i.offsetY+o]}static _addDrawingListeners(e,t){}static _endDrawingSession(e=!1){return this._currentParent.endDrawingSession(e)}static startDrawing(t,n,r,i){let{pointerId:a,pointerType:o}=i;if(H.isInitializedAndDifferentPointerType(o))return;let s=this._getDrawingTarget(t,i),[c,l]=this._getPointerCoords(i),{viewport:{rotation:u}}=t,{x:d,y:f,width:p,height:m}=s.getBoundingClientRect(),h=e.#r=new AbortController,g=t.combinedSignal(h);if(H.setPointer(o,a),window.addEventListener(`pointerup`,e=>{H.isSamePointerIdOrRemove(e.pointerId)&&this._endDraw(e)},{signal:g}),window.addEventListener(`pointercancel`,e=>{H.isSamePointerIdOrRemove(e.pointerId)&&this._endDrawingSession()},{signal:g}),window.addEventListener(`pointerdown`,t=>{H.isSamePointerType(t.pointerType)&&(H.initializeAndAddPointerId(t.pointerId),e.#n.isCancellable()&&(e.#n.removeLastElement(),e.#n.isEmpty()?this._endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:g}),window.addEventListener(`contextmenu`,R,{signal:g}),s.addEventListener(`pointermove`,this._drawMove.bind(this),{signal:g}),s.addEventListener(`touchmove`,e=>{H.isSameTimeStamp(e.timeStamp)&&z(e)},{signal:g}),this._addDrawingListeners(s,g),t.toggleDrawing(),n._editorUndoBar?.hide(),e.#n){t.drawLayer.updateProperties(this._currentDrawId,e.#n.startNew(c,l,p,m,u));return}n.updateUIForDefaultProperties(this),e.#n=this.createDrawerInstance({x:c,y:l,box:[d,f,p,m],rotation:u,parent:t,isLTR:r}),e.#i=this.getDefaultDrawingOptions(),this._currentParent=t;let{id:_,clipPathId:v}=t.drawLayer.draw(this._mergeSVGProperties(e.#i.toSVGProperties(),e.#n.defaultSVGProperties),!0,this._hasClipPath);this._currentDrawId=_,e.#a=this._hasClipPath?v:null}static _drawMove(t){if(H.isSameTimeStamp(t.timeStamp),!e.#n||!H.isSamePointerId(t.pointerId))return;if(H.isUsingMultiplePointers()){this._endDraw(t);return}let n,r=t.getCoalescedEvents?.();if(r?.length){let i=[];for(let e of r)i.push(...this._getPointerCoords(e,t));n=e.#n.addPoints(i)}else n=e.#n.add(...this._getPointerCoords(t));this._currentParent.drawLayer.updateProperties(this._currentDrawId,n),H.setTimeStamp(t.timeStamp),z(t)}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,e.#n=null,e.#i=null,e.#a=null,H.clearTimeStamp()),e.#r&&(e.#r.abort(),e.#r=null,H.clearPointerIds())}static _endDraw(t){let n=this._currentParent;if(n){if(n.toggleDrawing(!0),this._cleanup(!1),n.drawLayer.updateProperties(this._currentDrawId,t?.target===n.div?e.#n.end(...this._getPointerCoords(t)):e.#n.end()),this.supportMultipleDrawings){let t=e.#n,r=this._currentDrawId,i=t.getLastElement();n.addCommands({cmd:()=>{n.drawLayer.updateProperties(r,t.setLastElement(i))},undo:()=>{n.drawLayer.updateProperties(r,t.removeLastElement())},mustExec:!1,type:d.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){let n=this._currentParent;if(!n)return null;if(n.toggleDrawing(!0),n.cleanUndoStack(d.DRAW_STEP),!e.#n.isEmpty()){let{pageDimensions:[r,i],scale:a}=n,o=n.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,clipPathId:e.#a,drawOutlines:e.#n.getOutlines(r*a,i*a,a,this._INNER_MARGIN),drawingOptions:e.#i,mustBeCommitted:!t});return this._cleanup(!0),o}return n.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(e){}static deserializeDraw(e,t,n,r,i,a,o){E(`Not implemented`)}static async deserialize(e,t,n){let{rawDims:{pageWidth:r,pageHeight:i,pageX:a,pageY:o}}=t.viewport,s=this.deserializeDraw(a,o,r,i,this._INNER_MARGIN,e,n),c=await super.deserialize(e,t,n);return c.createDrawingOptions(e),c.#o({drawOutlines:s}),c.#m(),c.onScaleChanging(),c.rotate(),c}serializeDraw(e){let[t,n]=this.pageTranslation,[r,i]=this.pageDimensions;return this._drawOutlines.serialize([t,n,r,i],e)}renderAnnotationElement(e){return e.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}},$=class{static PRECISION=1e-4;focusOutline=null;toSVGPath(){E("Abstract method `toSVGPath` must be implemented.")}get box(){E("Abstract getter `box` must be implemented.")}serialize(e,t){E("Abstract method `serialize` must be implemented.")}get defaultSVGProperties(){E("Abstract getter `defaultSVGProperties` must be implemented.")}get defaultProperties(){return this.defaultSVGProperties}getFocusSVGProperties(e){return null}get focusMustRemoveSelfIntersections(){return!1}updateProperty(e,t){return null}updateParentDimensions(e,t){return null}serializeQuadPoints(e,t){return null}updateRotation(e){return{}}getPathResizingSVGProperties(e){return{}}getPathResizedSVGProperties(e){return{}}getPathTranslatedSVGProperties(e,t){return{}}static _rotateBox([e,t,n,r],i){switch(i){case 90:return[1-t-r,e,r,n];case 180:return[1-e-n,1-t-r,n,r];case 270:return[t,1-e-n,r,n]}return[e,t,n,r]}static _rescale(e,t,n,r,i,a){a||=new Float32Array(e.length);for(let o=0,s=e.length;o=6;e-=6)isNaN(t[e])?n.push(`L${t[e+4]} ${t[e+5]}`):n.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);return this.#v(n),n.join(` `)}#_(){let[e,t,n,r]=this.#e,[i,a,o,s]=this.#g();return`M${(this.#a[2]-e)/n} ${(this.#a[3]-t)/r} L${(this.#a[4]-e)/n} ${(this.#a[5]-t)/r} L${i} ${a} L${o} ${s} L${(this.#a[16]-e)/n} ${(this.#a[17]-t)/r} L${(this.#a[14]-e)/n} ${(this.#a[15]-t)/r} Z`}#v(e){let t=this.#t;e.push(`L${t[4]} ${t[5]} Z`)}#y(e){let[t,n,r,i]=this.#e,a=this.#a.subarray(4,6),o=this.#a.subarray(16,18),[s,c,l,u]=this.#g();e.push(`L${(a[0]-t)/r} ${(a[1]-n)/i} L${s} ${c} L${l} ${u} L${(o[0]-t)/r} ${(o[1]-n)/i}`)}newFreeDrawOutline(e,t,n,r,i,a){return new Ri(e,t,n,r,i,a)}getOutlines(){let e=this.#i,t=this.#t,n=this.#a,[r,i,a,o]=this.#e,s=new Float32Array((this.#f?.length??0)+2);for(let e=0,t=s.length-2;e=6;e-=6)for(let n=0;n<6;n+=2){if(isNaN(t[e+n])){c[l]=c[l+1]=NaN,l+=2;continue}c[l]=t[e+n],c[l+1]=t[e+n+1],l+=2}return this.#x(c,l),this.newFreeDrawOutline(c,s,this.#e,this.#u,this.#n,this.#r)}#b(e){let t=this.#a,[n,r,i,a]=this.#e,[o,s,c,l]=this.#g(),u=new Float32Array(36);return u.set([NaN,NaN,NaN,NaN,(t[2]-n)/i,(t[3]-r)/a,NaN,NaN,NaN,NaN,(t[4]-n)/i,(t[5]-r)/a,NaN,NaN,NaN,NaN,o,s,NaN,NaN,NaN,NaN,c,l,NaN,NaN,NaN,NaN,(t[16]-n)/i,(t[17]-r)/a,NaN,NaN,NaN,NaN,(t[14]-n)/i,(t[15]-r)/a],0),this.newFreeDrawOutline(u,e,this.#e,this.#u,this.#n,this.#r)}#x(e,t){let n=this.#t;return e.set([NaN,NaN,NaN,NaN,n[4],n[5]],t),t+=6}#S(e,t){let n=this.#a.subarray(4,6),r=this.#a.subarray(16,18),[i,a,o,s]=this.#e,[c,l,u,d]=this.#g();return e.set([NaN,NaN,NaN,NaN,(n[0]-i)/o,(n[1]-a)/s,NaN,NaN,NaN,NaN,c,l,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(r[0]-i)/o,(r[1]-a)/s],t),t+=24}},Ri=class extends ${#e;#t=new Float32Array(4);#n;#r;#i;#a;#o;constructor(e,t,n,r,i,a){super(),this.#o=e,this.#i=t,this.#e=n,this.#a=r,this.#n=i,this.#r=a,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#s(a);let[o,s,c,l]=this.#t;for(let t=0,n=e.length;tp?(o=f,s=p):s===p&&(o=u(o,f)),ld[1]?(o=d[0],s=d[1]):s===d[1]&&(o=u(o,d[0])),le[0]-t[0]||e[1]-t[1]||e[2]-t[2]);let e=[];for(let t of this.#r)t[3]?(e.push(...this.#l(t)),this.#s(t)):(this.#c(t),e.push(...this.#l(t)));return this.#a(e)}#a(e){let t=[],n=new Set;for(let n of e){let[e,r,i]=n;t.push([e,r,n],[e,i,n])}t.sort((e,t)=>e[1]-t[1]||e[0]-t[0]);for(let e=0,r=t.length;e0;){let e=n.values().next().value,[t,a,o,s,c]=e;n.delete(e);let l=t,u=a;for(i=[t,o],r.push(i);;){let e;if(n.has(s))e=s;else if(n.has(c))e=c;else break;n.delete(e),[t,a,o,s,c]=e,l!==t&&(i.push(l,u,t,u===a?a:o),l=t),u=u===a?o:a}i.push(l,u)}return new Hi(r,this.#e,this.#t,this.#n)}#o(e){let t=this.#i,n=0,r=t.length-1;for(;n<=r;){let i=n+r>>1,a=t[i][0];if(a===e)return i;a=0;r--){let[n,i]=this.#i[r];if(n!==e)break;if(n===e&&i===t){this.#i.splice(r,1);return}}}#l(e){let[t,n,r]=e,i=[[t,n,r]],a=this.#o(r);for(let e=0;e=n){if(s>r)i[e][1]=r;else{if(a===1)return[];i.splice(e,1),e--,a--}continue}i[e][2]=n,s>r&&i.push([t,r,s])}}}return i}},Hi=class extends ${#e;#t=null;#n;constructor(e,t,n,r){super(),this.#n=e,this.#e=t,this.firstPoint=n,this.lastPoint=r}static build(e,t){let n=new Vi(e,.001).getOutlines();return n.#t=e,n.focusOutline=new Vi(e,.0025,.001,t).getOutlines(),n}get isFree(){return!1}get defaultSVGProperties(){return zi(this)}getFocusSVGProperties(e){return Bi(this,e)}updateRotation(e){return{root:{"data-main-rotation":e}}}serializeQuadPoints([e,t],[n,r]){let i=this.#t,a=new Float32Array(i.length*8),o=0;for(let{x:s,y:c,width:l,height:u}of i){let i=s*n+e,d=(1-c)*r+t;a[o]=a[o+4]=i,a[o+1]=a[o+3]=d,a[o+2]=a[o+6]=i+l*n,a[o+5]=a[o+7]=d-u*r,o+=8}return a}toSVGPath(){let e=[];for(let t of this.#n){let[n,r]=t;e.push(`M${n} ${r}`);for(let i=2;ie.classList.remove(`free`),{once:!0}),window.addEventListener(`blur`,()=>this._endDraw(null),{signal:t}),window.addEventListener(`pointerdown`,z,{capture:!0,passive:!1,signal:t})}static _endDrawingSession(e=!1){return this.endDrawing(e)}createDrawingOptions({color:t,opacity:n,thickness:r}){let{_defaultDrawingOptions:i,_DEFAULT_OPACITY:a}=e;this._drawingOptions=e.getDefaultDrawingOptions({fill:I.makeHexColor(...t),"fill-opacity":n||a,thickness:r||i.thickness})}static deserializeDraw(e,t,n,r,i,a,o){let{quadPoints:s}=a;if(s){let i=[];for(let a=0,o=s.length;ae!==t[n])}renderAnnotationElement(e){return this.deleted?(e.hide(),null):(e.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}},Ji=class{#e=new Float64Array(6);#t=new Float64Array(2);#n;#r;#i;#a;#o;#s=``;#c=0;#l=new Yi;#u;#d;constructor(e,t,n,r,i,a){this.#u=n,this.#d=r,this.#i=i,this.#a=a,[e,t]=this.#f(e,t);let o=this.#n=[NaN,NaN,NaN,NaN,e,t];this.#o=[e,t],this.#r=[{line:o,points:this.#o}],this.#e.set(o,0),this.#t.set([e,t],0)}updateProperty(e,t){e===`stroke-width`&&(this.#a=t)}#f(e,t){return $._normalizePoint(e,t,this.#u,this.#d,this.#i)}isEmpty(){return!this.#r?.length}isCancellable(){return this.#o.length<=10}add(e,t){return this.#p(e,t)&&this.toSVGPath(),{path:{d:this.#m()}}}addPoints(e){let t=!1;for(let n=0,r=e.length;ne??NaN),u,d,f,p),points:m(o[e].map(e=>e??NaN),u,d,f,p)});let h=new this.prototype.constructor;return h.build(l,n,r,1,s,c,i),h}#l(e=this.#c){let t=this.#n+e/2*this.#o;return this.#s%180==0?[t/this.#i,t/this.#a]:[t/this.#a,t/this.#i]}#u(){let[e,t,n,r]=this.#e,[i,a]=this.#l(0);return[e+i,t+a,n-2*i,r-2*a]}#d(){let e=this.#e=r.slice();for(let{line:t}of this.#r){if(t.length<=12){for(let n=4,r=t.length;ne!==t[n])||e.thickness!==n||e.opacity!==r||e.pageIndex!==i}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let{points:t,rect:n}=this.serializeDraw(!1);return e.updateEdited({rect:n,thickness:this._drawingOptions[`stroke-width`],points:t,popup:this.comment}),null}},Qi=class extends Yi{toSVGPath(){let e=super.toSVGPath();return e.endsWith(`Z`)||(e+=`Z`),e}},$i=8,ea=3,ta=class{static#e={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#t(e,t,n,r){return n-=e,r-=t,n===0?r>0?0:4:n===1?r+6:2-r}static#n=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#r(e,t,n,r,i,a,o){let s=this.#t(n,r,i,a);for(let i=0;i<8;i++){let a=(-i+s-o+16)%8,c=this.#n[2*a],l=this.#n[2*a+1];if(e[(n+c)*t+(r+l)]!==0)return a}return-1}static#i(e,t,n,r,i,a,o){let s=this.#t(n,r,i,a);for(let i=0;i<8;i++){let a=(i+s+o+16)%8,c=this.#n[2*a],l=this.#n[2*a+1];if(e[(n+c)*t+(r+l)]!==0)return a}return-1}static#a(e,t,n,r){let i=e.length,a=new Int32Array(i);for(let t=0;t=1&&a[r+1]===0)o+=1,u+=1,i>1&&(s=i);else{i!==1&&(s=Math.abs(i));continue}let d=[n,e],f=u===n+1,p={isHole:f,points:d,id:o,parent:0};c.push(p);let m;for(let e of c)if(e.id===s){m=e;break}p.parent=m?m.isHole?f?m.parent:s:f?s:m.parent:f?s:0;let h=this.#r(a,t,e,n,l,u,0);if(h===-1){a[r]=-o,a[r]!==1&&(s=Math.abs(a[r]));continue}let g=this.#n[2*h],_=this.#n[2*h+1],v=e+g,y=n+_;l=v,u=y;let b=e,x=n;for(;;){let i=this.#i(a,t,b,x,l,u,1);g=this.#n[2*i],_=this.#n[2*i+1];let c=b+g,f=x+_;d.push(f,c);let p=b*t+x;if(a[p+1]===0?a[p]=-o:a[p]===1&&(a[p]=o),c===e&&f===n&&b===v&&x===y){a[r]!==1&&(s=Math.abs(a[r]));break}l=b,u=x,b=c,x=f}}}return c}static#o(e,t,n,r){if(n-t<=4){for(let i=t;ib&&(x=r,b=t)}b>(c*y)**2?(this.#o(e,t,x+2,r),this.#o(e,x,n,r)):r.push(i,a)}static#s(e){let t=[],n=e.length;return this.#o(e,0,n,t),t.push(e[n-2],e[n-1]),t.length<=4?null:t}static#c(e,t,n,r,i,a){let o=new Float32Array(a**2),s=-2*r**2,c=a>>1;for(let e=0;e=n))for(let n=0;n=t)continue;let p=e[f*t+r],h=o[s*a+n]*l[Math.abs(p-u)];d+=p*h,m+=h}}let h=f[s]=Math.round(d/m);p[h]++}return[f,p]}static#l(e){let t=new Uint32Array(256);for(let n of e)t[n]++;return t}static#u(e){let t=e.length,n=new Uint8ClampedArray(t>>2),r=-1/0,i=1/0;for(let t=0,a=n.length;te!==0),a=i,o=i;for(t=i;t<256;t++){let i=e[t];i>n&&(t-a>r&&(r=t-a,o=t-1),n=i,a=t)}for(t=o-1;t>=0&&!(e[t]>e[t+1]);t--);return t}static#f(e){let t=e,{width:n,height:r}=e,{maxDim:i}=this.#e,a=n,o=r;if(n>i||r>i){let s=n,c=r,l=Math.log2(Math.max(n,r)/i),u=Math.floor(l);l=l===u?u-1:u;for(let n=0;n=-128&&o<=127?Int8Array:a>=-32768&&o<=32767?Int16Array:Int32Array;let l=e.length,u=$i+ea*l,d=new Uint32Array(u),f=0;d[f++]=u*Uint32Array.BYTES_PER_ELEMENT+(s-2*l)*c.BYTES_PER_ELEMENT,d[f++]=0,d[f++]=r,d[f++]=i,d[f++]=+!t,d[f++]=Math.max(0,Math.floor(n??0)),d[f++]=l,d[f++]=c.BYTES_PER_ELEMENT;for(let t of e)d[f++]=t.length-2,d[f++]=t[0],d[f++]=t[1];let p=new CompressionStream(`deflate-raw`),m=p.writable.getWriter();await m.ready,m.write(d);let h=c.prototype.constructor;for(let t of e){let e=new h(t.length-2);for(let n=2,r=t.length;n{await i.ready,await i.close()}).catch(()=>{});let a=null,o=0;for await(let e of n)a||=new Uint8Array(new Uint32Array(e.buffer,0,4)[0]),a.set(e,o),o+=e.length;let s=new Uint32Array(a.buffer,0,a.length>>2),c=s[1];if(c!==0)throw Error(`Invalid version: ${c}`);let l=s[2],u=s[3],d=s[4]===0,f=s[5],p=s[6],m=s[7],h=[],g=($i+ea*p)*Uint32Array.BYTES_PER_ELEMENT,_;switch(m){case Int8Array.BYTES_PER_ELEMENT:_=new Int8Array(a.buffer,g);break;case Int16Array.BYTES_PER_ELEMENT:_=new Int16Array(a.buffer,g);break;case Int32Array.BYTES_PER_ELEMENT:_=new Int32Array(a.buffer,g)}o=0;for(let e=0;e{t?.updateEditSignatureButton(e)}))}getSignaturePreview(){let{newCurves:e,areContours:t,thickness:n,width:r,height:i}=this.#n,a=Math.max(r,i);return{areContours:t,outline:ta.processDrawnLines({lines:{curves:e.map(e=>({points:e})),thickness:n,width:r,height:i},pageWidth:a,pageHeight:a,rotation:0,innerMargin:0,mustSmooth:!1,areContours:t}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[[`editSignature`,this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,n,r,i){let{x:a,y:o}=this,{outline:s}=this.#n=t;this.#e=s instanceof Qi,this.description=r;let c;this.#e?c=e.getDefaultDrawingOptions():(c=e._defaultDrawnSignatureOptions.clone(),c.updateProperties({"stroke-width":s.thickness})),this._addOutlines({drawOutlines:s,drawingOptions:c});let[,l]=this.pageDimensions,u=n/l;u=u>=1?.5:u,this.width*=u/this.height,this.width>=1&&(u*=.9/this.width,this.width=.9),this.height=u,this.setDims(),this.x=a,this.y=o,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(i),this._reportTelemetry({action:`pdfjs.signature.inserted`,data:{hasBeenSaved:!!i,hasDescription:!!r}}),this.div.hidden=!1}getFromImage(t){let{rawDims:{pageWidth:n,pageHeight:r},rotation:i}=this.parent.viewport;return ta.process(t,n,r,i,e._INNER_MARGIN)}getFromText(t,n){let{rawDims:{pageWidth:r,pageHeight:i},rotation:a}=this.parent.viewport;return ta.extractContoursFromText(t,n,r,i,a,e._INNER_MARGIN)}getDrawnSignature(t){let{rawDims:{pageWidth:n,pageHeight:r},rotation:i}=this.parent.viewport;return ta.processDrawnLines({lines:t,pageWidth:n,pageHeight:r,rotation:i,innerMargin:e._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:n}){t?this._drawingOptions=e.getDefaultDrawingOptions():(this._drawingOptions=e._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":n}))}serialize(e=!1){if(this.isEmpty())return null;let{lines:t,points:n}=this.serializeDraw(e),{_drawingOptions:{"stroke-width":r}}=this,i=Object.assign(super.serialize(e),{isSignature:!0,areContours:this.#e,color:[0,0,0],thickness:this.#e?0:r});return this.addComment(i),e?(i.paths={lines:t,points:n},i.uuid=this.#r,i.isCopy=!0):i.lines=t,this.#t&&(i.accessibilityData={type:`Figure`,alt:this.#t}),i}static deserializeDraw(e,t,n,r,i,a){return a.areContours?Qi.deserialize(e,t,n,r,i,a):Yi.deserialize(e,t,n,r,i,a)}static async deserialize(e,t,n){let r=await super.deserialize(e,t,n);return r.#e=e.areContours,r.description=e.accessibilityData?.alt||``,r.#r=e.uuid,r}},aa=class extends U{#e=null;#t=null;#n=null;#r=null;#i=null;#a=``;#o=null;#s=!1;#c=null;#l=!1;#u=!1;static _type=`stamp`;static _editorType=u.STAMP;constructor(e){super({...e,name:`stampEditor`}),this.#r=e.bitmapUrl,this.#i=e.bitmapFile,this.defaultL10nId=`pdfjs-editor-stamp-editor`}static initialize(e,t){U.initialize(e,t)}static isHandlingMimeForPasting(e){return Le.includes(e)}static paste(e,t){t.pasteEditor({mode:u.STAMP},{bitmapFile:e.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:`stamp`,hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(e){let t=e.get(`hasAltText`);return{hasAltText:t.get(!0)??0,hasNoAltText:t.get(!1)??0}}#d(e,t=!1){if(!e){this.remove();return}this.#e=e.bitmap,t||(this.#t=e.id,this.#l=e.isSvg),e.file&&(this.#a=e.file.name),this.#m()}#f(){if(this.#n=null,this._uiManager.enableWaiting(!1),this.#o){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this._reportTelemetry({action:`pdfjs.image.image_added`,data:{alt_text_modal:!1,alt_text_type:`empty`}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(e=null,t=!0){if(this.hasAltTextData())return null;let{mlManager:n}=this._uiManager;if(!n)throw Error(`No ML.`);if(!await n.isEnabledFor(`altText`))throw Error(`ML isn't enabled for alt text.`);let{data:r,width:i,height:a}=e||this.copyCanvas(null,null,!0).imageData,o=await n.guess({name:`altText`,request:{data:r,width:i,height:a,channels:r.length/(i*a)}});if(!o)throw Error(`No response from the AI service.`);if(o.error)throw Error(`Error from the AI service.`);if(o.cancel)return null;if(!o.output)throw Error(`No valid response from the AI service.`);let s=o.output;return await this.setGuessedAltText(s),t&&!this.hasAltTextData()&&(this.altTextData={alt:s,decorative:!1}),s}#p(){if(this.#t){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#t).then(e=>this.#d(e,!0)).finally(()=>this.#f());return}if(this.#r){let e=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromUrl(e).then(e=>this.#d(e)).finally(()=>this.#f());return}if(this.#i){let e=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromFile(e).then(e=>this.#d(e)).finally(()=>this.#f());return}let e=document.createElement(`input`);e.type=`file`,e.accept=Le.join(`,`);let t=this._uiManager._signal;this.#n=new Promise(n=>{e.addEventListener(`change`,async()=>{if(!e.files||e.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);let t=await this._uiManager.imageManager.getFromFile(e.files[0]);this._reportTelemetry({action:`pdfjs.image.image_selected`,data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#d(t)}n()},{signal:t}),e.addEventListener(`cancel`,()=>{this.remove(),n()},{signal:t})}).finally(()=>this.#f()),e.click()}remove(){this.#t&&(this.#e=null,this._uiManager.imageManager.deleteId(this.#t),this.#o?.remove(),this.#o=null,this.#c&&=(clearTimeout(this.#c),null)),super.remove()}rebuild(){if(!this.parent){this.#t&&this.#p();return}super.rebuild(),this.div!==null&&(this.#t&&this.#o===null&&this.#p(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(e){this._isDraggable=!0,e&&this.div.focus()}isEmpty(){return!(this.#n||this.#e||this.#r||this.#i||this.#t||this.#s)}get toolbarButtons(){return[[`altText`,this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let e,t;return this._isCopy&&(e=this.x,t=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#s||(this.#e?this.#m():this.#p()),this._isCopy&&this._moveAfterPaste(e,t),this._uiManager.addShouldRescale(this),this.div}setCanvas(e,t){let{id:n,bitmap:r}=this._uiManager.imageManager.getFromCanvas(e,t);t.remove(),n&&this._uiManager.imageManager.isValidId(n)&&(this.#t=n,r&&(this.#e=r),this.#s=!1,this.#m())}_onResized(){this.onScaleChanging()}onScaleChanging(){this.parent&&(this.#c!==null&&clearTimeout(this.#c),this.#c=setTimeout(()=>{this.#c=null,this.#g()},200))}#m(){let{div:e}=this,{width:t,height:n}=this.#e,[r,i]=this.pageDimensions,a=.75;if(this.width)t=this.width*r,n=this.height*i;else if(t>a*r||n>a*i){let e=Math.min(a*r/t,a*i/n);t*=e,n*=e}this._uiManager.enableWaiting(!1);let o=this.#o=document.createElement(`canvas`);o.setAttribute(`role`,`img`),this.addContainer(o),this.width=t/r,this.height=n/i,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(e.hidden=!1),this.#g(),this.#u||=(this.parent.addUndoableEditor(this),!0),this._reportTelemetry({action:`inserted_image`}),this.#a&&this.div.setAttribute(`aria-description`,this.#a),this.annotationElementId||this._uiManager.a11yAlert(U._l10nAlert.stamp)}copyCanvas(e,t,n=!1){e||=224;let{width:r,height:i}=this.#e,a=new Ie,o=this.#e,s=r,c=i,l=null;if(t){if(r>t||i>t){let e=Math.min(t/r,t/i);s=Math.floor(r*e),c=Math.floor(i*e)}l=document.createElement(`canvas`);let e=l.width=Math.ceil(s*a.sx),n=l.height=Math.ceil(c*a.sy);this.#l||(o=this.#h(e,n));let u=l.getContext(`2d`);u.filter=this._uiManager.hcmFilter;let d=`white`,f=`#cfcfd8`;this._uiManager.hcmFilter===`none`?Re.isDarkMode&&(d=`#8f8f9d`,f=`#42414d`):f=`black`;let p=15*a.sx,m=15*a.sy,h=new OffscreenCanvas(p*2,m*2),g=h.getContext(`2d`);g.fillStyle=d,g.fillRect(0,0,p*2,m*2),g.fillStyle=f,g.fillRect(0,0,p,m),g.fillRect(p,m,p,m),u.fillStyle=u.createPattern(h,`repeat`),u.fillRect(0,0,e,n),u.drawImage(o,0,0,o.width,o.height,0,0,e,n)}let u=null;if(n){let t,n;if(a.symmetric&&o.widthe||i>e){let a=Math.min(e/r,e/i);t=Math.floor(r*a),n=Math.floor(i*a),this.#l||(o=this.#h(t,n))}let s=new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0});s.drawImage(o,0,0,o.width,o.height,0,0,t,n),u={width:t,height:n,data:s.getImageData(0,0,t,n).data}}return{canvas:l,width:s,height:c,imageData:u}}#h(e,t){let{width:n,height:r}=this.#e,i=n,a=r,o=this.#e;for(;i>2*e||a>2*t;){let n=i,r=a;i>2*e&&(i=Math.ceil(i/2)),a>2*t&&(a=Math.ceil(a/2));let s=new OffscreenCanvas(i,a);s.getContext(`2d`).drawImage(o,0,0,n,r,0,0,i,a),o=s.transferToImageBitmap()}return o}#g(){let[e,t]=this.parentDimensions,{width:n,height:r}=this,i=new Ie,a=Math.ceil(n*e*i.sx),o=Math.ceil(r*t*i.sy),s=this.#o;if(!s||s.width===a&&s.height===o)return;s.width=a,s.height=o;let c=this.#l?this.#e:this.#h(a,o),l=s.getContext(`2d`);l.filter=this._uiManager.hcmFilter,l.drawImage(c,0,0,c.width,c.height,0,0,a,o)}#_(e){if(e){if(this.#l){let e=this._uiManager.imageManager.getSvgUrl(this.#t);if(e)return e}let e=document.createElement(`canvas`);return{width:e.width,height:e.height}=this.#e,e.getContext(`2d`).drawImage(this.#e,0,0),e.toDataURL()}if(this.#l){let[e,t]=this.pageDimensions,n=Math.round(this.width*e*Se.PDF_TO_CSS_UNITS),r=Math.round(this.height*t*Se.PDF_TO_CSS_UNITS),i=new OffscreenCanvas(n,r);return i.getContext(`2d`).drawImage(this.#e,0,0,this.#e.width,this.#e.height,0,0,n,r),i.transferToImageBitmap()}return structuredClone(this.#e)}static async deserialize(e,t,n){let r=null,i=!1;if(e instanceof ki){let{data:{rect:a,rotation:o,id:s,structParent:l,popupRef:d,richText:f,contentsObj:p,creationDate:m,modificationDate:h},container:g,parent:{page:{pageNumber:_}},canvas:v}=e,y,b;v?(delete e.canvas,{id:y,bitmap:b}=n.imageManager.getFromCanvas(g.id,v),v.remove()):(i=!0,e._hasNoCanvas=!0);let x=(await t._structTree.getAriaAttributes(`${c}${s}`))?.get(`aria-label`)||``;r=e={annotationType:u.STAMP,bitmapId:y,bitmap:b,pageIndex:_-1,rect:a.slice(0),rotation:o,annotationElementId:s,id:s,deleted:!1,accessibilityData:{decorative:!1,altText:x},isSvg:!1,structParent:l,popupRef:d,richText:f,comment:p?.str||null,creationDate:m,modificationDate:h}}let a=await super.deserialize(e,t,n),{rect:o,bitmap:s,bitmapUrl:l,bitmapId:d,isSvg:f,accessibilityData:p}=e;i?(n.addMissingCanvas(e.id,a),a.#s=!0):d&&n.imageManager.isValidId(d)?(a.#t=d,s&&(a.#e=s)):a.#r=l,a.#l=f;let[m,h]=a.pageDimensions;return a.width=(o[2]-o[0])/m,a.height=(o[3]-o[1])/h,p&&(a.altTextData=p),a._initialData=r,e.comment&&a.setCommentData(e),a.#u=!!r,a}serialize(e=!1,t=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let n=Object.assign(super.serialize(e),{bitmapId:this.#t,isSvg:this.#l});if(this.addComment(n),e)return n.bitmapUrl=this.#_(!0),n.accessibilityData=this.serializeAltText(!0),n.isCopy=!0,n;let{decorative:r,altText:i}=this.serializeAltText(!1);if(!r&&i&&(n.accessibilityData={type:`Figure`,alt:i}),this.annotationElementId){let e=this.#v(n);return e.isSame?null:(e.isSameAltText?delete n.accessibilityData:n.accessibilityData.structParent=this._initialData.structParent??-1,n.id=this.annotationElementId,delete n.bitmapId,n)}if(t===null)return n;t.stamps||=new Map;let a=this.#l?(n.rect[2]-n.rect[0])*(n.rect[3]-n.rect[1]):null;if(!t.stamps.has(this.#t))t.stamps.set(this.#t,{area:a,serialized:n}),n.bitmap=this.#_(!1);else if(this.#l){let e=t.stamps.get(this.#t);a>e.area&&(e.area=a,e.serialized.bitmap.close(),e.serialized.bitmap=this.#_(!1))}return n}#v(e){let{pageIndex:t,accessibilityData:{altText:n}}=this._initialData,r=e.pageIndex===t,i=(e.accessibilityData?.alt||``)===n;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&r&&i,isSameAltText:i}}renderAnnotationElement(e){return this.deleted?(e.hide(),null):(e.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}},oa=class e{#e;#t=!1;#n=null;#r=null;#i=null;#a=new Map;#o=!1;#s=!1;#c=!1;#l=null;#u=null;#d=null;#f=null;#p=null;#m=-1;#h;static _initialized=!1;static#g=new Map([Pi,Zi,aa,qi,ia].map(e=>[e._editorType,e]));constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:i,accessibilityManager:a,annotationLayer:o,drawLayer:s,textLayer:c,viewport:l,l10n:u}){let d=[...e.#g.values()];if(!e._initialized){e._initialized=!0;for(let e of d)e.initialize(u,t)}t.registerEditorTypes(d),this.#h=t,this.pageIndex=n,this.div=r,this.#e=a,this.#n=o,this.viewport=l,this.#d=c,this.drawLayer=s,this._structTree=i,this.#h.addLayer(this)}get isEmpty(){return this.#a.size===0}get isInvisible(){return this.isEmpty&&this.#h.getMode()===u.NONE}updateToolbar(e){this.#h.updateToolbar(e)}updateMode(t=this.#h.getMode()){switch(this.#S(),t){case u.NONE:this.div.classList.toggle(`nonEditing`,!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case u.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case u.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:n}=this.div;if(n.toggle(`nonEditing`,!1),t===u.POPUP)n.toggle(`commentEditing`,!0);else{n.toggle(`commentEditing`,!1);for(let r of e.#g.values())n.toggle(`${r._type}Editing`,t===r._editorType)}this.div.hidden=!1}hasTextLayer(e){return e===this.#d?.div}setEditingState(e){this.#h.setEditingState(e)}addCommands(e){this.#h.addCommands(e)}cleanUndoStack(e){this.#h.cleanUndoStack(e)}toggleDrawing(e=!1){this.div.classList.toggle(`drawing`,!e)}togglePointerEvents(e=!1){this.div.classList.toggle(`disabled`,!e)}toggleAnnotationLayerPointerEvents(e=!1){this.#n?.togglePointerEvents(e)}get#_(){return this.#a.size===0?this.#h.getEditors(this.pageIndex):this.#a.values()}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle(`nonEditing`,!1),this.#p?.abort(),this.#p=null;let e=new Set;for(let t of this.#_)t.enableEditing(),t.show(!0),t.annotationElementId&&(this.#h.removeChangedExistingAnnotation(t),e.add(t.annotationElementId));let t=this.#n;if(t)for(let n of t.getEditableAnnotations()){if(n.hide(),this.#h.isDeletedAnnotationElement(n.data.id)||e.has(n.data.id))continue;let t=await this.deserialize(n);t&&(this.addOrRebuild(t),t.enableEditing())}this.#c=!1,this.#h._eventBus.dispatch(`editorsrendered`,{source:this,pageNumber:this.pageIndex+1})}disable(){if(this.#s=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle(`nonEditing`,!0),this.#d&&!this.#p){this.#p=new AbortController;let e=this.#h.combinedSignal(this.#p);this.#d.div.addEventListener(`pointerdown`,e=>{let{clientX:t,clientY:n,timeStamp:r}=e;if(r-this.#m>500){this.#m=r;return}this.#m=-1;let{classList:i}=this.div;i.toggle(`getElements`,!0);let a=document.elementsFromPoint(t,n);if(i.toggle(`getElements`,!1),!this.div.contains(a[0]))return;let o,s=RegExp(`^${l}[0-9]+$`);for(let e of a)if(s.test(e.id)){o=e.id;break}if(!o)return;let c=this.#a.get(o);c?.annotationElementId===null&&(z(e),c.dblclick(e))},{signal:e,capture:!0})}let t=this.#n,n=[];if(t){let e=new Map,r=new Map;for(let t of this.#_){if(t.disableEditing(),!t.annotationElementId){n.push(t);continue}if(t.serialize()!==null){e.set(t.annotationElementId,t);continue}r.set(t.annotationElementId,t),this.getEditableAnnotation(t.annotationElementId)?.show(),t.remove()}for(let n of t.getEditableAnnotations()){let{id:t}=n.data;if(this.#h.isDeletedAnnotationElement(t)){n.updateEdited({deleted:!0});continue}let i=r.get(t);if(i){i.resetAnnotationElement(n),i.show(!1),n.show();continue}i=e.get(t),i&&(this.#h.addChangedExistingAnnotation(i),i.renderAnnotationElement(n)&&i.show(!1)),n.show()}}this.#S(),this.isEmpty&&(this.div.hidden=!0);let{classList:r}=this.div;for(let t of e.#g.values())r.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),t?.updateFakeAnnotations(n),this.#s=!1}getEditableAnnotation(e){return this.#n?.getEditableAnnotation(e)||null}setActiveEditor(e){this.#h.getActive()!==e&&this.#h.setActiveEditor(e)}enableTextSelection(){if(this.div.tabIndex=-1,this.#d?.div&&!this.#f){this.#f=new AbortController;let e=this.#h.combinedSignal(this.#f);this.#d.div.addEventListener(`pointerdown`,this.#v.bind(this),{signal:e}),this.#d.div.classList.add(`highlighting`)}}disableTextSelection(){this.div.tabIndex=0,this.#d?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#d.div.classList.remove(`highlighting`))}#v(e){this.#h.unselectAll();let{target:t}=e;if(t===this.#d.div||(t.getAttribute(`role`)===`img`||t.classList.contains(`endOfContent`)||t.classList.contains(`textLayerImages`)||t.classList.contains(`textLayerImagePlaceholder`))&&this.#d.div.contains(t)){let{isMac:t}=F.platform;if(e.button!==0||e.ctrlKey&&t)return;this.#h.showAllEditors(`highlight`,!0,!0),qi.startDrawing(this,this.#h,this.#h.direction===`ltr`,e),e.preventDefault()}}enableClick(){if(this.#r)return;this.#r=new AbortController;let e=this.#h.combinedSignal(this.#r);this.div.addEventListener(`pointerdown`,this.pointerdown.bind(this),{signal:e});let t=this.pointerup.bind(this);this.div.addEventListener(`pointerup`,t,{signal:e}),this.div.addEventListener(`pointercancel`,t,{signal:e})}disableClick(){this.#r?.abort(),this.#r=null}attach(e){this.#a.set(e.id,e);let{annotationElementId:t}=e;t&&this.#h.isDeletedAnnotationElement(t)&&this.#h.removeDeletedAnnotationElement(e)}detach(e){this.#a.delete(e.id),this.#e?.removePointerInTextLayer(e.contentDiv),!this.#s&&e.annotationElementId&&this.#h.addDeletedAnnotationElement(e)}remove(e){this.detach(e),this.#h.removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1}changeParent(e){e.parent!==this&&(e.parent&&e.annotationElementId&&(this.#h.addDeletedAnnotationElement(e),U.deleteAnnotationElement(e),e.annotationElementId=null),this.attach(e),e.parent?.detach(e),e.setParent(this),e.div&&e.isAttachedToDOM&&(e.div.remove(),this.div.append(e.div)))}add(e){if(!(e.parent===this&&e.isAttachedToDOM)){if(this.changeParent(e),this.#h.addEditor(e),this.attach(e),!e.isAttachedToDOM){let t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(!this.#c),this.#h.addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}}moveEditorInDOM(e){if(!e.isAttachedToDOM)return;let{activeElement:t}=document;e.div.contains(t)&&!this.#i&&(e._focusEventsAllowed=!1,this.#i=setTimeout(()=>{this.#i=null,e.div.contains(document.activeElement)?e._focusEventsAllowed=!0:(e.div.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this.#h._signal}),t.focus())},0)),e._structTreeParentId=this.#e?.moveElementInDOM(this.div,e.div,e.contentDiv,!0)}addOrRebuild(e){e.needsToBeRebuilt()?(e.parent||=this,e.rebuild(),e.show()):this.add(e)}addUndoableEditor(e){this.addCommands({cmd:()=>e._uiManager.rebuild(e),undo:()=>{e.remove()},mustExec:!1})}getEditorByUID(e){for(let t of this.#a.values())if(t.uid===e)return t;return null}get#y(){return e.#g.get(this.#h.getMode())}combinedSignal(e){return this.#h.combinedSignal(e)}#b(e){let t=this.#y;return t?new t.prototype.constructor(e):null}canCreateNewEmptyEditor(){return this.#y?.canCreateNewEmptyEditor()}async pasteEditor(e,t){this.updateToolbar(e),await this.#h.updateMode(e.mode);let{offsetX:n,offsetY:r}=this.#x(),i=this.#h.getId(),a=this.#b({parent:this,id:i,x:n,y:r,uiManager:this.#h,isCentered:!0,...t});a&&this.add(a)}async deserialize(t){return await e.#g.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#h)||null}createAndAddNewEditor(e,t,n={}){let r=this.#h.getId(),i=this.#b({parent:this,id:r,x:e.offsetX,y:e.offsetY,uiManager:this.#h,isCentered:t,...n});return i&&this.add(i),i}get boundingClientRect(){return this.div.getBoundingClientRect()}#x(){let{x:e,y:t,width:n,height:r}=this.boundingClientRect,i=Math.max(0,e),a=Math.max(0,t),o=Math.min(window.innerWidth,e+n),s=Math.min(window.innerHeight,t+r),c=(i+o)/2-e,l=(a+s)/2-t,[u,d]=this.viewport.rotation%180==0?[c,l]:[l,c];return{offsetX:u,offsetY:d}}addNewEditor(e={}){this.createAndAddNewEditor(this.#x(),!0,e)}setSelected(e){this.#h.setSelected(e)}toggleSelected(e){this.#h.toggleSelected(e)}unselect(e){this.#h.unselect(e)}pointerup(e){let{isMac:t}=F.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div||!this.#o||(this.#o=!1,this.#y?.isDrawer&&this.#y.supportMultipleDrawings))return;if(!this.#t){this.#t=!0;return}let n=this.#h.getMode();if(n===u.STAMP||n===u.POPUP||n===u.SIGNATURE){this.#h.unselectAll();return}this.createAndAddNewEditor(e,!1)}pointerdown(e){if(this.#h.getMode()===u.HIGHLIGHT&&this.enableTextSelection(),this.#o){this.#o=!1;return}let{isMac:t}=F.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div)return;if(this.#o=!0,this.#y?.isDrawer){this.startDrawingSession(e);return}let n=this.#h.getActive();this.#t=!n||n.isEmpty()}startDrawingSession(e){if(this.div.focus({preventScroll:!0}),this.#l){this.#y.startDrawing(this,this.#h,!1,e);return}this.#h.setCurrentDrawingSession(this),this.#l=new AbortController;let t=this.#h.combinedSignal(this.#l);this.div.addEventListener(`blur`,({relatedTarget:e})=>{e&&!this.div.contains(e)&&(this.#u=null,this.commitOrRemove())},{signal:t}),this.#y.startDrawing(this,this.#h,!1,e)}pause(e){if(e){let{activeElement:e}=document;this.div.contains(e)&&(this.#u=e);return}this.#u&&setTimeout(()=>{this.#u?.focus(),this.#u=null},0)}endDrawingSession(e=!1){return this.#l?(this.#h.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#u=null,this.#y.endDrawing(e)):null}findNewParent(e,t,n){let r=this.#h.findParent(t,n);return r===null||r===this?!1:(r.changeParent(e),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#y.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#h.getActive()?.parent===this&&(this.#h.commitOrRemove(),this.#h.setActiveEditor(null)),this.#i&&=(clearTimeout(this.#i),null);for(let e of this.#a.values())this.#e?.removePointerInTextLayer(e.contentDiv),e.setParent(null),e.isAttachedToDOM=!1,e.div.remove();this.div=null,this.#a.clear(),this.#h.removeLayer(this)}#S(){for(let e of this.#a.values())e.isEmpty()&&e.remove()}async render({viewport:e}){this.viewport=e,Fe(this.div,e);for(let e of this.#h.getEditors(this.pageIndex))this.add(e),e.rebuild();await this.#h.findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:e}){this.#h.commitOrRemove(),this.#S();let t=this.viewport.rotation,n=e.rotation;if(this.viewport=e,Fe(this.div,{rotation:n}),t!==n)for(let e of this.#a.values())e.rotate(n)}get pageDimensions(){let{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return this.#h.viewParameters.realScale}};function sa(e,t){return e===t?0:e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function ca(e){return e?e.nodeType===Node.ELEMENT_NODE?e.closest(`.textLayer`):e.parentElement?.closest(`.textLayer`)||null:null}function la(e,t,n,r){if(e===n)return t<=r;let i=e.compareDocumentPosition(n);return i&Node.DOCUMENT_POSITION_FOLLOWING?!0:i&Node.DOCUMENT_POSITION_PRECEDING?!1:null}function ua(e,t,n){if(e.nodeType!==Node.ELEMENT_NODE||!e.classList.contains(`textLayer`)||t!==e.childNodes.length)return{container:e,offset:t};let r=e.lastChild;return r?.nodeType===Node.ELEMENT_NODE&&r.classList.contains(`endOfContent`)&&(r=r.previousSibling),!r||!n.contains(r)?null:r.nodeType===Node.TEXT_NODE?{container:r,offset:r.textContent.length}:{container:r,offset:r.childNodes.length}}var da=class e{#e=null;#t=new Map;#n=null;#r=null;#i=null;#a=null;#o=new Map;static#s=0;static#c=0;static#l=null;static#u=new Set;static#d=!1;static#f=new Set;static#p=new WeakMap;constructor({filterFactory:t=null,pageColors:n=null,pageIndex:r,textLayer:i=null}){if(this.pageIndex=r,this.#r=t,this.#i=n,i){let t=e.#p.get(i);if(t?.selectionDiv&&(t.selectionDiv.remove(),e.#u.delete(t.selectionDiv)),e.#p.set(i,{drawLayer:this}),e.#f.add(i),this.#n=i,this.#a=new MutationObserver(t=>{if(!(!this.#e||!this.#n?.isConnected||!e.#h())){for(let{addedNodes:n}of t)for(let t of n)if(t.nodeType===Node.ELEMENT_NODE&&t.classList.contains(`endOfContent`)){e.#_();return}}}),this.#a.observe(i,{childList:!0}),e.#l===null){e.#l=new AbortController;let{signal:t}=e.#l;document.addEventListener(`selectionchange`,e.#_.bind(e),{signal:t}),document.addEventListener(`pointerdown`,()=>{e.#d=!0},{signal:t}),document.addEventListener(`pointerup`,()=>{e.#d=!1},{signal:t}),window.addEventListener(`blur`,()=>{e.#d=!1},{signal:t})}}}setParent(t){if(!this.#e){this.#e=t,this.#n?.isConnected&&e.#h()&&e.#_();return}if(this.#e!==t){if(this.#t.size>0)for(let e of this.#t.values())e.remove(),t.append(e);this.#e=t}}static#m(e){let t=this.#p.get(e);t?.selectionDiv&&(t.selectionDiv.remove(),this.#u.delete(t.selectionDiv),t.selectionDiv=null,t.path=null)}static#h(){let e=document.getSelection();return!!e&&!e.isCollapsed}static#g(){return this.#f.keys().filter(e=>e.isConnected).toArray().sort(sa)}static#_(){let t=document.getSelection();if(!t||t.isCollapsed){for(let e of this.#u)e.remove();this.#u.clear();return}let n=new WeakMap,r=this.#g(),i=[];for(let e=0,n=t.rangeCount;en.intersectsNode(e));if(p.length===0)continue;let m=!1;if(l||(l=p[0],a=l,o=0,m=!0),u||(u=p.at(-1),s=u,c=u.childNodes.length,m=!0),s.nodeType===Node.ELEMENT_NODE){if(s.classList.contains(`endOfContent`)){let e=s.previousSibling;if(!e)continue;s=e,c=e.nodeType===Node.TEXT_NODE?e.textContent.length:e.childNodes.length}else if(s.classList.contains(`textLayer`)&&s.childNodes.length===c){let e=ua(s,c,u);if(!e)continue;s=e.container,c=e.offset}}if(a.nodeType===Node.ELEMENT_NODE){let e=ua(a,o,l);if(!e)continue;a=e.container,o=e.offset}if(l===u&&!m&&p.includes(l)){i.push([n,l]);continue}for(let e of p){let t=e.firstChild;if(!t)continue;let n=document.createRange();if(e===l?n.setStart(a,o):n.setStartBefore(t),e===u)n.setEnd(s,c);else{let t=e.lastChild;if(!t)continue;if(t.nodeType===Node.ELEMENT_NODE&&t.classList.contains(`endOfContent`)){let e=t.previousSibling;if(!e)continue;n.setEndAfter(e)}else n.setEndAfter(t)}n.collapsed||i.push([n,e])}}let a=new Set(i.map(e=>e[1]));for(let e of this.#f)a.has(e)||this.#m(e);for(let[t,r]of i){let i=e.#p.get(r);if(!i)continue;let a=n.get(r);if(!a){let e=r.getBoundingClientRect();a=(t,n,r,i)=>({x:(t-e.x)/e.width,y:(n-e.y)/e.height,width:r/e.width,height:i/e.height}),n.set(r,a)}let o=[];for(let{x:e,y:n,width:r,height:i}of t.getClientRects())r!==0&&i!==0&&({x:e,y:n,width:r,height:i}=a(e,n,r,i),(r!==1||i!==1)&&o.push(`M${e} ${n} h${r} v${i} h-${r} Z`));if(o.length===0)continue;let s=i.drawLayer,c=i.selectionDiv,l=i.path;if(!c){let t=`clip_selection_${e.#c++}`;c=document.createElement(`div`),c.className=`selection`,c.style.clipPath=`url(#${t})`;let n=s.#r?.createSelectionStyle(s.#i);if(n)for(let[e,t]of Object.entries(n))c.style.setProperty(e,t);let r=e._svgFactory.create(1,1,!0);r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`width`,`100%`),r.setAttribute(`height`,`100%`);let a=e._svgFactory.createElement(`clipPath`);a.setAttribute(`id`,t),a.setAttribute(`clipPathUnits`,`objectBoundingBox`),l=e._svgFactory.createElement(`path`),a.append(l),r.append(a),c.append(r),i.path=l,i.selectionDiv=c}s.#e&&c.parentNode!==s.#e&&(s.#e.append(c),this.#u.add(c)),l.setAttribute(`d`,o.join(` `))}}static get _svgFactory(){return M(this,`_svgFactory`,new ei)}static#v(e,[t,n,r,i]){let{style:a}=e;a.top=`${100*n}%`,a.left=`${100*t}%`,a.width=`${100*r}%`,a.height=`${100*i}%`}#y(){let t=e._svgFactory.create(1,1,!0);return this.#e.append(t),t.setAttribute(`aria-hidden`,`true`),t}#b(t,n){let r=e._svgFactory.createElement(`clipPath`);t.append(r);let i=`clip_${n}`;r.setAttribute(`id`,i),r.setAttribute(`clipPathUnits`,`objectBoundingBox`);let a=e._svgFactory.createElement(`use`);return r.append(a),a.setAttribute(`href`,`#${n}`),a.classList.add(`clip`),i}#x(e,t){for(let[n,r]of Object.entries(t))r===null?e.removeAttribute(n):e.setAttribute(n,r)}draw(t,n=!1,r=!1){let i=e.#s++,a=this.#y(),o=e._svgFactory.createElement(`defs`);a.append(o);let s=e._svgFactory.createElement(`path`);o.append(s);let c=`path_${i}`;s.setAttribute(`id`,c),s.setAttribute(`vector-effect`,`non-scaling-stroke`),n&&this.#o.set(i,s);let l=r?this.#b(o,c):null,u=e._svgFactory.createElement(`use`);return a.append(u),u.setAttribute(`href`,`#${c}`),this.updateProperties(a,t),this.#t.set(i,a),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,n){let r=e.#s++,i=this.#y(),a=e._svgFactory.createElement(`defs`);i.append(a);let o=e._svgFactory.createElement(`path`);a.append(o);let s=`path_${r}`;o.setAttribute(`id`,s),o.setAttribute(`vector-effect`,`non-scaling-stroke`);let c;if(n){let t=e._svgFactory.createElement(`mask`);a.append(t),c=`mask_${r}`,t.setAttribute(`id`,c),t.setAttribute(`maskUnits`,`objectBoundingBox`);let n=e._svgFactory.createElement(`rect`);t.append(n),n.setAttribute(`width`,`1`),n.setAttribute(`height`,`1`),n.setAttribute(`fill`,`white`);let i=e._svgFactory.createElement(`use`);t.append(i),i.setAttribute(`href`,`#${s}`),i.setAttribute(`stroke`,`none`),i.setAttribute(`fill`,`black`),i.setAttribute(`fill-rule`,`nonzero`),i.classList.add(`mask`)}let l=e._svgFactory.createElement(`use`);i.append(l),l.setAttribute(`href`,`#${s}`),c&&l.setAttribute(`mask`,`url(#${c})`);let u=l.cloneNode();return i.append(u),l.classList.add(`mainOutline`),u.classList.add(`secondaryOutline`),this.updateProperties(i,t),this.#t.set(r,i),r}finalizeDraw(e,t){this.#o.delete(e),this.updateProperties(e,t)}updateProperties(t,n){if(!n)return;let{root:r,bbox:i,rootClass:a,path:o}=n,s=typeof t==`number`?this.#t.get(t):t;if(s){if(r&&this.#x(s,r),i&&e.#v(s,i),a){let{classList:e}=s;for(let[t,n]of Object.entries(a))e.toggle(t,n)}if(o){let e=s.firstElementChild.firstElementChild;this.#x(e,o)}}}updateParent(e,t){if(t===this)return;let n=this.#t.get(e);n&&(t.#e.append(n),this.#t.delete(e),t.#t.set(e,n))}remove(e){this.#o.delete(e),this.#e!==null&&(this.#t.get(e).remove(),this.#t.delete(e))}destroy(){this.#e=null;for(let e of this.#t.values())e.remove();this.#t.clear(),this.#o.clear(),this.#a?.disconnect(),this.#a=null,this.#n&&=(e.#p.get(this.#n)?.drawLayer===this&&(e.#m(this.#n),e.#p.delete(this.#n),e.#f.delete(this.#n),e.#f.size===0&&(e.#l?.abort(),e.#l=null,e.#d=!1)),null)}};function fa(e){return`${(e*100).toFixed(2)}%`}var pa=class e{#e=[];#t=new Map;#n=null;#r=0;#i=0;#a=0;static#o=null;constructor(e,t,n,r){this.#r=e,this.#e=t,this.#i=n.rawDims.pageWidth,this.#a=n.rawDims.pageHeight,this.#n=r}render(){let t=document.createElement(`div`);t.className=`textLayerImages`;for(let e=0;e{if(!(t.target instanceof HTMLCanvasElement))return;let n=t.target,r=this.#t.get(n);if(!r)return;let i=e.#o?.deref();if(i===n)return;i&&(i.width=0,i.height=0),e.#o=new WeakRef(n);let{inverseTransform:a,x1:o,y1:s,width:c,height:l}=r,u=this.#n(),d=Math.ceil(o*u.width),f=Math.ceil(s*u.height),p=Math.floor((o+c/this.#i)*u.width),m=Math.floor((s+l/this.#a)*u.height);n.width=p-d,n.height=m-f;let h=n.getContext(`2d`);h.setTransform(...a),h.translate(-d,-f),h.drawImage(u,0,0)}),t}#s([e,t,n,r,i,a]){let o=Math.hypot((i-e)*this.#i,(a-t)*this.#a),s=Math.hypot((n-e)*this.#i,(r-t)*this.#a);if(oObject.keys(e).reduce((t,n)=>{let r=e[n];return r==null?t:t+`${n}:${r};`},``),S=(e,t)=>`_`+t,{min:C,max:w,abs:T,floor:E}=Math,D=(e,t,n)=>C(n,w(t,e)),O=e=>[...e].sort((e,t)=>e-t),k=setTimeout,A=clearTimeout,j=typeof queueMicrotask==`function`?queueMicrotask:e=>{Promise.resolve().then(e)},M=()=>{let e;return[new Promise(t=>{e=t}),e]},N=e=>{let t;return()=>(e&&=(t=e(),void 0),t)},P=e=>e.documentElement,F=e=>e.ownerDocument,I=e=>e.defaultView,L=N(()=>!!/iP(hone|od|ad)/.test(navigator.userAgent)||navigator.platform===`MacIntel`&&navigator.maxTouchPoints>0),R=N(()=>`scrollBehavior`in P(document).style),z=e=>w(e.$getTotalSize(),e.$getViewportSize()),B=({$getRange:e,$findIndex:t,$getItemOffset:n,$getItemSize:r,$setItemSize:i,$isSizeEqual:a,$getTotalSize:o,$getLength:s,$setLength:c,$estimateDefaultSize:l},u=0)=>{let d=!!l,f=!!u,p=1,m=0,h=0,g=0,_=0,v=0,y=0,b=0,x=0,S=null,E=[0,f?w(u-1,0):-1],D=0,O=!1,k=new Set,A=()=>g-h,j=()=>A()+v+_,M=(e,t)=>{let i=n(e)-v;return t?o()-i-r(e):i},N=e=>{e&&(L()&&b!==0||S&&x===1?v+=e:_+=e)};return{$dispose:()=>{k.clear()},$getStateVersion:()=>p,$getRange:(t=200)=>{if(!O||f)return E;let n,r;if(y)[n,r]=E;else{let i=w(0,j()),a=i+m;d||(t=w(0,t),b!==1&&(i-=t),b!==2&&(a+=t)),[n,r]=E=e(w(0,i),w(0,a)),S&&(n=C(n,S[0]),r=w(r,S[1]))}return[w(n,0),C(r,s()-1)]},$findItemIndex:e=>t(e-h),$isUnmeasuredItem:a,$getItemOffset:M,$getItemSize:r,$getItemsLength:s,$getScrollOffset:()=>g,$isScrolling:()=>b!==0,$getViewportSize:()=>m,$getStartSpacerSize:()=>h,$getTotalSize:o,t:()=>(y=_,_=0,[y,x===2]),$subscribe:(e,t)=>{let n=[e,t];return k.add(n),()=>{k.delete(n)}},$update:(n,s)=>{let u,C,w=0;switch(n){case 1:{if(s===g&&x===0)break;let e=y;y=0;let t=s-g,n=T(t);e&&n=-m&&r<=o()&&(w+=1,C=n>m);break}case 2:w=8,b!==0&&(u=!0,w+=1),b=0,x=0,S=null;break;case 3:{let e=s.filter(([e,t])=>!a(e,t));if(!e.length)break;N(e.reduce((e,[t,n])=>{let i;if(x===2)i=!0;else if(S&&x===1)i=tm&&(N(l(t(j()))),d=!1),w=3,C=!0;break}case 4:m!==s&&(m||(O=C=!0),m=s,w=3);break;case 5:s[1]?(N(c(s[0],!0)),x=2,w=1):(c(s[0]),w=1);break;case 6:h=s;break;case 7:x=1;break;case 8:S=e(s,s+m),w=1}w&&(p=1+(2147483647&p),u&&v&&(_+=v,v=0),k.forEach(([e,t])=>{w&e&&t(C)}))}}},V=(e,t,n,r=0,i=t-1)=>{let a=r;for(;r<=i;){let t=E((r+i)/2);e(t)<=n?(a=t,r=t+1):i=t-1}return D(a,0,t-1)},H=(e,t,n)=>{let r=n?`unshift`:`push`;for(let n=0;n{let r=n&&n[1]||t||40,i=-1,a=0,o=n&&n[0],s=o?H(o.slice(0,C(e,o.length)),w(0,e-o.length)):H([],e),c=H([],e+1),l=e=>{let t=s[e];return t===-1?r:t},u=t=>{if(!e)return 0;if(i>=t)return c[t];i<0&&(c[0]=0,i=0);let n=i,r=c[n];for(;n{let r,i;return a=C(a,e-1),u(a)<=t?(i=V(u,e,n,a),r=V(u,e,t,a,i)):(r=V(u,e,t,void 0,a),i=V(u,e,n,r)),a=r,[r,i]},$findIndex:t=>V(u,e,t),$getItemOffset:u,$getItemSize:l,$setItemSize:(e,t)=>{let n=s[e]===-1;return s[e]=t,i=C(e,i),n},$isSizeEqual:(e,t=-1)=>s[e]===t,$getTotalSize:()=>u(e),$getLength:()=>e,$setLength:(t,n)=>{let a=t-e;return i=n?-1:C(t-1,i),e=t,a>0?(H(c,a),H(s,a,n),r*a):(c.splice(a),(n?s.splice(0,-a):s.splice(a)).reduce((e,t)=>e-(t===-1?r:t),0))},$estimateDefaultSize:t?void 0:e=>{let t=0,n=[];s.forEach((r,i)=>{r!==-1&&(r&&n.push(r),i[s.slice(),r]}},W=e=>{let t;return{o(n){(t||=new(I(F(n))).ResizeObserver(e)).observe(n)},i(e){t.unobserve(e)},l(){t&&t.disconnect()}}},G=(e,t)=>t?-e:e,K=(e,t,n,r,i,a)=>{let o,s=0,c=!1,l=!1,u=!1,d=!1,f=Date.now,p=()=>{if(c||l)return c=!1,void m();u=!1,e.$update(2)},m=()=>{A(o),o=k(p,150)},h=()=>{s=f(),u&&(d=!0),a&&e.$update(6,a()),e.$update(1,r()),m()},g=t=>{if(c||!e.$isScrolling()||t.ctrlKey)return;let r=f()-s;150>r&&50{l=!0,u=d=!1},v=()=>{l=!1,L()&&(u=!0)};return t.addEventListener(`scroll`,h),t.addEventListener(`wheel`,g,{passive:!0}),t.addEventListener(`touchstart`,_,{passive:!0}),t.addEventListener(`touchend`,v,{passive:!0}),{l:()=>{t.removeEventListener(`scroll`,h),t.removeEventListener(`wheel`,g),t.removeEventListener(`touchstart`,_),t.removeEventListener(`touchend`,v),A(o)},u:()=>{let[t,n]=e.t();t&&(i(t,n,d),d=!1,n&&e.$getViewportSize()>e.$getTotalSize()&&e.$update(1,r()))}}},q=(e,t,n)=>{let r;return[async(i,a)=>{if(!await t())return;let o,s,c;r&&r();let l=a&&R(),u=r=()=>{o=!0,A(s),c&&c()},d=()=>{if(!o){if(e.$getViewportSize()&&(A(s),s=k(u,150)),l){for(let[t,n]=e.$getRange(0);t<=n;t++)if(e.$isUnmeasuredItem(t))return;u()}e.$update(7),n(i(),l)}},f=()=>{if(o)return;let t;c=e.$subscribe(2,()=>{t||(t=!0,j(()=>{t=!1,d()}))}),d()};l?(e.$update(8,i()),j(f)):f()},()=>{r&&r()}]},J=(e,t)=>{let n,r,i=M(),a=!1,o=t?`scrollLeft`:`scrollTop`,s=t?`overflowX`:`overflowY`,[c,l]=q(e,()=>i[0],(e,r)=>{e=G(e,a),r?n.scrollTo({[t?`left`:`top`]:e,behavior:`smooth`}):n[o]=e}),u=t?`width`:`height`,d=new WeakMap,f=W(t=>{let r=[];for(let{target:i,contentRect:a}of t)if(i.offsetParent){if(i===n)e.$update(4,a[u]);else{let e=d.get(i);e!=null&&r.push([e,a[u]])}}r.length&&e.$update(3,r)});return{$observe(c,u=c.parentElement){f.o(n=u),t&&(a=getComputedStyle(u).direction===`rtl`),r=K(e,u,t,()=>G(u[o],a),(t,n,r)=>{if(r){let e=u.style,t=e[s];e[s]=`hidden`,k(()=>{e[s]=t})}u[o]=G(e.$getScrollOffset()+t,a),n&&l()}),i[1](!0)},$dispose(){f.l(),r&&r.l(),i[1](!1),i=M()},$observeItem:(e,t)=>(d.set(e,t),f.o(e),()=>{d.delete(e),f.i(e)}),$isNegative:()=>a,$scroll:c,$effect(){r&&r.u()},$getBaseOffset:e.$getStartSpacerSize,$getScrollbarSize:()=>0}},Y=(e,t)=>{e.$scroll(()=>t)},X=(e,t,n)=>{Y(e,n+t.$getScrollOffset())},Z=(e,t,n,{align:r,smooth:i,offset:a=0}={})=>{if(n=D(n,0,t.$getItemsLength()-1),r===`nearest`){let e=t.$getItemOffset(n),i=t.$getScrollOffset();if(ei+t.$getViewportSize()))return;r=`end`}}e.$scroll(()=>a+e.$getBaseOffset()+t.$getItemOffset(n)+(r===`end`?t.$getItemSize(n)-(t.$getViewportSize()-e.$getScrollbarSize()):r===`center`?(t.$getItemSize(n)-(t.$getViewportSize()-e.$getScrollbarSize()))/2:0),i)};function ee(i,s){t(s,!0);let d=c(s,`as`,3,`div`),f,m,h;l(()=>{h!==s.index&&(m&&m(),m=s.resizer(f,h=s.index))}),p(()=>{m&&m()});let g=b(()=>{let e={contain:`layout style`,position:s.hide&&s.isSSR?void 0:`absolute`,[s.horizontal?`height`:`width`]:`100%`,[s.horizontal?`top`:`left`]:`0px`,[s.horizontal?`left`:`top`]:s.offset+`px`,visibility:!s.hide||s.isSSR?void 0:`hidden`,...s.itemProps?.style};return s.horizontal&&(e.display=`inline-flex`),x(e)}),S=b(()=>{if(!s.itemProps)return;let{style:e,...t}=s.itemProps;return t});var C=n(),w=v(C);y(w,d,!1,(t,i)=>{_(t,e=>f=e,()=>f),u(t,()=>({style:r(g),...r(S)}));var o=n(),c=v(o);e(c,()=>s.children,()=>s.item,()=>s.index),a(i,o)}),a(i,C),o()}function Q(e,C){t(C,!0);let w=c(C,`getKey`,3,S),T=c(C,`as`,3,`div`),E=c(C,`shift`,3,!1),D=c(C,`horizontal`,3,!1),k=c(C,`startMargin`,3,0),A=U(C.data.length,C.itemSize,C.cache),j=B(A,C.ssrCount),M=J(j,D());j.$subscribe(1,()=>{f(F,j.$getStateVersion(),!0)}),j.$subscribe(4,()=>{C.onscroll&&C.onscroll(j.$getScrollOffset())}),j.$subscribe(8,()=>{C.onscrollend&&C.onscrollend()});let N=d(!!C.ssrCount),P=d(void 0),F=d(h(j.$getStateVersion())),I=b(()=>r(F)&&j.$getRange(C.bufferSize)),L=b(()=>r(F)&&j.$isScrolling()),R=b(()=>r(F)&&j.$getTotalSize()),V=b(()=>r(F)&&M.$isNegative()),H=b(()=>{let e=C.data.length,[t,n]=r(I),i=[];if(C.keepMounted){let r=new Set(C.keepMounted);for(let e=t;e<=n;e++)r.add(e);for(let t of O([...r]))t{f(N,!1);let e=!1,t=r(P);return s().then(()=>{e||M.$observe(t,C.scrollRef)}),()=>{e=!0}}),p(()=>{j.$dispose(),M.$dispose()}),m(()=>{C.data.length!==j.$getItemsLength()&&j.$update(5,[C.data.length,E()])}),m(()=>{k()!==j.$getStartSpacerSize()&&j.$update(6,k())});let W;l(()=>{W!==r(F)&&(W=r(F),M.$effect())});let G=A.$snapshot,K=j.$getScrollOffset,q=()=>z(j),Q=j.$getViewportSize,te=j.$findItemIndex,ne=j.$getItemOffset,re=j.$getItemSize,ie=(e,t)=>Z(M,j,e,t),ae=e=>Y(M,e),oe=e=>X(M,j,e),se=b(()=>x({contain:`size style`,"overflow-anchor":`none`,flex:`none`,position:`relative`,width:D()?r(R)+`px`:`100%`,height:D()?`100%`:r(R)+`px`,"pointer-events":r(L)?`none`:void 0}));var ce={getCache:G,getScrollOffset:K,getScrollSize:q,getViewportSize:Q,findItemIndex:te,getItemOffset:ne,getItemSize:re,scrollToIndex:ie,scrollTo:ae,scrollBy:oe},$=n(),le=v($);return y(le,T,!1,(e,t)=>{_(e,e=>f(P,e,!0),()=>r(P)),u(e,()=>({style:r(se)}));var o=n(),s=v(o);i(s,17,()=>r(H),e=>w()(C.data[e],e),(e,t)=>{let n=b(()=>C.data[r(t)]);{let i=b(()=>r(F)&&j.$getItemOffset(r(t),r(V))),a=b(()=>r(F)&&j.$isUnmeasuredItem(r(t))),o=b(()=>C.itemProps?.({item:r(n),index:r(t)}));ee(e,{get children(){return C.children},get item(){return r(n)},get index(){return r(t)},get as(){return C.item},get offset(){return r(i)},get hide(){return r(a)},get horizontal(){return D()},get isSSR(){return r(N)},get resizer(){return M.$observeItem},get itemProps(){return r(o)}})}}),a(t,o)}),a(e,$),o(ce)}export{Q as t}; \ No newline at end of file diff --git a/apps/api/internal/webassets/dist/_app/immutable/chunks/FDulIy0t.js b/apps/api/internal/webassets/dist/_app/immutable/chunks/FDulIy0t.js new file mode 100644 index 000000000..98c3d7a4f --- /dev/null +++ b/apps/api/internal/webassets/dist/_app/immutable/chunks/FDulIy0t.js @@ -0,0 +1 @@ +import{E as e,Et as t,F as n,K as r,O as i,P as a,Tt as o,X as s,a as c,at as l,d as u,gt as d,ht as f,n as p,ot as m,pt as h,r as g,s as _,ut as v,w as y,yt as b}from"./CxKeDCcw.js";import"./xihTtKlq.js";var x=e=>Object.keys(e).reduce((t,n)=>{let r=e[n];return r==null?t:t+`${n}:${r};`},``),S=(e,t)=>`_`+t,{min:C,max:w,abs:T,floor:E}=Math,D=(e,t,n)=>C(n,w(t,e)),O=e=>[...e].sort((e,t)=>e-t),k=setTimeout,A=clearTimeout,j=typeof queueMicrotask==`function`?queueMicrotask:e=>{Promise.resolve().then(e)},M=()=>{let e;return[new Promise(t=>{e=t}),e]},N=e=>e.ownerDocument,P=e=>e.defaultView,F=(e=>{let t;return()=>(e&&=(t=e(),void 0),t)})(()=>!!/iP(hone|od|ad)/.test(navigator.userAgent)||navigator.platform===`MacIntel`&&navigator.maxTouchPoints>0),I=e=>w(e.$getTotalSize(),e.$getViewportSize()),L=({$getRange:e,$findIndex:t,$getItemOffset:n,$getItemSize:r,$setItemSize:i,$isSizeEqual:a,$getTotalSize:o,$getLength:s,$setLength:c,$estimateDefaultSize:l},u=0)=>{let d=!!l,f=!!u,p=1,m=0,h=0,g=0,_=0,v=0,y=0,b=0,x=0,S=null,E=[0,f?w(u-1,0):-1],D=0,O=!1,k=new Set,A=()=>g-h,j=()=>A()+v+_,M=e=>n(e)-v,N=e=>{e&&(F()&&b!==0||S&&x===1?v+=e:_+=e)};return{$dispose:()=>{k.clear()},$getStateVersion:()=>p,$getRange:(t=200)=>{if(!O||f)return E;let n,r;if(y)[n,r]=E;else{let i=w(0,j()),a=i+m;d||(t=w(0,t),b!==1&&(i-=t),b!==2&&(a+=t)),[n,r]=E=e(w(0,i),w(0,a)),S&&(n=C(n,S[0]),r=w(r,S[1]))}return[w(n,0),C(r,s()-1)]},$findItemIndex:e=>t(e-h),$isUnmeasuredItem:a,$getItemOffset:M,$getItemSize:r,$getItemsLength:s,$getScrollOffset:()=>g,$isScrolling:()=>b!==0,$getViewportSize:()=>m,$getStartSpacerSize:()=>h,$getTotalSize:o,t:()=>(y=_,_=0,[y,x===2]),$subscribe:(e,t)=>{let n=[e,t];return k.add(n),()=>{k.delete(n)}},$update:(n,s)=>{let u,C,w=0;switch(n){case 1:{if(s===g&&x===0)break;let e=y;y=0;let t=s-g,n=T(t);e&&n=-m&&r<=o()&&(w+=1,C=n>m);break}case 2:w=8,b!==0&&(u=!0,w+=1),b=0,x=0,S=null;break;case 3:{let e=s.filter(([e,t])=>!a(e,t));if(!e.length)break;N(e.reduce((e,[t,n])=>{let i;if(x===2)i=!0;else if(S&&x===1)i=tm&&(N(l(t(j()))),d=!1),w=3,C=!0;break}case 4:m!==s&&(m||(O=C=!0),m=s,w=3);break;case 5:s[1]?(N(c(s[0],!0)),x=2,w=1):(c(s[0]),w=1);break;case 6:h=s;break;case 7:x=1;break;case 8:S=e(s,s+m),w=1}w&&(p=1+(2147483647&p),u&&v&&(_+=v,v=0),k.forEach(([e,t])=>{w&e&&t(C)}))}}},R=(e,t,n,r=0,i=t-1)=>{let a=r;for(;r<=i;){let t=E((r+i)/2);e(t)<=n?(a=t,r=t+1):i=t-1}return D(a,0,t-1)},z=(e,t,n)=>{let r=n?`unshift`:`push`;for(let n=0;n{let r=n&&n[1]||t||40,i=-1,a=0,o=n&&n[0],s=o?z(o.slice(0,C(e,o.length)),w(0,e-o.length)):z([],e),c=z([],e+1),l=e=>{let t=s[e];return t===-1?r:t},u=t=>{if(!e)return 0;if(i>=t)return c[t];i<0&&(c[0]=0,i=0);let n=i,r=c[n];for(;n{let r,i;return a=C(a,e-1),u(a)<=t?(i=R(u,e,n,a),r=R(u,e,t,a,i)):(r=R(u,e,t,void 0,a),i=R(u,e,n,r)),a=r,[r,i]},$findIndex:t=>R(u,e,t),$getItemOffset:u,$getItemSize:l,$setItemSize:(e,t)=>{let n=s[e]===-1;return s[e]=t,i=C(e,i),n},$isSizeEqual:(e,t=-1)=>s[e]===t,$getTotalSize:()=>u(e),$getLength:()=>e,$setLength:(t,n)=>{let a=t-e;return i=n?-1:C(t-1,i),e=t,a>0?(z(c,a),z(s,a,n),r*a):(c.splice(a),(n?s.splice(0,-a):s.splice(a)).reduce((e,t)=>e-(t===-1?r:t),0))},$estimateDefaultSize:t?void 0:e=>{let t=0,n=[];s.forEach((r,i)=>{r!==-1&&(r&&n.push(r),i[s.slice(),r]}},V=e=>{let t;return{o(n){(t||=new(P(N(n))).ResizeObserver(e)).observe(n)},i(e){t.unobserve(e)},l(){t&&t.disconnect()}}},H=(e,t)=>t?-e:e,U=(e,t,n,r,i,a)=>{let o,s=0,c=!1,l=!1,u=!1,d=!1,f=Date.now,p=()=>{if(c||l)return c=!1,void m();u=!1,e.$update(2)},m=()=>{A(o),o=k(p,150)},h=()=>{s=f(),u&&(d=!0),a&&e.$update(6,a()),e.$update(1,r()),m()},g=t=>{if(c||!e.$isScrolling()||t.ctrlKey)return;let r=f()-s;150>r&&50{l=!0,u=d=!1},v=()=>{l=!1,F()&&(u=!0)};return t.addEventListener(`scroll`,h),t.addEventListener(`wheel`,g,{passive:!0}),t.addEventListener(`touchstart`,_,{passive:!0}),t.addEventListener(`touchend`,v,{passive:!0}),{l:()=>{t.removeEventListener(`scroll`,h),t.removeEventListener(`wheel`,g),t.removeEventListener(`touchstart`,_),t.removeEventListener(`touchend`,v),A(o)},u:()=>{let[t,n]=e.t();t&&(i(t,n,d),d=!1,n&&e.$getViewportSize()>e.$getTotalSize()&&e.$update(1,r()))}}},W=(e,t,n)=>{let r;return[async(i,a)=>{if(!await t())return;let o,s,c;r&&r();let l=r=()=>{o=!0,A(s),c&&c()},u=()=>{if(!o){if(e.$getViewportSize()&&(A(s),s=k(l,150)),a){for(let[t,n]=e.$getRange(0);t<=n;t++)if(e.$isUnmeasuredItem(t))return;l()}e.$update(7),n(i(),a)}},d=()=>{if(o)return;let t;c=e.$subscribe(2,()=>{t||(t=!0,j(()=>{t=!1,u()}))}),u()};a?(e.$update(8,i()),j(d)):d()},()=>{r&&r()}]},G=(e,t)=>{let n,r,i=M(),a=!1,o=t?`scrollLeft`:`scrollTop`,s=t?`left`:`top`,c=t?`overflowX`:`overflowY`,[l,u]=W(e,()=>i[0],(e,t)=>{n.scrollTo({[s]:H(e,a),behavior:t?`smooth`:`instant`})}),d=t?`width`:`height`,f=new WeakMap,p=V(t=>{let r=[];for(let{target:i,contentRect:a}of t)if(i.offsetParent){if(i===n)e.$update(4,a[d]);else{let e=f.get(i);e!=null&&r.push([e,a[d]])}}r.length&&e.$update(3,r)});return{$observe(l,d=l.parentElement){p.o(n=d),t&&(a=getComputedStyle(d).direction===`rtl`),r=U(e,d,t,()=>H(d[o],a),(t,n,r)=>{if(r){let e=d.style,t=e[c];e[c]=`hidden`,k(()=>{e[c]=t})}let i=e.$getScrollOffset()+t;i<=0||i>=e.$getStartSpacerSize()+e.$getTotalSize()-e.$getViewportSize()?d.scrollTo({[s]:H(i,a),behavior:`instant`}):d.scrollBy({[s]:H(t,a),behavior:`instant`}),n&&u()}),i[1](!0)},$dispose(){p.l(),r&&r.l(),i[1](!1),i=M()},$observeItem:(e,t)=>(f.set(e,t),p.o(e),()=>{f.delete(e),p.i(e)}),$scroll:l,$effect(){r&&r.u()},$getBaseOffset:e.$getStartSpacerSize}},K=(e,t)=>{e.$scroll(()=>t)},q=(e,t,n)=>{K(e,n+t.$getScrollOffset())},J=(e,t,n,{align:r,smooth:i,offset:a=0}={})=>{if(n=D(n,0,t.$getItemsLength()-1),r===`nearest`){let e=t.$getItemOffset(n),i=t.$getScrollOffset();if(ei+t.$getViewportSize()))return;r=`end`}}e.$scroll(()=>a+e.$getBaseOffset()+t.$getItemOffset(n)+(r===`end`?t.$getItemSize(n)-t.$getViewportSize():r===`center`?(t.$getItemSize(n)-t.$getViewportSize())/2:0),i)};function Y(i,s){t(s,!0);let d=c(s,`as`,3,`div`),f,m,h;l(()=>{h!==s.index&&(m&&m(),m=s.resizer(f,h=s.index))}),p(()=>{m&&m()});let g=b(()=>{let e={contain:`layout style`,position:s.hide&&s.isSSR?void 0:`absolute`,[s.horizontal?`height`:`width`]:`100%`,[s.horizontal?`top`:`left`]:`0px`,[s.horizontal?`inset-inline-start`:`top`]:s.offset+`px`,visibility:!s.hide||s.isSSR?void 0:`hidden`,...s.itemProps?.style};return s.horizontal&&(e.display=`inline-flex`),x(e)}),S=b(()=>{if(!s.itemProps)return;let{style:e,...t}=s.itemProps;return t});var C=n(),w=v(C);y(w,d,!1,(t,i)=>{_(t,e=>f=e,()=>f),u(t,()=>({style:r(g),...r(S)}));var o=n(),c=v(o);e(c,()=>s.children,()=>s.item,()=>s.index),a(i,o)}),a(i,C),o()}function X(e,C){t(C,!0);let w=c(C,`getKey`,3,S),T=c(C,`as`,3,`div`),E=c(C,`shift`,3,!1),D=c(C,`horizontal`,3,!1),k=c(C,`startMargin`,3,0),A=B(C.data.length,C.itemSize,C.cache),j=L(A,C.ssrCount),M=G(j,D());j.$subscribe(1,()=>{f(F,j.$getStateVersion(),!0)}),j.$subscribe(4,()=>{C.onscroll&&C.onscroll(j.$getScrollOffset())}),j.$subscribe(8,()=>{C.onscrollend&&C.onscrollend()});let N=d(!!C.ssrCount),P=d(void 0),F=d(h(j.$getStateVersion())),R=b(()=>r(F)&&j.$getRange(C.bufferSize)),z=b(()=>r(F)&&j.$isScrolling()),V=b(()=>r(F)&&j.$getTotalSize()),H=b(()=>{let e=C.data.length,[t,n]=r(R),i=[];if(C.keepMounted){let r=new Set(C.keepMounted);for(let e=t;e<=n;e++)r.add(e);for(let t of O([...r]))t{f(N,!1);let e=!1,t=r(P);return s().then(()=>{e||M.$observe(t,C.scrollRef)}),()=>{e=!0}}),p(()=>{j.$dispose(),M.$dispose()}),m(()=>{C.data.length!==j.$getItemsLength()&&j.$update(5,[C.data.length,E()])}),m(()=>{k()!==j.$getStartSpacerSize()&&j.$update(6,k())});let U;l(()=>{U!==r(F)&&(U=r(F),M.$effect())});let W=A.$snapshot,X=j.$getScrollOffset,Z=()=>I(j),Q=j.$getViewportSize,ee=j.$findItemIndex,te=j.$getItemOffset,ne=j.$getItemSize,re=(e,t)=>J(M,j,e,t),ie=e=>K(M,e),ae=e=>q(M,j,e),oe=b(()=>x({contain:`size style`,"overflow-anchor":`none`,flex:`none`,position:`relative`,width:D()?r(V)+`px`:`100%`,height:D()?`100%`:r(V)+`px`,"pointer-events":r(z)?`none`:void 0}));var se={getCache:W,getScrollOffset:X,getScrollSize:Z,getViewportSize:Q,findItemIndex:ee,getItemOffset:te,getItemSize:ne,scrollToIndex:re,scrollTo:ie,scrollBy:ae},$=n(),ce=v($);return y(ce,T,!1,(e,t)=>{_(e,e=>f(P,e,!0),()=>r(P)),u(e,()=>({style:r(oe)}));var o=n(),s=v(o);i(s,17,()=>r(H),e=>w()(C.data[e],e),(e,t)=>{let n=b(()=>C.data[r(t)]);{let i=b(()=>r(F)&&j.$getItemOffset(r(t))),a=b(()=>r(F)&&j.$isUnmeasuredItem(r(t))),o=b(()=>C.itemProps?.({item:r(n),index:r(t)}));Y(e,{get children(){return C.children},get item(){return r(n)},get index(){return r(t)},get as(){return C.item},get offset(){return r(i)},get hide(){return r(a)},get horizontal(){return D()},get isSSR(){return r(N)},get resizer(){return M.$observeItem},get itemProps(){return r(o)}})}}),a(t,o)}),a(e,$),o(se)}export{X as t}; \ No newline at end of file diff --git a/apps/api/internal/webassets/dist/_app/immutable/entry/app.CuIU8RJQ.js b/apps/api/internal/webassets/dist/_app/immutable/entry/app.CmNQCuu5.js similarity index 84% rename from apps/api/internal/webassets/dist/_app/immutable/entry/app.CuIU8RJQ.js rename to apps/api/internal/webassets/dist/_app/immutable/entry/app.CmNQCuu5.js index c99a4ada0..25d87cb90 100644 --- a/apps/api/internal/webassets/dist/_app/immutable/entry/app.CuIU8RJQ.js +++ b/apps/api/internal/webassets/dist/_app/immutable/entry/app.CmNQCuu5.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../nodes/0.BoweeEZi.js","../chunks/DK3Fl9T5.js","../chunks/CxKeDCcw.js","../chunks/ChC1oWd7.js","../chunks/Dt-HX3Vu.js","../chunks/xihTtKlq.js","../chunks/qQG-ipvL.js","../chunks/Y2iPPnRJ.js","../chunks/Dsl_OP1c.js","../assets/0.C7M1Y4Cy.css","../nodes/1.CvWNubFT.js","../chunks/Dr1oMBlb.js","../nodes/2.FqypOih0.js","../chunks/Qo16U5GS.js","../chunks/OQjxVT6U.js","../nodes/3.Bk3qR6j8.js","../chunks/HclGiUj8.js","../chunks/CYM1xkwL.js","../nodes/4.B4ob5Fc_.js","../chunks/bE-mhUF5.js","../chunks/HlY492D_.js","../chunks/ZgTSXUg-.js","../assets/QuoteBlock.Bmfc9wvU.css","../chunks/CS_f1eMF.js","../chunks/DlGnnCJo.js","../chunks/DuOqi7WJ.js","../chunks/j7YOEK28.js","../assets/ThreadPanel.DFXp9CyT.css","../chunks/DNWg-bnz.js","../chunks/CQTKCwo-.js","../assets/ChatApp.BrxGlI__.css","../nodes/5.DbuY83i0.js","../nodes/6.D1H8DGKr.js","../nodes/7.7Sil-m_s.js","../chunks/Co6zx9gg.js","../nodes/8.DQV6fdDu.js","../nodes/9.Dg3zskXi.js","../nodes/10.B7i4Jw-E.js","../nodes/11.CirkYH_v.js","../nodes/12.CslOyJOL.js","../assets/12.CzRaoRZI.css","../nodes/13.C612ugSD.js","../assets/13.CMVv15Ug.css"])))=>i.map(i=>d[i]); -import{At as e,Et as t,F as n,I as r,K as i,N as a,P as o,R as s,T as c,Tt as l,X as u,a as d,at as f,ft as p,gt as m,ht as h,i as g,it as _,j as v,lt as y,ot as b,r as x,s as S,ut as C,yt as w}from"../chunks/CxKeDCcw.js";import{t as T}from"../chunks/HclGiUj8.js";import"../chunks/xihTtKlq.js";var E={},D=r(`
            `),O=r(` `,1);function k(r,g){t(g,!0);let T=d(g,`components`,23,()=>[]),E=d(g,`data_0`,3,null),k=d(g,`data_1`,3,null),A=d(g,`data_2`,3,null);b(()=>g.stores.page.set(g.page)),f(()=>{g.stores,g.page,g.constructors,T(),g.form,E(),k(),A(),g.stores.page.notify()});let j=m(!1),M=m(!1),N=m(null);x(()=>{let e=g.stores.page.subscribe(()=>{i(j)&&(h(M,!0),u().then(()=>{h(N,document.title||`untitled page`,!0)}))});return h(j,!0),e});let P=w(()=>g.constructors[2]);var F=O(),I=C(F),L=e=>{let t=w(()=>g.constructors[0]);var r=n(),a=C(r);c(a,()=>i(t),(e,t)=>{S(t(e,{get data(){return E()},get form(){return g.form},get params(){return g.page.params},children:(e,t)=>{var r=n(),a=C(r),s=e=>{let t=w(()=>g.constructors[1]);var r=n(),a=C(r);c(a,()=>i(t),(e,t)=>{S(t(e,{get data(){return k()},get form(){return g.form},get params(){return g.page.params},children:(e,t)=>{var r=n(),a=C(r);c(a,()=>i(P),(e,t)=>{S(t(e,{get data(){return A()},get form(){return g.form},get params(){return g.page.params}}),e=>T()[2]=e,()=>T()?.[2])}),o(e,r)},$$slots:{default:!0}}),e=>T()[1]=e,()=>T()?.[1])}),o(e,r)},l=e=>{let t=w(()=>g.constructors[1]);var r=n(),a=C(r);c(a,()=>i(t),(e,t)=>{S(t(e,{get data(){return k()},get form(){return g.form},get params(){return g.page.params}}),e=>T()[1]=e,()=>T()?.[1])}),o(e,r)};v(a,e=>{g.constructors[2]?e(s):e(l,-1)}),o(e,r)},$$slots:{default:!0}}),e=>T()[0]=e,()=>T()?.[0])}),o(e,r)},R=e=>{let t=w(()=>g.constructors[0]);var r=n(),a=C(r);c(a,()=>i(t),(e,t)=>{S(t(e,{get data(){return E()},get form(){return g.form},get params(){return g.page.params}}),e=>T()[0]=e,()=>T()?.[0])}),o(e,r)};v(I,e=>{g.constructors[1]?e(L):e(R,-1)});var z=p(I,2),B=t=>{var n=D(),r=y(n),c=e=>{var t=s();_(()=>a(t,i(N))),o(e,t)};v(r,e=>{i(M)&&e(c)}),e(n),o(t,n)};v(z,e=>{i(j)&&e(B)}),o(r,F),l()}var A=g(k),j=[()=>T(()=>import(`../nodes/0.BoweeEZi.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]),import.meta.url),()=>T(()=>import(`../nodes/1.CvWNubFT.js`),__vite__mapDeps([10,2,1,5,11,3,4]),import.meta.url),()=>T(()=>import(`../nodes/2.FqypOih0.js`),__vite__mapDeps([12,1,2,3,4,5,6,8,11,13,14]),import.meta.url),()=>T(()=>import(`../nodes/3.Bk3qR6j8.js`),__vite__mapDeps([15,1,2,16,5,17]),import.meta.url),()=>T(()=>import(`../nodes/4.B4ob5Fc_.js`),__vite__mapDeps([18,2,1,5,17,19,3,4,16,6,8,7,13,14,20,21,22,23,24,25,26,27,28,29,30]),import.meta.url),()=>T(()=>import(`../nodes/5.DbuY83i0.js`),__vite__mapDeps([31,2,1,5,19,3,4,16,6,8,7,13,14,17,20,21,22,23,24,25,26,27,28,29,30]),import.meta.url),()=>T(()=>import(`../nodes/6.D1H8DGKr.js`),__vite__mapDeps([32,1,4,13]),import.meta.url),()=>T(()=>import(`../nodes/7.7Sil-m_s.js`),__vite__mapDeps([33,1,2,5,8,7,14,28,34]),import.meta.url),()=>T(()=>import(`../nodes/8.DQV6fdDu.js`),__vite__mapDeps([35,1,2,5,8,7,14,24,25,28,29,34]),import.meta.url),()=>T(()=>import(`../nodes/9.Dg3zskXi.js`),__vite__mapDeps([36,1,2,5,21,8,25,29]),import.meta.url),()=>T(()=>import(`../nodes/10.B7i4Jw-E.js`),__vite__mapDeps([37,1,2,3,4,5,6,8,14,29]),import.meta.url),()=>T(()=>import(`../nodes/11.CirkYH_v.js`),__vite__mapDeps([38,2,1,5,19,3,4,16,6,8,7,13,14,17,20,21,22,23,24,25,26,27,28,29,30]),import.meta.url),()=>T(()=>import(`../nodes/12.CslOyJOL.js`),__vite__mapDeps([39,1,2,5,8,7,20,21,22,23,24,25,29,40]),import.meta.url),()=>T(()=>import(`../nodes/13.C612ugSD.js`),__vite__mapDeps([41,1,2,5,8,7,20,21,22,24,26,27,29,42]),import.meta.url)],M=[],N={"/":[3],"/app":[4],"/app/[workspaceID]":[5],"/app/[workspaceID]/(settings)/settings":[6,[2]],"/app/[workspaceID]/(settings)/settings/bots":[7,[2]],"/app/[workspaceID]/(settings)/settings/integrations":[8,[2]],"/app/[workspaceID]/(settings)/settings/members":[9,[2]],"/app/[workspaceID]/(settings)/settings/overview":[10,[2]],"/app/[workspaceID]/[targetID]":[11],"/embed/channel/[workspaceID]/[channelID]":[12],"/embed/thread/[workspaceID]/[messageID]":[13]},P={handleError:(({error:e})=>{console.error(e)}),reroute:(()=>{}),transport:{}},F=Object.fromEntries(Object.entries(P.transport).map(([e,t])=>[e,t.decode])),I=Object.fromEntries(Object.entries(P.transport).map(([e,t])=>[e,t.encode])),L=!1,R=(e,t)=>F[e](t),z=()=>T(()=>import(`../chunks/Bjy-W4x2.js`).then(e=>e.default),[],import.meta.url);export{R as decode,F as decoders,N as dictionary,I as encoders,z as get_error_template,L as hash,P as hooks,E as matchers,j as nodes,A as root,M as server_loads}; \ No newline at end of file +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../nodes/0.BoweeEZi.js","../chunks/DK3Fl9T5.js","../chunks/CxKeDCcw.js","../chunks/ChC1oWd7.js","../chunks/Dt-HX3Vu.js","../chunks/xihTtKlq.js","../chunks/qQG-ipvL.js","../chunks/Y2iPPnRJ.js","../chunks/Dsl_OP1c.js","../assets/0.C7M1Y4Cy.css","../nodes/1.CvWNubFT.js","../chunks/Dr1oMBlb.js","../nodes/2.FqypOih0.js","../chunks/Qo16U5GS.js","../chunks/OQjxVT6U.js","../nodes/3.BjKv85Xn.js","../chunks/HclGiUj8.js","../chunks/CYM1xkwL.js","../nodes/4.DWf1Rryr.js","../chunks/Bi80bmu0.js","../chunks/HlY492D_.js","../chunks/ZgTSXUg-.js","../assets/QuoteBlock.Bmfc9wvU.css","../chunks/BZg3JVyH.js","../chunks/DlGnnCJo.js","../chunks/FDulIy0t.js","../chunks/j7YOEK28.js","../assets/ThreadPanel.DFXp9CyT.css","../chunks/DNWg-bnz.js","../chunks/CQTKCwo-.js","../assets/ChatApp.BrxGlI__.css","../nodes/5.RekE5Dhm.js","../nodes/6.D1H8DGKr.js","../nodes/7.7Sil-m_s.js","../chunks/Co6zx9gg.js","../nodes/8.Mhs-olOD.js","../nodes/9.B0w8C4TJ.js","../nodes/10.B7i4Jw-E.js","../nodes/11.CjJE99y4.js","../nodes/12.DdKfTBT7.js","../assets/12.CzRaoRZI.css","../nodes/13.C612ugSD.js","../assets/13.CMVv15Ug.css"])))=>i.map(i=>d[i]); +import{At as e,Et as t,F as n,I as r,K as i,N as a,P as o,R as s,T as c,Tt as l,X as u,a as d,at as f,ft as p,gt as m,ht as h,i as g,it as _,j as v,lt as y,ot as b,r as x,s as S,ut as C,yt as w}from"../chunks/CxKeDCcw.js";import{t as T}from"../chunks/HclGiUj8.js";import"../chunks/xihTtKlq.js";var E={},D=r(`
            `),O=r(` `,1);function k(r,g){t(g,!0);let T=d(g,`components`,23,()=>[]),E=d(g,`data_0`,3,null),k=d(g,`data_1`,3,null),A=d(g,`data_2`,3,null);b(()=>g.stores.page.set(g.page)),f(()=>{g.stores,g.page,g.constructors,T(),g.form,E(),k(),A(),g.stores.page.notify()});let j=m(!1),M=m(!1),N=m(null);x(()=>{let e=g.stores.page.subscribe(()=>{i(j)&&(h(M,!0),u().then(()=>{h(N,document.title||`untitled page`,!0)}))});return h(j,!0),e});let P=w(()=>g.constructors[2]);var F=O(),I=C(F),L=e=>{let t=w(()=>g.constructors[0]);var r=n(),a=C(r);c(a,()=>i(t),(e,t)=>{S(t(e,{get data(){return E()},get form(){return g.form},get params(){return g.page.params},children:(e,t)=>{var r=n(),a=C(r),s=e=>{let t=w(()=>g.constructors[1]);var r=n(),a=C(r);c(a,()=>i(t),(e,t)=>{S(t(e,{get data(){return k()},get form(){return g.form},get params(){return g.page.params},children:(e,t)=>{var r=n(),a=C(r);c(a,()=>i(P),(e,t)=>{S(t(e,{get data(){return A()},get form(){return g.form},get params(){return g.page.params}}),e=>T()[2]=e,()=>T()?.[2])}),o(e,r)},$$slots:{default:!0}}),e=>T()[1]=e,()=>T()?.[1])}),o(e,r)},l=e=>{let t=w(()=>g.constructors[1]);var r=n(),a=C(r);c(a,()=>i(t),(e,t)=>{S(t(e,{get data(){return k()},get form(){return g.form},get params(){return g.page.params}}),e=>T()[1]=e,()=>T()?.[1])}),o(e,r)};v(a,e=>{g.constructors[2]?e(s):e(l,-1)}),o(e,r)},$$slots:{default:!0}}),e=>T()[0]=e,()=>T()?.[0])}),o(e,r)},R=e=>{let t=w(()=>g.constructors[0]);var r=n(),a=C(r);c(a,()=>i(t),(e,t)=>{S(t(e,{get data(){return E()},get form(){return g.form},get params(){return g.page.params}}),e=>T()[0]=e,()=>T()?.[0])}),o(e,r)};v(I,e=>{g.constructors[1]?e(L):e(R,-1)});var z=p(I,2),B=t=>{var n=D(),r=y(n),c=e=>{var t=s();_(()=>a(t,i(N))),o(e,t)};v(r,e=>{i(M)&&e(c)}),e(n),o(t,n)};v(z,e=>{i(j)&&e(B)}),o(r,F),l()}var A=g(k),j=[()=>T(()=>import(`../nodes/0.BoweeEZi.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]),import.meta.url),()=>T(()=>import(`../nodes/1.CvWNubFT.js`),__vite__mapDeps([10,2,1,5,11,3,4]),import.meta.url),()=>T(()=>import(`../nodes/2.FqypOih0.js`),__vite__mapDeps([12,1,2,3,4,5,6,8,11,13,14]),import.meta.url),()=>T(()=>import(`../nodes/3.BjKv85Xn.js`),__vite__mapDeps([15,1,2,16,5,17]),import.meta.url),()=>T(()=>import(`../nodes/4.DWf1Rryr.js`),__vite__mapDeps([18,2,1,5,17,19,3,4,16,6,8,7,13,14,20,21,22,23,24,25,26,27,28,29,30]),import.meta.url),()=>T(()=>import(`../nodes/5.RekE5Dhm.js`),__vite__mapDeps([31,2,1,5,19,3,4,16,6,8,7,13,14,17,20,21,22,23,24,25,26,27,28,29,30]),import.meta.url),()=>T(()=>import(`../nodes/6.D1H8DGKr.js`),__vite__mapDeps([32,1,4,13]),import.meta.url),()=>T(()=>import(`../nodes/7.7Sil-m_s.js`),__vite__mapDeps([33,1,2,5,8,7,14,28,34]),import.meta.url),()=>T(()=>import(`../nodes/8.Mhs-olOD.js`),__vite__mapDeps([35,1,2,5,8,7,14,24,25,28,29,34]),import.meta.url),()=>T(()=>import(`../nodes/9.B0w8C4TJ.js`),__vite__mapDeps([36,1,2,5,21,8,25,29]),import.meta.url),()=>T(()=>import(`../nodes/10.B7i4Jw-E.js`),__vite__mapDeps([37,1,2,3,4,5,6,8,14,29]),import.meta.url),()=>T(()=>import(`../nodes/11.CjJE99y4.js`),__vite__mapDeps([38,2,1,5,19,3,4,16,6,8,7,13,14,17,20,21,22,23,24,25,26,27,28,29,30]),import.meta.url),()=>T(()=>import(`../nodes/12.DdKfTBT7.js`),__vite__mapDeps([39,1,2,5,8,7,20,21,22,23,24,25,29,40]),import.meta.url),()=>T(()=>import(`../nodes/13.C612ugSD.js`),__vite__mapDeps([41,1,2,5,8,7,20,21,22,24,26,27,29,42]),import.meta.url)],M=[],N={"/":[3],"/app":[4],"/app/[workspaceID]":[5],"/app/[workspaceID]/(settings)/settings":[6,[2]],"/app/[workspaceID]/(settings)/settings/bots":[7,[2]],"/app/[workspaceID]/(settings)/settings/integrations":[8,[2]],"/app/[workspaceID]/(settings)/settings/members":[9,[2]],"/app/[workspaceID]/(settings)/settings/overview":[10,[2]],"/app/[workspaceID]/[targetID]":[11],"/embed/channel/[workspaceID]/[channelID]":[12],"/embed/thread/[workspaceID]/[messageID]":[13]},P={handleError:(({error:e})=>{console.error(e)}),reroute:(()=>{}),transport:{}},F=Object.fromEntries(Object.entries(P.transport).map(([e,t])=>[e,t.decode])),I=Object.fromEntries(Object.entries(P.transport).map(([e,t])=>[e,t.encode])),L=!1,R=(e,t)=>F[e](t),z=()=>T(()=>import(`../chunks/Bjy-W4x2.js`).then(e=>e.default),[],import.meta.url);export{R as decode,F as decoders,N as dictionary,I as encoders,z as get_error_template,L as hash,P as hooks,E as matchers,j as nodes,A as root,M as server_loads}; \ No newline at end of file diff --git a/apps/api/internal/webassets/dist/_app/immutable/nodes/11.CirkYH_v.js b/apps/api/internal/webassets/dist/_app/immutable/nodes/11.CjJE99y4.js similarity index 77% rename from apps/api/internal/webassets/dist/_app/immutable/nodes/11.CirkYH_v.js rename to apps/api/internal/webassets/dist/_app/immutable/nodes/11.CjJE99y4.js index c6e237114..4f1803fe3 100644 --- a/apps/api/internal/webassets/dist/_app/immutable/nodes/11.CirkYH_v.js +++ b/apps/api/internal/webassets/dist/_app/immutable/nodes/11.CjJE99y4.js @@ -1 +1 @@ -import{Et as e,Tt as t}from"../chunks/CxKeDCcw.js";import"../chunks/xihTtKlq.js";import{t as n}from"../chunks/bE-mhUF5.js";function r(r,i){e(i,!0),n(r,{get routeWorkspaceID(){return i.params.workspaceID},get routeTargetID(){return i.params.targetID}}),t()}export{r as component}; \ No newline at end of file +import{Et as e,Tt as t}from"../chunks/CxKeDCcw.js";import"../chunks/xihTtKlq.js";import{t as n}from"../chunks/Bi80bmu0.js";function r(r,i){e(i,!0),n(r,{get routeWorkspaceID(){return i.params.workspaceID},get routeTargetID(){return i.params.targetID}}),t()}export{r as component}; \ No newline at end of file diff --git a/apps/api/internal/webassets/dist/_app/immutable/nodes/12.CslOyJOL.js b/apps/api/internal/webassets/dist/_app/immutable/nodes/12.DdKfTBT7.js similarity index 99% rename from apps/api/internal/webassets/dist/_app/immutable/nodes/12.CslOyJOL.js rename to apps/api/internal/webassets/dist/_app/immutable/nodes/12.DdKfTBT7.js index a46b2281d..5d8c213fe 100644 --- a/apps/api/internal/webassets/dist/_app/immutable/nodes/12.CslOyJOL.js +++ b/apps/api/internal/webassets/dist/_app/immutable/nodes/12.DdKfTBT7.js @@ -1 +1 @@ -import{t as e}from"../chunks/DK3Fl9T5.js";import{A as t,At as n,B as r,C as i,Et as a,F as o,I as s,K as c,N as l,P as u,Q as ee,S as te,Tt as d,V as ne,X as f,dt as p,ft as m,gt as h,ht as g,it as _,j as v,kt as re,lt as y,n as ie,pt as ae,r as oe,st as se,ut as ce,yt as b,z as x}from"../chunks/CxKeDCcw.js";import"../chunks/xihTtKlq.js";import{i as le,n as S,t as C,u as w}from"../chunks/Dsl_OP1c.js";import{d as ue}from"../chunks/Y2iPPnRJ.js";import{D as de,E as fe,R as pe,T as me,f as he,j as ge,p as _e,w as ve,x as ye}from"../chunks/HlY492D_.js";import{i as be,n as xe,t as Se}from"../chunks/CS_f1eMF.js";import{t as Ce}from"../chunks/DlGnnCJo.js";import{r as we,t as Te}from"../chunks/CQTKCwo-.js";var T=e({prerender:()=>!1,ssr:()=>!1}),Ee=s(``),De=s(`Archived`),Oe=s(`

            `),ke=s(`

            `),Ae=s(`

            Sign in to ClickClack

            Open ClickClack in a new tab, sign in, then return here. This panel will reconnect automatically.

            Open ClickClack
            `),je=s(`
            `),Me=s(`
            `),Ne=s(`
            `),Pe=s(`
            `),Fe=s(``),Ie=s(` `,1);function E(e,t){a(t,!0);let o=h(`loading`),s=h(``),x=h(null),T=new ve(()=>c(x)?.id||``),E=new de(He),D=h(null),O=h(null),k=h(ae([])),A=h(0),j=h(0),M=h(!1),N=h(!1),P=h(!1),F=h(``),I=h(null),Le=h(null),L=h(null),R=h(void 0),z=h(``),B=h(``),V=h(!1),H=h(null),U=h(null),W=null,G=0,Re=!1,K=null,q=h(ae([])),J=0,ze=null,Y=h(``),X=null,Z=new be(()=>[c(x)?.id,c(O)?.id].join(`:`)),Be=b(()=>{let e=new Map;for(let t of c(q))t.id&&!t.deleted_at&&e.set(t.id,t);for(let t of c(k))t.author?.id&&t.author.handle?.trim()&&!t.author.deleted_at&&e.set(t.author.id,t.author);return c(x)?.id&&e.set(c(x).id,c(x)),[...e.values()]});async function Ve(e){let t=++J;ze?.abort();let n=new AbortController;ze=n,g(Y,``),g(q,[],!0);try{let r=await Te({workspaceID:e,limit:100,signal:n.signal});t===J&&g(q,r.map(e=>e.user),!0)}catch(e){!n.signal.aborted&&t===J&&(g(q,[],!0),g(Y,we(e),!0))}}async function He(e,t){if(e===c(O)?.id){c(L)?.scrollToMessage(t.messageID);for(let e=0;e<16;e+=1){await f(),await new Promise(e=>requestAnimationFrame(()=>e()));let e=document.querySelector(`.embed-channel-shell`)?.querySelector(`[data-message-id="${CSS.escape(t.messageID)}"]`)?.querySelector(`textarea[aria-label="Edit message"]`);if(e){e.focus();return}}}}function Ue(e){g(k,c(k).map(Z.updateMessage(e)),!0)}function We(...e){let t=new Map;for(let n of e)for(let e of n)t.set(e.id,e);return[...t.values()].sort((e,t)=>(e.channel_seq||0)-(t.channel_seq||0))}function Q(e,t){t===`replace`&&g(R,void 0),T.seedMessages(e.messages),g(k,t===`replace`?e.messages:t===`prepend`?We(e.messages,c(k)):We(c(k),e.messages),!0),E.reconcile(c(O)?.id||``,c(k)),t===`replace`?(g(A,e.oldest_seq,!0),g(j,e.newest_seq,!0),g(M,e.has_older,!0),g(N,e.has_newer,!0)):(g(A,Math.min(c(A)||e.oldest_seq,e.oldest_seq||c(A)),!0),t===`prepend`&&g(M,e.has_older,!0),t===`append`&&(e.newest_seq>c(j)?g(N,e.has_newer,!0):e.newest_seq===c(j)&&g(N,c(N)||e.has_newer,!0)),g(j,Math.max(c(j),e.newest_seq),!0))}function Ge(){Z.clear(),K=null,g(V,!1),g(z,``),J+=1,ze?.abort(),W?.close(),W=null,g(D,null),g(O,null),T.clear(),E.clear(),g(k,[],!0),g(R,void 0),g(A,0),g(j,0),g(M,!1),g(N,!1),g(P,!1),X=null,g(I,null),g(U,null),g(H,null)}function Ke(e){if(Ge(),e instanceof me){g(o,`forbidden`);return}if(e instanceof C){if(e.status===401){g(o,`auth`);return}if(e.status===403){g(o,`forbidden`);return}if(e.status===404){g(o,`not-found`);return}}g(s,w(e,`Could not load this channel.`),!0),g(o,`error`)}async function qe(){if(Re)return;Re=!0;let e=++G;c(o)!==`auth`&&g(o,`loading`),g(s,``);try{let n=await ue(),r=await S(`/api/routes/${encodeURIComponent(t.workspaceRouteID)}/${encodeURIComponent(t.channelRouteID)}`);if(r.route.target_type!==`channel`)throw new C(404,`Channel route not found`);await Xe(r.route.workspace_id,r.route.target_id,e=>{c(x)&&c(x).id!==n.user.id&&g(F,``),g(x,n.user,!0),g(D,r.route,!0),Ve(r.route.workspace_id),g(O,e.channel,!0),Q(e,`replace`),g(o,`ready`),at(r.route.workspace_id)},()=>e===G)}catch(t){e===G&&Ke(t)}finally{e===G&&(Re=!1)}}async function Je(){if(!c(O)||c(P)||!c(M)||c(A)<=0)return;let e=c(O).id,t=G;g(P,!0);try{await Z.run(()=>S(`/api/channels/${encodeURIComponent(e)}/messages?before_seq=${encodeURIComponent(String(c(A)))}&limit=100`),e=>{g(R,c(L)?.captureState()??void 0,!0),Q(e,`prepend`)},()=>t===G&&c(O)?.id===e&&c(o)===`ready`)}catch(e){t===G&&g(z,w(e,`Could not load older messages.`),!0)}finally{t===G&&g(P,!1)}}async function Ye(){let e=G;if(!(X===e||!c(N))){X=e;try{await Qe(()=>e===G)}catch(t){e===G&&rt(t)}finally{X===e&&(X=null)}}}function Xe(e,t,n,r){return Z.run(async()=>{let[n,r]=await Promise.all([S(`/api/workspaces/${encodeURIComponent(e)}/channels`),S(`/api/channels/${encodeURIComponent(t)}/messages?limit=100`)]),i=n.channels.find(e=>e.id===t);if(!i)throw new C(404,`Channel not found`);return{...r,channel:i}},n,r)}async function Ze(e=()=>!0){if(!c(D)||!c(O)||c(o)!==`ready`)return;let t=c(D).workspace_id,n=c(O).id,r=G;await Xe(t,n,e=>{G++,Z.prune(),g(P,!1),X=null,g(O,e.channel,!0),Q(e,`replace`)},()=>e()&&r===G&&c(O)?.id===n&&c(o)===`ready`)}async function Qe(e=()=>!0){if(!c(O)||c(o)!==`ready`)return;let t=c(O).id,n=G,r=()=>e()&&n===G&&c(O)?.id===t&&c(o)===`ready`;try{let e=c(j);for(let n=0;n<20;n++){let n=await Z.run(()=>S(`/api/channels/${encodeURIComponent(t)}/messages?after_seq=${encodeURIComponent(String(e))}&limit=100`),e=>Q(e,`append`),r);if(!n||!r())return;let i=n.newest_seq||e;if(!n.has_newer||i<=e){it();return}e=i}throw Error(`Realtime message recovery exceeded its page limit`)}catch(e){if(!r())return;throw e}}async function $e(e,t=()=>!0){!c(k).some(t=>t.id===e)&&!Z.pending||await Z.run(()=>S(`/api/messages/${encodeURIComponent(e)}`),e=>{Ue(e.message),E.reconcile(c(O)?.id||``,c(k))},t)}async function et(e=()=>!0){if(!c(D)||!c(O))return;let t=await S(`/api/workspaces/${encodeURIComponent(c(D).workspace_id)}/channels`);if(!e())return;let n=t.channels.find(e=>e.id===c(O)?.id);if(!n)throw new C(404,`Channel not found`);g(O,n,!0)}function tt(e){return e.channel_id||e.payload.channel_id||``}async function nt(e,t){if(!(!c(O)||tt(e)!==c(O).id)){if(e.type===`message.created`){let n=e.seq||e.payload.seq||0;if(n>0&&n<=c(j))return;await Qe(t);return}if(e.type===`message.updated`||e.type===`message.deleted`){e.payload.message_id&&await $e(e.payload.message_id,t);return}if(e.type===`reaction.added`||e.type===`reaction.removed`){T.applyEvent(e);return}e.type===`channel.updated`&&await et(t)}}function rt(e){if(c(o)===`ready`){if(e instanceof me||e instanceof C&&[401,403,404].includes(e.status)){Ke(e);return}g(B,w(e,`Could not process a realtime update.`),!0),g(z,c(B),!0)}}function it(){c(z)===c(B)&&g(z,``),g(B,``)}function at(e){W?.close(),W=fe({workspaceID:e,onEvent:nt,onOpen:async(e,t)=>{t&&(T.clear(),await Ze(e)),e()&&it()},onError:rt})}async function ot(){let e=c(F).trim();if(!e||!c(O)||c(V))return;let t=c(O).id,n=c(I)?.id,r=K?.body===e&&K.quotedMessageID===n?K:{body:e,nonce:ge(),quotedMessageID:n};K=r,g(z,``),g(V,!0);let i;try{({message:i}=await S(`/api/channels/${encodeURIComponent(t)}/messages`,{method:`POST`,body:JSON.stringify({body:e,nonce:r.nonce,quoted_message_id:n})}))}catch(e){if(K!==r)return;if(e instanceof C&&e.status===401){Ke(e);return}g(z,w(e,`Could not send this message.`),!0);return}finally{K===r&&g(V,!1)}if(K!==r||c(O)?.id!==t||c(o)!==`ready`)return;K=null,g(k,We([i],c(k)),!0),c(F).trim()===e&&g(F,``),n&&c(I)?.id===n&&g(I,null);let a=G;Qe(()=>a===G).catch(e=>{a===G&&rt(e)}),await f(),a===G&&c(O)?.id===t&&c(o)===`ready`&&await c(L)?.scrollToBottom()}function st(e){if(e.key===`Escape`&&c(I)){e.preventDefault(),g(I,null);return}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ot())}function ct(e){c(V)||(g(I,e,!0),f().then(()=>c(Le)?.focus()))}function lt(e){e.quoted_message_id&&c(L)?.scrollToMessage(e.quoted_message_id)}function ut(e){if(!e.route_id)return;let n=window.open(`/app/${encodeURIComponent(t.workspaceRouteID)}/${encodeURIComponent(e.route_id)}`,`_blank`,`noopener,noreferrer`);n&&(n.opener=null)}function dt(e){let t=e.target;!(t instanceof HTMLImageElement)||!t.closest(`.markdown`)||(e.preventDefault(),g(H,{url:pe(t),title:t.alt||`Image`},!0))}function ft(e){let t=window.open(le(`/api/uploads/${e.id}`),`_blank`,`noopener,noreferrer`);t&&(t.opener=null)}function $(){c(o)===`auth`&&document.visibilityState===`visible`&&qe()}function pt(e){return e.showModal(),{destroy:()=>e.close()}}oe(()=>{qe(),window.addEventListener(`focus`,$),document.addEventListener(`visibilitychange`,$)}),ie(()=>{G+=1,Ge(),window.removeEventListener(`focus`,$),document.removeEventListener(`visibilitychange`,$)});var mt=Ie();i(`6awrv5`,e=>{var t=Ee();ee(e=>{se.title=e??``},[()=>c(O)?`#${Ce(c(O))} · ClickClack`:`ClickClack channel`]),u(e,t)});var ht=ce(mt),gt=e=>{var t=ke(),r=y(t),i=y(r),a=m(y(i),2),o=p(a,!0),s=m(a,2),ee=e=>{var t=De();u(e,t)};v(s,e=>{c(O).archived_at&&e(ee)}),n(i),n(r);var te=m(r,2);{let e=b(()=>c(x)?.id);xe(te,{get messages(){return c(k)},get selectedChannel(){return c(O)},get mentionPeople(){return c(Be)},get viewKey(){return c(O).id},get hasOlder(){return c(M)},get hasNewer(){return c(N)},get loadingOlder(){return c(P)},get restoreState(){return c(R)},get currentUserID(){return c(e)},get reactionController(){return T},get editController(){return E},get editScope(){return c(O).id},onMessageEdited:Ue,onListRef:e=>g(L,e,!0),onActivateMessageComposer:()=>{},onInlineImagePointerUp:dt,onOpenProfile:e=>g(U,e||null,!0),onReply:e=>ct(e),onOpenThread:ut,onJumpToQuote:lt,onOpenImage:(e,t)=>g(H,{url:e,title:t},!0),onOpenArtifact:ft,onLoadOlder:()=>void Je(),onLoadNewer:()=>void Ye()})}var d=m(te,2),ne=y(d),f=e=>{var t=Oe(),n=p(t);_(()=>l(n,`Mentions unavailable: ${c(Y)??``}`)),u(e,t)};v(ne,e=>{c(Y)&&e(f)});var h=m(ne,2),re=e=>{var t=Oe(),n=p(t,!0);_(()=>l(n,c(z))),u(e,t)};v(h,e=>{c(z)&&e(re)});var ie=m(h,2);{let e=b(()=>`Message #${Ce(c(O))}`);ye(ie,{get value(){return c(F)},get placeholder(){return c(e)},ariaLabel:`Message body`,submitLabel:`Send`,formClass:`composer embed-channel-composer`,get disabled(){return c(V)},get replyTarget(){return c(I)},showToolbar:!0,get mentionPeople(){return c(Be)},onValue:e=>g(F,e,!0),onSubmit:()=>void ot(),onKeydown:st,onFocus:()=>g(z,``),onInputRef:e=>g(Le,e,!0),onClearReply:()=>g(I,null)})}n(d),n(t),_(e=>l(o,e),[()=>Ce(c(O))]),u(e,t)},_t=e=>{var t=Ae(),r=y(t),i=y(r);he(i,{class:`embed-mark`,size:42}),re(6),n(r),n(t),u(e,t)},vt=e=>{var t=je();u(e,t)},yt=e=>{var t=Me();u(e,t)},bt=e=>{var t=Ne(),i=y(t),a=m(y(i),2),o=p(a,!0),ee=m(a,2);n(i),n(t),_(()=>l(o,c(s))),r(`click`,ee,()=>void qe()),u(e,t)},xt=e=>{var t=Pe();u(e,t)};v(ht,e=>{c(o)===`ready`&&c(O)&&c(D)?e(gt):c(o)===`auth`?e(_t,1):c(o)===`forbidden`?e(vt,2):c(o)===`not-found`?e(yt,3):c(o)===`error`?e(bt,4):e(xt,-1)});var St=m(ht,2),Ct=e=>{_e(e,{get url(){return c(H).url},get title(){return c(H).title},onClose:()=>g(H,null)})};v(St,e=>{c(H)&&e(Ct)});var wt=m(St,2),Tt=e=>{var t=Fe(),r=y(t);Se(r,{get profile(){return c(U)},get currentUser(){return c(x)},onClose:()=>g(U,null)}),n(t),te(t,e=>pt?.(e)),ne(`close`,t,()=>g(U,null)),u(e,t)};v(wt,e=>{c(U)&&e(Tt)}),u(e,mt),d()}x([`click`]);function D(e,n){a(n,!0);var r=o(),i=ce(r);t(i,()=>`${n.params.workspaceID}:${n.params.channelID}`,e=>{E(e,{get workspaceRouteID(){return n.params.workspaceID},get channelRouteID(){return n.params.channelID}})}),u(e,r),d()}export{D as component,T as universal}; \ No newline at end of file +import{t as e}from"../chunks/DK3Fl9T5.js";import{A as t,At as n,B as r,C as i,Et as a,F as o,I as s,K as c,N as l,P as u,Q as ee,S as te,Tt as d,V as ne,X as f,dt as p,ft as m,gt as h,ht as g,it as _,j as v,kt as re,lt as y,n as ie,pt as ae,r as oe,st as se,ut as ce,yt as b,z as x}from"../chunks/CxKeDCcw.js";import"../chunks/xihTtKlq.js";import{i as le,n as S,t as C,u as w}from"../chunks/Dsl_OP1c.js";import{d as ue}from"../chunks/Y2iPPnRJ.js";import{D as de,E as fe,R as pe,T as me,f as he,j as ge,p as _e,w as ve,x as ye}from"../chunks/HlY492D_.js";import{i as be,n as xe,t as Se}from"../chunks/BZg3JVyH.js";import{t as Ce}from"../chunks/DlGnnCJo.js";import{r as we,t as Te}from"../chunks/CQTKCwo-.js";var T=e({prerender:()=>!1,ssr:()=>!1}),Ee=s(``),De=s(`Archived`),Oe=s(`

            `),ke=s(`

            `),Ae=s(`

            Sign in to ClickClack

            Open ClickClack in a new tab, sign in, then return here. This panel will reconnect automatically.

            Open ClickClack
            `),je=s(`
            `),Me=s(`
            `),Ne=s(`
            `),Pe=s(`
            `),Fe=s(``),Ie=s(` `,1);function E(e,t){a(t,!0);let o=h(`loading`),s=h(``),x=h(null),T=new ve(()=>c(x)?.id||``),E=new de(He),D=h(null),O=h(null),k=h(ae([])),A=h(0),j=h(0),M=h(!1),N=h(!1),P=h(!1),F=h(``),I=h(null),Le=h(null),L=h(null),R=h(void 0),z=h(``),B=h(``),V=h(!1),H=h(null),U=h(null),W=null,G=0,Re=!1,K=null,q=h(ae([])),J=0,ze=null,Y=h(``),X=null,Z=new be(()=>[c(x)?.id,c(O)?.id].join(`:`)),Be=b(()=>{let e=new Map;for(let t of c(q))t.id&&!t.deleted_at&&e.set(t.id,t);for(let t of c(k))t.author?.id&&t.author.handle?.trim()&&!t.author.deleted_at&&e.set(t.author.id,t.author);return c(x)?.id&&e.set(c(x).id,c(x)),[...e.values()]});async function Ve(e){let t=++J;ze?.abort();let n=new AbortController;ze=n,g(Y,``),g(q,[],!0);try{let r=await Te({workspaceID:e,limit:100,signal:n.signal});t===J&&g(q,r.map(e=>e.user),!0)}catch(e){!n.signal.aborted&&t===J&&(g(q,[],!0),g(Y,we(e),!0))}}async function He(e,t){if(e===c(O)?.id){c(L)?.scrollToMessage(t.messageID);for(let e=0;e<16;e+=1){await f(),await new Promise(e=>requestAnimationFrame(()=>e()));let e=document.querySelector(`.embed-channel-shell`)?.querySelector(`[data-message-id="${CSS.escape(t.messageID)}"]`)?.querySelector(`textarea[aria-label="Edit message"]`);if(e){e.focus();return}}}}function Ue(e){g(k,c(k).map(Z.updateMessage(e)),!0)}function We(...e){let t=new Map;for(let n of e)for(let e of n)t.set(e.id,e);return[...t.values()].sort((e,t)=>(e.channel_seq||0)-(t.channel_seq||0))}function Q(e,t){t===`replace`&&g(R,void 0),T.seedMessages(e.messages),g(k,t===`replace`?e.messages:t===`prepend`?We(e.messages,c(k)):We(c(k),e.messages),!0),E.reconcile(c(O)?.id||``,c(k)),t===`replace`?(g(A,e.oldest_seq,!0),g(j,e.newest_seq,!0),g(M,e.has_older,!0),g(N,e.has_newer,!0)):(g(A,Math.min(c(A)||e.oldest_seq,e.oldest_seq||c(A)),!0),t===`prepend`&&g(M,e.has_older,!0),t===`append`&&(e.newest_seq>c(j)?g(N,e.has_newer,!0):e.newest_seq===c(j)&&g(N,c(N)||e.has_newer,!0)),g(j,Math.max(c(j),e.newest_seq),!0))}function Ge(){Z.clear(),K=null,g(V,!1),g(z,``),J+=1,ze?.abort(),W?.close(),W=null,g(D,null),g(O,null),T.clear(),E.clear(),g(k,[],!0),g(R,void 0),g(A,0),g(j,0),g(M,!1),g(N,!1),g(P,!1),X=null,g(I,null),g(U,null),g(H,null)}function Ke(e){if(Ge(),e instanceof me){g(o,`forbidden`);return}if(e instanceof C){if(e.status===401){g(o,`auth`);return}if(e.status===403){g(o,`forbidden`);return}if(e.status===404){g(o,`not-found`);return}}g(s,w(e,`Could not load this channel.`),!0),g(o,`error`)}async function qe(){if(Re)return;Re=!0;let e=++G;c(o)!==`auth`&&g(o,`loading`),g(s,``);try{let n=await ue(),r=await S(`/api/routes/${encodeURIComponent(t.workspaceRouteID)}/${encodeURIComponent(t.channelRouteID)}`);if(r.route.target_type!==`channel`)throw new C(404,`Channel route not found`);await Xe(r.route.workspace_id,r.route.target_id,e=>{c(x)&&c(x).id!==n.user.id&&g(F,``),g(x,n.user,!0),g(D,r.route,!0),Ve(r.route.workspace_id),g(O,e.channel,!0),Q(e,`replace`),g(o,`ready`),at(r.route.workspace_id)},()=>e===G)}catch(t){e===G&&Ke(t)}finally{e===G&&(Re=!1)}}async function Je(){if(!c(O)||c(P)||!c(M)||c(A)<=0)return;let e=c(O).id,t=G;g(P,!0);try{await Z.run(()=>S(`/api/channels/${encodeURIComponent(e)}/messages?before_seq=${encodeURIComponent(String(c(A)))}&limit=100`),e=>{g(R,c(L)?.captureState()??void 0,!0),Q(e,`prepend`)},()=>t===G&&c(O)?.id===e&&c(o)===`ready`)}catch(e){t===G&&g(z,w(e,`Could not load older messages.`),!0)}finally{t===G&&g(P,!1)}}async function Ye(){let e=G;if(!(X===e||!c(N))){X=e;try{await Qe(()=>e===G)}catch(t){e===G&&rt(t)}finally{X===e&&(X=null)}}}function Xe(e,t,n,r){return Z.run(async()=>{let[n,r]=await Promise.all([S(`/api/workspaces/${encodeURIComponent(e)}/channels`),S(`/api/channels/${encodeURIComponent(t)}/messages?limit=100`)]),i=n.channels.find(e=>e.id===t);if(!i)throw new C(404,`Channel not found`);return{...r,channel:i}},n,r)}async function Ze(e=()=>!0){if(!c(D)||!c(O)||c(o)!==`ready`)return;let t=c(D).workspace_id,n=c(O).id,r=G;await Xe(t,n,e=>{G++,Z.prune(),g(P,!1),X=null,g(O,e.channel,!0),Q(e,`replace`)},()=>e()&&r===G&&c(O)?.id===n&&c(o)===`ready`)}async function Qe(e=()=>!0){if(!c(O)||c(o)!==`ready`)return;let t=c(O).id,n=G,r=()=>e()&&n===G&&c(O)?.id===t&&c(o)===`ready`;try{let e=c(j);for(let n=0;n<20;n++){let n=await Z.run(()=>S(`/api/channels/${encodeURIComponent(t)}/messages?after_seq=${encodeURIComponent(String(e))}&limit=100`),e=>Q(e,`append`),r);if(!n||!r())return;let i=n.newest_seq||e;if(!n.has_newer||i<=e){it();return}e=i}throw Error(`Realtime message recovery exceeded its page limit`)}catch(e){if(!r())return;throw e}}async function $e(e,t=()=>!0){!c(k).some(t=>t.id===e)&&!Z.pending||await Z.run(()=>S(`/api/messages/${encodeURIComponent(e)}`),e=>{Ue(e.message),E.reconcile(c(O)?.id||``,c(k))},t)}async function et(e=()=>!0){if(!c(D)||!c(O))return;let t=await S(`/api/workspaces/${encodeURIComponent(c(D).workspace_id)}/channels`);if(!e())return;let n=t.channels.find(e=>e.id===c(O)?.id);if(!n)throw new C(404,`Channel not found`);g(O,n,!0)}function tt(e){return e.channel_id||e.payload.channel_id||``}async function nt(e,t){if(!(!c(O)||tt(e)!==c(O).id)){if(e.type===`message.created`){let n=e.seq||e.payload.seq||0;if(n>0&&n<=c(j))return;await Qe(t);return}if(e.type===`message.updated`||e.type===`message.deleted`){e.payload.message_id&&await $e(e.payload.message_id,t);return}if(e.type===`reaction.added`||e.type===`reaction.removed`){T.applyEvent(e);return}e.type===`channel.updated`&&await et(t)}}function rt(e){if(c(o)===`ready`){if(e instanceof me||e instanceof C&&[401,403,404].includes(e.status)){Ke(e);return}g(B,w(e,`Could not process a realtime update.`),!0),g(z,c(B),!0)}}function it(){c(z)===c(B)&&g(z,``),g(B,``)}function at(e){W?.close(),W=fe({workspaceID:e,onEvent:nt,onOpen:async(e,t)=>{t&&(T.clear(),await Ze(e)),e()&&it()},onError:rt})}async function ot(){let e=c(F).trim();if(!e||!c(O)||c(V))return;let t=c(O).id,n=c(I)?.id,r=K?.body===e&&K.quotedMessageID===n?K:{body:e,nonce:ge(),quotedMessageID:n};K=r,g(z,``),g(V,!0);let i;try{({message:i}=await S(`/api/channels/${encodeURIComponent(t)}/messages`,{method:`POST`,body:JSON.stringify({body:e,nonce:r.nonce,quoted_message_id:n})}))}catch(e){if(K!==r)return;if(e instanceof C&&e.status===401){Ke(e);return}g(z,w(e,`Could not send this message.`),!0);return}finally{K===r&&g(V,!1)}if(K!==r||c(O)?.id!==t||c(o)!==`ready`)return;K=null,g(k,We([i],c(k)),!0),c(F).trim()===e&&g(F,``),n&&c(I)?.id===n&&g(I,null);let a=G;Qe(()=>a===G).catch(e=>{a===G&&rt(e)}),await f(),a===G&&c(O)?.id===t&&c(o)===`ready`&&await c(L)?.scrollToBottom()}function st(e){if(e.key===`Escape`&&c(I)){e.preventDefault(),g(I,null);return}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ot())}function ct(e){c(V)||(g(I,e,!0),f().then(()=>c(Le)?.focus()))}function lt(e){e.quoted_message_id&&c(L)?.scrollToMessage(e.quoted_message_id)}function ut(e){if(!e.route_id)return;let n=window.open(`/app/${encodeURIComponent(t.workspaceRouteID)}/${encodeURIComponent(e.route_id)}`,`_blank`,`noopener,noreferrer`);n&&(n.opener=null)}function dt(e){let t=e.target;!(t instanceof HTMLImageElement)||!t.closest(`.markdown`)||(e.preventDefault(),g(H,{url:pe(t),title:t.alt||`Image`},!0))}function ft(e){let t=window.open(le(`/api/uploads/${e.id}`),`_blank`,`noopener,noreferrer`);t&&(t.opener=null)}function $(){c(o)===`auth`&&document.visibilityState===`visible`&&qe()}function pt(e){return e.showModal(),{destroy:()=>e.close()}}oe(()=>{qe(),window.addEventListener(`focus`,$),document.addEventListener(`visibilitychange`,$)}),ie(()=>{G+=1,Ge(),window.removeEventListener(`focus`,$),document.removeEventListener(`visibilitychange`,$)});var mt=Ie();i(`6awrv5`,e=>{var t=Ee();ee(e=>{se.title=e??``},[()=>c(O)?`#${Ce(c(O))} · ClickClack`:`ClickClack channel`]),u(e,t)});var ht=ce(mt),gt=e=>{var t=ke(),r=y(t),i=y(r),a=m(y(i),2),o=p(a,!0),s=m(a,2),ee=e=>{var t=De();u(e,t)};v(s,e=>{c(O).archived_at&&e(ee)}),n(i),n(r);var te=m(r,2);{let e=b(()=>c(x)?.id);xe(te,{get messages(){return c(k)},get selectedChannel(){return c(O)},get mentionPeople(){return c(Be)},get viewKey(){return c(O).id},get hasOlder(){return c(M)},get hasNewer(){return c(N)},get loadingOlder(){return c(P)},get restoreState(){return c(R)},get currentUserID(){return c(e)},get reactionController(){return T},get editController(){return E},get editScope(){return c(O).id},onMessageEdited:Ue,onListRef:e=>g(L,e,!0),onActivateMessageComposer:()=>{},onInlineImagePointerUp:dt,onOpenProfile:e=>g(U,e||null,!0),onReply:e=>ct(e),onOpenThread:ut,onJumpToQuote:lt,onOpenImage:(e,t)=>g(H,{url:e,title:t},!0),onOpenArtifact:ft,onLoadOlder:()=>void Je(),onLoadNewer:()=>void Ye()})}var d=m(te,2),ne=y(d),f=e=>{var t=Oe(),n=p(t);_(()=>l(n,`Mentions unavailable: ${c(Y)??``}`)),u(e,t)};v(ne,e=>{c(Y)&&e(f)});var h=m(ne,2),re=e=>{var t=Oe(),n=p(t,!0);_(()=>l(n,c(z))),u(e,t)};v(h,e=>{c(z)&&e(re)});var ie=m(h,2);{let e=b(()=>`Message #${Ce(c(O))}`);ye(ie,{get value(){return c(F)},get placeholder(){return c(e)},ariaLabel:`Message body`,submitLabel:`Send`,formClass:`composer embed-channel-composer`,get disabled(){return c(V)},get replyTarget(){return c(I)},showToolbar:!0,get mentionPeople(){return c(Be)},onValue:e=>g(F,e,!0),onSubmit:()=>void ot(),onKeydown:st,onFocus:()=>g(z,``),onInputRef:e=>g(Le,e,!0),onClearReply:()=>g(I,null)})}n(d),n(t),_(e=>l(o,e),[()=>Ce(c(O))]),u(e,t)},_t=e=>{var t=Ae(),r=y(t),i=y(r);he(i,{class:`embed-mark`,size:42}),re(6),n(r),n(t),u(e,t)},vt=e=>{var t=je();u(e,t)},yt=e=>{var t=Me();u(e,t)},bt=e=>{var t=Ne(),i=y(t),a=m(y(i),2),o=p(a,!0),ee=m(a,2);n(i),n(t),_(()=>l(o,c(s))),r(`click`,ee,()=>void qe()),u(e,t)},xt=e=>{var t=Pe();u(e,t)};v(ht,e=>{c(o)===`ready`&&c(O)&&c(D)?e(gt):c(o)===`auth`?e(_t,1):c(o)===`forbidden`?e(vt,2):c(o)===`not-found`?e(yt,3):c(o)===`error`?e(bt,4):e(xt,-1)});var St=m(ht,2),Ct=e=>{_e(e,{get url(){return c(H).url},get title(){return c(H).title},onClose:()=>g(H,null)})};v(St,e=>{c(H)&&e(Ct)});var wt=m(St,2),Tt=e=>{var t=Fe(),r=y(t);Se(r,{get profile(){return c(U)},get currentUser(){return c(x)},onClose:()=>g(U,null)}),n(t),te(t,e=>pt?.(e)),ne(`close`,t,()=>g(U,null)),u(e,t)};v(wt,e=>{c(U)&&e(Tt)}),u(e,mt),d()}x([`click`]);function D(e,n){a(n,!0);var r=o(),i=ce(r);t(i,()=>`${n.params.workspaceID}:${n.params.channelID}`,e=>{E(e,{get workspaceRouteID(){return n.params.workspaceID},get channelRouteID(){return n.params.channelID}})}),u(e,r),d()}export{D as component,T as universal}; \ No newline at end of file diff --git a/apps/api/internal/webassets/dist/_app/immutable/nodes/3.Bk3qR6j8.js b/apps/api/internal/webassets/dist/_app/immutable/nodes/3.BjKv85Xn.js similarity index 82% rename from apps/api/internal/webassets/dist/_app/immutable/nodes/3.Bk3qR6j8.js rename to apps/api/internal/webassets/dist/_app/immutable/nodes/3.BjKv85Xn.js index c1cb52060..4f4f12373 100644 --- a/apps/api/internal/webassets/dist/_app/immutable/nodes/3.Bk3qR6j8.js +++ b/apps/api/internal/webassets/dist/_app/immutable/nodes/3.BjKv85Xn.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../chunks/bE-mhUF5.js","../chunks/DK3Fl9T5.js","../chunks/CxKeDCcw.js","../chunks/ChC1oWd7.js","../chunks/Dt-HX3Vu.js","../chunks/HclGiUj8.js","../chunks/xihTtKlq.js","../chunks/qQG-ipvL.js","../chunks/Dsl_OP1c.js","../chunks/Y2iPPnRJ.js","../chunks/Qo16U5GS.js","../chunks/OQjxVT6U.js","../chunks/CYM1xkwL.js","../chunks/HlY492D_.js","../chunks/ZgTSXUg-.js","../assets/QuoteBlock.Bmfc9wvU.css","../chunks/CS_f1eMF.js","../chunks/DlGnnCJo.js","../chunks/DuOqi7WJ.js","../chunks/j7YOEK28.js","../assets/ThreadPanel.DFXp9CyT.css","../chunks/DNWg-bnz.js","../chunks/CQTKCwo-.js","../assets/ChatApp.BrxGlI__.css","../chunks/D3xoa4tU.js","../assets/ProductSite.BGg6Zt1K.css"])))=>i.map(i=>d[i]); -import{t as e}from"../chunks/DK3Fl9T5.js";import{F as t,K as n,M as r,P as i,ut as a,vt as o}from"../chunks/CxKeDCcw.js";import{t as s}from"../chunks/HclGiUj8.js";import"../chunks/xihTtKlq.js";import"../chunks/CYM1xkwL.js";var c=e({prerender:()=>!0});function l(e){let c=window.location.hostname.startsWith(`app.`)?s(()=>import(`../chunks/bE-mhUF5.js`).then(e=>e.n),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]),import.meta.url):s(()=>import(`../chunks/D3xoa4tU.js`),__vite__mapDeps([24,2,1,6,12,25]),import.meta.url);var l=t(),u=a(l);r(u,()=>c,null,(e,t)=>{let r=o(()=>n(t).default);n(r)(e,{})}),i(e,l)}export{l as component,c as universal}; \ No newline at end of file +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../chunks/Bi80bmu0.js","../chunks/DK3Fl9T5.js","../chunks/CxKeDCcw.js","../chunks/ChC1oWd7.js","../chunks/Dt-HX3Vu.js","../chunks/HclGiUj8.js","../chunks/xihTtKlq.js","../chunks/qQG-ipvL.js","../chunks/Dsl_OP1c.js","../chunks/Y2iPPnRJ.js","../chunks/Qo16U5GS.js","../chunks/OQjxVT6U.js","../chunks/CYM1xkwL.js","../chunks/HlY492D_.js","../chunks/ZgTSXUg-.js","../assets/QuoteBlock.Bmfc9wvU.css","../chunks/BZg3JVyH.js","../chunks/DlGnnCJo.js","../chunks/FDulIy0t.js","../chunks/j7YOEK28.js","../assets/ThreadPanel.DFXp9CyT.css","../chunks/DNWg-bnz.js","../chunks/CQTKCwo-.js","../assets/ChatApp.BrxGlI__.css","../chunks/D3xoa4tU.js","../assets/ProductSite.BGg6Zt1K.css"])))=>i.map(i=>d[i]); +import{t as e}from"../chunks/DK3Fl9T5.js";import{F as t,K as n,M as r,P as i,ut as a,vt as o}from"../chunks/CxKeDCcw.js";import{t as s}from"../chunks/HclGiUj8.js";import"../chunks/xihTtKlq.js";import"../chunks/CYM1xkwL.js";var c=e({prerender:()=>!0});function l(e){let c=window.location.hostname.startsWith(`app.`)?s(()=>import(`../chunks/Bi80bmu0.js`).then(e=>e.n),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]),import.meta.url):s(()=>import(`../chunks/D3xoa4tU.js`),__vite__mapDeps([24,2,1,6,12,25]),import.meta.url);var l=t(),u=a(l);r(u,()=>c,null,(e,t)=>{let r=o(()=>n(t).default);n(r)(e,{})}),i(e,l)}export{l as component,c as universal}; \ No newline at end of file diff --git a/apps/api/internal/webassets/dist/_app/immutable/nodes/4.B4ob5Fc_.js b/apps/api/internal/webassets/dist/_app/immutable/nodes/4.DWf1Rryr.js similarity index 63% rename from apps/api/internal/webassets/dist/_app/immutable/nodes/4.B4ob5Fc_.js rename to apps/api/internal/webassets/dist/_app/immutable/nodes/4.DWf1Rryr.js index 7b5a47b2a..eb3b1f628 100644 --- a/apps/api/internal/webassets/dist/_app/immutable/nodes/4.B4ob5Fc_.js +++ b/apps/api/internal/webassets/dist/_app/immutable/nodes/4.DWf1Rryr.js @@ -1 +1 @@ -import"../chunks/CxKeDCcw.js";import"../chunks/xihTtKlq.js";import"../chunks/CYM1xkwL.js";import{t as e}from"../chunks/bE-mhUF5.js";function t(t){e(t,{})}export{t as component}; \ No newline at end of file +import"../chunks/CxKeDCcw.js";import"../chunks/xihTtKlq.js";import"../chunks/CYM1xkwL.js";import{t as e}from"../chunks/Bi80bmu0.js";function t(t){e(t,{})}export{t as component}; \ No newline at end of file diff --git a/apps/api/internal/webassets/dist/_app/immutable/nodes/5.DbuY83i0.js b/apps/api/internal/webassets/dist/_app/immutable/nodes/5.RekE5Dhm.js similarity index 72% rename from apps/api/internal/webassets/dist/_app/immutable/nodes/5.DbuY83i0.js rename to apps/api/internal/webassets/dist/_app/immutable/nodes/5.RekE5Dhm.js index 269c6c53a..49ddfe9a8 100644 --- a/apps/api/internal/webassets/dist/_app/immutable/nodes/5.DbuY83i0.js +++ b/apps/api/internal/webassets/dist/_app/immutable/nodes/5.RekE5Dhm.js @@ -1 +1 @@ -import{Et as e,Tt as t}from"../chunks/CxKeDCcw.js";import"../chunks/xihTtKlq.js";import{t as n}from"../chunks/bE-mhUF5.js";function r(r,i){e(i,!0),n(r,{get routeWorkspaceID(){return i.params.workspaceID}}),t()}export{r as component}; \ No newline at end of file +import{Et as e,Tt as t}from"../chunks/CxKeDCcw.js";import"../chunks/xihTtKlq.js";import{t as n}from"../chunks/Bi80bmu0.js";function r(r,i){e(i,!0),n(r,{get routeWorkspaceID(){return i.params.workspaceID}}),t()}export{r as component}; \ No newline at end of file diff --git a/apps/api/internal/webassets/dist/_app/immutable/nodes/8.DQV6fdDu.js b/apps/api/internal/webassets/dist/_app/immutable/nodes/8.Mhs-olOD.js similarity index 99% rename from apps/api/internal/webassets/dist/_app/immutable/nodes/8.DQV6fdDu.js rename to apps/api/internal/webassets/dist/_app/immutable/nodes/8.Mhs-olOD.js index 5c689f59d..9df0a10bf 100644 --- a/apps/api/internal/webassets/dist/_app/immutable/nodes/8.DQV6fdDu.js +++ b/apps/api/internal/webassets/dist/_app/immutable/nodes/8.Mhs-olOD.js @@ -1,4 +1,4 @@ -import{t as e}from"../chunks/DK3Fl9T5.js";import{At as t,B as n,Et as r,F as i,I as a,K as o,L as s,N as c,O as l,P as u,R as d,Tt as f,V as p,Z as m,_ as h,at as g,b as _,c as v,dt as y,f as b,ft as x,g as S,gt as C,h as w,ht as T,it as E,j as D,jt as O,kt as k,l as A,lt as j,m as M,n as N,p as P,pt as F,u as I,ut as L,yt as R,z}from"../chunks/CxKeDCcw.js";import"../chunks/xihTtKlq.js";import{n as B,t as ee}from"../chunks/Dsl_OP1c.js";import{d as V}from"../chunks/Y2iPPnRJ.js";import{t as H}from"../chunks/OQjxVT6U.js";import{t as te}from"../chunks/DlGnnCJo.js";import{t as U}from"../chunks/DuOqi7WJ.js";import{a as W,f as ne,g as G,h as K,i as q,l as re,m as ie,n as J,o as ae,r as Y,s as oe,t as se,y as ce}from"../chunks/DNWg-bnz.js";import{n as le}from"../chunks/CQTKCwo-.js";import{t as ue}from"../chunks/Co6zx9gg.js";async function de(e){return(await B(`/api/workspaces/${e}/app-installations`)).app_installations??[]}async function fe(e,t){return(await B(`/api/workspaces/${e}/app-installations`,{method:`POST`,body:JSON.stringify(t)})).app_installation}async function pe(e,t={}){return B(`/api/app-installations/${e}/revoke`,{method:`POST`,body:JSON.stringify(t)})}async function me(e){return(await B(`/api/workspaces/${e}/slash-commands`)).slash_commands??[]}async function X(e,t){return(await B(`/api/workspaces/${e}/slash-commands`,{method:`POST`,body:JSON.stringify(t)})).slash_command}async function he(e){return(await B(`/api/slash-commands/${e}/revoke`,{method:`POST`,body:JSON.stringify({})})).slash_command}async function ge(e){return(await B(`/api/slash-commands/${e}/rotate-secret`,{method:`POST`,body:JSON.stringify({})})).slash_command}async function _e(e){return(await B(`/api/workspaces/${e}/event-subscriptions`)).event_subscriptions??[]}async function ve(e,t){return(await B(`/api/workspaces/${e}/event-subscriptions`,{method:`POST`,body:JSON.stringify(t)})).event_subscription}async function ye(e){return(await B(`/api/event-subscriptions/${e}/revoke`,{method:`POST`,body:JSON.stringify({})})).event_subscription}async function be(e){return(await B(`/api/event-subscriptions/${e}/rotate-secret`,{method:`POST`,body:JSON.stringify({})})).event_subscription}async function Z(e,t={}){let n=new URLSearchParams;t.limit&&n.set(`limit`,String(t.limit)),t.before&&n.set(`before`,t.before);let r=n.toString(),i=await B(`/api/event-subscriptions/${e}/deliveries${r?`?${r}`:``}`);return{deliveries:i.deliveries??[],next_cursor:i.next_cursor??null}}async function xe(e){return(await B(`/api/workspaces/${e}/connected-accounts`)).connected_accounts??[]}async function Se(e){return(await B(`/api/connected-accounts/${e}/revoke`,{method:`POST`,body:JSON.stringify({})})).connected_account}async function Ce(){return(await B(`/api/event-types`)).event_types??[]}function Q(e){if(e instanceof ee){if(e.status===401)return`Sign in to manage integrations.`;if(e.status===403)return`You don't have permission to manage integrations in this workspace.`;if(e.status===404)return`That integration is no longer available.`;if(e.status===400)return e.message||`That request is invalid.`}return e instanceof Error?e.message:`Something went wrong`}function we(e){return!!e.revoked_at}function Te(e){return e.filter(e=>!we(e))}function Ee(e,t){return e.filter(e=>e.app_installation_id===t)}function De(e){return e.filter(e=>!e.app_installation_id)}var Oe=e({load:()=>$,prerender:()=>!1,ssr:()=>!1});async function $({params:e,parent:t}){let{workspace:n}=await t(),r=n?.id??e.workspaceID,i=n?G(n):e.workspaceID,a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=null,p=``,[m,h,g,_,v,y,b,x]=await Promise.allSettled([de(r),me(r),_e(r),xe(r),K(r),B(`/api/workspaces/${r}/channels`),Ce(),V()]);m.status===`fulfilled`&&(a=m.value),h.status===`fulfilled`&&(o=h.value),g.status===`fulfilled`&&(s=g.value),_.status===`fulfilled`&&(c=_.value),v.status===`fulfilled`&&(l=v.value),y.status===`fulfilled`&&(u=y.value.channels??[]),b.status===`fulfilled`&&(d=b.value),x.status===`fulfilled`&&(f=x.value.user);let S=[m,h,g,_,v,y,b,x].filter(e=>e.status===`rejected`).map(e=>Q(e.reason));return S.length>0&&(p=`Some integration data could not be loaded. ${[...new Set(S)].join(` `)}`),{workspaceID:r,workspaceIdentifier:i,workspace:n,installations:a,commands:o,subscriptions:s,connectedAccounts:c,bots:l,channels:u,eventTypes:d,me:f,loaded:{installations:m.status===`fulfilled`,commands:h.status===`fulfilled`,subscriptions:g.status===`fulfilled`,connectedAccounts:_.status===`fulfilled`,bots:v.status===`fulfilled`,channels:y.status===`fulfilled`,eventTypes:b.status===`fulfilled`,me:x.status===`fulfilled`},loadError:p}}var ke=`agent_activity:write`,Ae=[{slug:`openclaw`,name:`OpenClaw`,description:`Connect an OpenClaw agent as a bot user. OpenClaw runs outside ClickClack and connects in over realtime using the bot token minted here.`,icon:[`M12 8V4H8`,`M5 4h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z`,`M9 13v2`,`M15 13v2`],suggestedScopeBundle:`bot:write`,suggestedBotName:`OpenClaw`,suggestedBotHandle:`openclaw`,configFields:[{id:`default_channel`,label:`Default channel`,hint:`Where the agent sends messages when no target is specified.`},{id:`allow_from`,label:`Who can talk to this agent`,hint:`Everyone in the workspace, or only specific members.`},{id:`agent_activity`,label:`Agent activity`,hint:`Stream the agent's thinking and tool progress into the conversation as it works. Grants the agent_activity:write token scope.`}],buildConfigSnippet:e=>W({workspace:e.workspace,botHandle:e.botHandle,botUserID:e.botUserID,mode:e.mode,defaultTo:e.defaultTo,allowFrom:e.allowFrom,agentActivity:e.agentActivity}),buildShellSnippet:e=>ae({botHandle:e.botHandle,token:e.token,mode:e.mode,workspace:e.workspace}),buildCodeSnippet:e=>q({code:e.setupCode??``,botHandle:e.botHandle,mode:e.mode,claimURL:e.setupClaimURL,apiBaseURL:e.apiBaseURL})},{slug:`custom`,name:`Custom app`,description:`Any external app or script that talks to the ClickClack API with a bot token. No platform-specific setup — you get the bot, the token, and the API.`,icon:[`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z`],suggestedScopeBundle:`bot:write`,suggestedBotName:``,suggestedBotHandle:``,configFields:[],buildConfigSnippet:null,buildShellSnippet:null,buildCodeSnippet:null}];function je(e){return Ae.find(t=>t.slug===e)}function Me(e){return je(e)??{slug:e,name:e,description:``,icon:[`M9 2v6`,`M15 2v6`,`M12 17v5`,`M5 8h14l-1 7a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4L5 8Z`],suggestedScopeBundle:`bot:write`,suggestedBotName:``,suggestedBotHandle:``,configFields:[],buildConfigSnippet:null,buildShellSnippet:null,buildCodeSnippet:null}}var Ne=s(``),Pe=a(``),Fe=a(`
            `,1),Ie=a(`
            Ownership
            `,1),Le=a(``),Re=a(``),ze=a(`
            How will you connect it?