var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, { get: (a3, b4) => (typeof require !== "undefined" ? require : a3)[b4] }) : x2)(function(x2) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x2 + '" is not supported'); }); var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require2() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to2, from2, except, desc) => { if (from2 && typeof from2 === "object" || typeof from2 === "function") { for (let key of __getOwnPropNames(from2)) if (!__hasOwnProp.call(to2, key) && key !== except) __defProp(to2, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable }); } return to2; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __decorateClass = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i7 = decorators.length - 1, decorator; i7 >= 0; i7--) if (decorator = decorators[i7]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; }; // scripts/process-shim.js var processShim, process_shim_default, process; var init_process_shim = __esm({ "scripts/process-shim.js"() { "use strict"; processShim = { browser: true, env: {}, cwd: () => "/", platform: "browser", version: "", versions: {}, argv: [], pid: 0, title: "browser", nextTick: (fn, ...args) => Promise.resolve().then(() => fn(...args)), stderr: {}, stdout: {}, stdin: {} }; process_shim_default = processShim; process = processShim; } }); // node_modules/@lit/reactive-element/css-tag.js var t, e, s, o, n, r, S, c; var init_css_tag = __esm({ "node_modules/@lit/reactive-element/css-tag.js"() { init_process_shim(); t = globalThis; e = t.ShadowRoot && (void 0 === t.ShadyCSS || t.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype; s = Symbol(); o = /* @__PURE__ */ new WeakMap(); n = class { constructor(t6, e9, o9) { if (this._$cssResult$ = true, o9 !== s) throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead."); this.cssText = t6, this.t = e9; } get styleSheet() { let t6 = this.o; const s6 = this.t; if (e && void 0 === t6) { const e9 = void 0 !== s6 && 1 === s6.length; e9 && (t6 = o.get(s6)), void 0 === t6 && ((this.o = t6 = new CSSStyleSheet()).replaceSync(this.cssText), e9 && o.set(s6, t6)); } return t6; } toString() { return this.cssText; } }; r = (t6) => new n("string" == typeof t6 ? t6 : t6 + "", void 0, s); S = (s6, o9) => { if (e) s6.adoptedStyleSheets = o9.map((t6) => t6 instanceof CSSStyleSheet ? t6 : t6.styleSheet); else for (const e9 of o9) { const o10 = document.createElement("style"), n7 = t.litNonce; void 0 !== n7 && o10.setAttribute("nonce", n7), o10.textContent = e9.cssText, s6.appendChild(o10); } }; c = e ? (t6) => t6 : (t6) => t6 instanceof CSSStyleSheet ? ((t7) => { let e9 = ""; for (const s6 of t7.cssRules) e9 += s6.cssText; return r(e9); })(t6) : t6; } }); // node_modules/@lit/reactive-element/reactive-element.js var i2, e2, h, r2, o2, n2, a, c2, l, p, d, u, f, b, y; var init_reactive_element = __esm({ "node_modules/@lit/reactive-element/reactive-element.js"() { init_process_shim(); init_css_tag(); init_css_tag(); ({ is: i2, defineProperty: e2, getOwnPropertyDescriptor: h, getOwnPropertyNames: r2, getOwnPropertySymbols: o2, getPrototypeOf: n2 } = Object); a = globalThis; c2 = a.trustedTypes; l = c2 ? c2.emptyScript : ""; p = a.reactiveElementPolyfillSupport; d = (t6, s6) => t6; u = { toAttribute(t6, s6) { switch (s6) { case Boolean: t6 = t6 ? l : null; break; case Object: case Array: t6 = null == t6 ? t6 : JSON.stringify(t6); } return t6; }, fromAttribute(t6, s6) { let i7 = t6; switch (s6) { case Boolean: i7 = null !== t6; break; case Number: i7 = null === t6 ? null : Number(t6); break; case Object: case Array: try { i7 = JSON.parse(t6); } catch (t7) { i7 = null; } } return i7; } }; f = (t6, s6) => !i2(t6, s6); b = { attribute: true, type: String, converter: u, reflect: false, useDefault: false, hasChanged: f }; Symbol.metadata ??= Symbol("metadata"), a.litPropertyMetadata ??= /* @__PURE__ */ new WeakMap(); y = class extends HTMLElement { static addInitializer(t6) { this._$Ei(), (this.l ??= []).push(t6); } static get observedAttributes() { return this.finalize(), this._$Eh && [...this._$Eh.keys()]; } static createProperty(t6, s6 = b) { if (s6.state && (s6.attribute = false), this._$Ei(), this.prototype.hasOwnProperty(t6) && ((s6 = Object.create(s6)).wrapped = true), this.elementProperties.set(t6, s6), !s6.noAccessor) { const i7 = Symbol(), h7 = this.getPropertyDescriptor(t6, i7, s6); void 0 !== h7 && e2(this.prototype, t6, h7); } } static getPropertyDescriptor(t6, s6, i7) { const { get: e9, set: r8 } = h(this.prototype, t6) ?? { get() { return this[s6]; }, set(t7) { this[s6] = t7; } }; return { get: e9, set(s7) { const h7 = e9?.call(this); r8?.call(this, s7), this.requestUpdate(t6, h7, i7); }, configurable: true, enumerable: true }; } static getPropertyOptions(t6) { return this.elementProperties.get(t6) ?? b; } static _$Ei() { if (this.hasOwnProperty(d("elementProperties"))) return; const t6 = n2(this); t6.finalize(), void 0 !== t6.l && (this.l = [...t6.l]), this.elementProperties = new Map(t6.elementProperties); } static finalize() { if (this.hasOwnProperty(d("finalized"))) return; if (this.finalized = true, this._$Ei(), this.hasOwnProperty(d("properties"))) { const t7 = this.properties, s6 = [...r2(t7), ...o2(t7)]; for (const i7 of s6) this.createProperty(i7, t7[i7]); } const t6 = this[Symbol.metadata]; if (null !== t6) { const s6 = litPropertyMetadata.get(t6); if (void 0 !== s6) for (const [t7, i7] of s6) this.elementProperties.set(t7, i7); } this._$Eh = /* @__PURE__ */ new Map(); for (const [t7, s6] of this.elementProperties) { const i7 = this._$Eu(t7, s6); void 0 !== i7 && this._$Eh.set(i7, t7); } this.elementStyles = this.finalizeStyles(this.styles); } static finalizeStyles(s6) { const i7 = []; if (Array.isArray(s6)) { const e9 = new Set(s6.flat(1 / 0).reverse()); for (const s7 of e9) i7.unshift(c(s7)); } else void 0 !== s6 && i7.push(c(s6)); return i7; } static _$Eu(t6, s6) { const i7 = s6.attribute; return false === i7 ? void 0 : "string" == typeof i7 ? i7 : "string" == typeof t6 ? t6.toLowerCase() : void 0; } constructor() { super(), this._$Ep = void 0, this.isUpdatePending = false, this.hasUpdated = false, this._$Em = null, this._$Ev(); } _$Ev() { this._$ES = new Promise((t6) => this.enableUpdating = t6), this._$AL = /* @__PURE__ */ new Map(), this._$E_(), this.requestUpdate(), this.constructor.l?.forEach((t6) => t6(this)); } addController(t6) { (this._$EO ??= /* @__PURE__ */ new Set()).add(t6), void 0 !== this.renderRoot && this.isConnected && t6.hostConnected?.(); } removeController(t6) { this._$EO?.delete(t6); } _$E_() { const t6 = /* @__PURE__ */ new Map(), s6 = this.constructor.elementProperties; for (const i7 of s6.keys()) this.hasOwnProperty(i7) && (t6.set(i7, this[i7]), delete this[i7]); t6.size > 0 && (this._$Ep = t6); } createRenderRoot() { const t6 = this.shadowRoot ?? this.attachShadow(this.constructor.shadowRootOptions); return S(t6, this.constructor.elementStyles), t6; } connectedCallback() { this.renderRoot ??= this.createRenderRoot(), this.enableUpdating(true), this._$EO?.forEach((t6) => t6.hostConnected?.()); } enableUpdating(t6) { } disconnectedCallback() { this._$EO?.forEach((t6) => t6.hostDisconnected?.()); } attributeChangedCallback(t6, s6, i7) { this._$AK(t6, i7); } _$ET(t6, s6) { const i7 = this.constructor.elementProperties.get(t6), e9 = this.constructor._$Eu(t6, i7); if (void 0 !== e9 && true === i7.reflect) { const h7 = (void 0 !== i7.converter?.toAttribute ? i7.converter : u).toAttribute(s6, i7.type); this._$Em = t6, null == h7 ? this.removeAttribute(e9) : this.setAttribute(e9, h7), this._$Em = null; } } _$AK(t6, s6) { const i7 = this.constructor, e9 = i7._$Eh.get(t6); if (void 0 !== e9 && this._$Em !== e9) { const t7 = i7.getPropertyOptions(e9), h7 = "function" == typeof t7.converter ? { fromAttribute: t7.converter } : void 0 !== t7.converter?.fromAttribute ? t7.converter : u; this._$Em = e9; const r8 = h7.fromAttribute(s6, t7.type); this[e9] = r8 ?? this._$Ej?.get(e9) ?? r8, this._$Em = null; } } requestUpdate(t6, s6, i7, e9 = false, h7) { if (void 0 !== t6) { const r8 = this.constructor; if (false === e9 && (h7 = this[t6]), i7 ??= r8.getPropertyOptions(t6), !((i7.hasChanged ?? f)(h7, s6) || i7.useDefault && i7.reflect && h7 === this._$Ej?.get(t6) && !this.hasAttribute(r8._$Eu(t6, i7)))) return; this.C(t6, s6, i7); } false === this.isUpdatePending && (this._$ES = this._$EP()); } C(t6, s6, { useDefault: i7, reflect: e9, wrapped: h7 }, r8) { i7 && !(this._$Ej ??= /* @__PURE__ */ new Map()).has(t6) && (this._$Ej.set(t6, r8 ?? s6 ?? this[t6]), true !== h7 || void 0 !== r8) || (this._$AL.has(t6) || (this.hasUpdated || i7 || (s6 = void 0), this._$AL.set(t6, s6)), true === e9 && this._$Em !== t6 && (this._$Eq ??= /* @__PURE__ */ new Set()).add(t6)); } async _$EP() { this.isUpdatePending = true; try { await this._$ES; } catch (t7) { Promise.reject(t7); } const t6 = this.scheduleUpdate(); return null != t6 && await t6, !this.isUpdatePending; } scheduleUpdate() { return this.performUpdate(); } performUpdate() { if (!this.isUpdatePending) return; if (!this.hasUpdated) { if (this.renderRoot ??= this.createRenderRoot(), this._$Ep) { for (const [t8, s7] of this._$Ep) this[t8] = s7; this._$Ep = void 0; } const t7 = this.constructor.elementProperties; if (t7.size > 0) for (const [s7, i7] of t7) { const { wrapped: t8 } = i7, e9 = this[s7]; true !== t8 || this._$AL.has(s7) || void 0 === e9 || this.C(s7, void 0, i7, e9); } } let t6 = false; const s6 = this._$AL; try { t6 = this.shouldUpdate(s6), t6 ? (this.willUpdate(s6), this._$EO?.forEach((t7) => t7.hostUpdate?.()), this.update(s6)) : this._$EM(); } catch (s7) { throw t6 = false, this._$EM(), s7; } t6 && this._$AE(s6); } willUpdate(t6) { } _$AE(t6) { this._$EO?.forEach((t7) => t7.hostUpdated?.()), this.hasUpdated || (this.hasUpdated = true, this.firstUpdated(t6)), this.updated(t6); } _$EM() { this._$AL = /* @__PURE__ */ new Map(), this.isUpdatePending = false; } get updateComplete() { return this.getUpdateComplete(); } getUpdateComplete() { return this._$ES; } shouldUpdate(t6) { return true; } update(t6) { this._$Eq &&= this._$Eq.forEach((t7) => this._$ET(t7, this[t7])), this._$EM(); } updated(t6) { } firstUpdated(t6) { } }; y.elementStyles = [], y.shadowRootOptions = { mode: "open" }, y[d("elementProperties")] = /* @__PURE__ */ new Map(), y[d("finalized")] = /* @__PURE__ */ new Map(), p?.({ ReactiveElement: y }), (a.reactiveElementVersions ??= []).push("2.1.2"); } }); // node_modules/lit-html/lit-html.js function V(t6, i7) { if (!u2(t6) || !t6.hasOwnProperty("raw")) throw Error("invalid template strings array"); return void 0 !== e3 ? e3.createHTML(i7) : i7; } function M(t6, i7, s6 = t6, e9) { if (i7 === E) return i7; let h7 = void 0 !== e9 ? s6._$Co?.[e9] : s6._$Cl; const o9 = a2(i7) ? void 0 : i7._$litDirective$; return h7?.constructor !== o9 && (h7?._$AO?.(false), void 0 === o9 ? h7 = void 0 : (h7 = new o9(t6), h7._$AT(t6, s6, e9)), void 0 !== e9 ? (s6._$Co ??= [])[e9] = h7 : s6._$Cl = h7), void 0 !== h7 && (i7 = M(t6, h7._$AS(t6, i7.values), h7, e9)), i7; } var t2, i3, s2, e3, h2, o3, n3, r3, l2, c3, a2, u2, d2, f2, v, _, m, p2, g, $2, y2, x, b2, w, T, E, A, C, P, N, S2, R, k, H, I, L, z, Z, j, B, D; var init_lit_html = __esm({ "node_modules/lit-html/lit-html.js"() { init_process_shim(); t2 = globalThis; i3 = (t6) => t6; s2 = t2.trustedTypes; e3 = s2 ? s2.createPolicy("lit-html", { createHTML: (t6) => t6 }) : void 0; h2 = "$lit$"; o3 = `lit$${Math.random().toFixed(9).slice(2)}$`; n3 = "?" + o3; r3 = `<${n3}>`; l2 = document; c3 = () => l2.createComment(""); a2 = (t6) => null === t6 || "object" != typeof t6 && "function" != typeof t6; u2 = Array.isArray; d2 = (t6) => u2(t6) || "function" == typeof t6?.[Symbol.iterator]; f2 = "[ \n\f\r]"; v = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g; _ = /-->/g; m = />/g; p2 = RegExp(`>|${f2}(?:([^\\s"'>=/]+)(${f2}*=${f2}*(?:[^ \f\r"'\`<>=]|("|')|))|$)`, "g"); g = /'/g; $2 = /"/g; y2 = /^(?:script|style|textarea|title)$/i; x = (t6) => (i7, ...s6) => ({ _$litType$: t6, strings: i7, values: s6 }); b2 = x(1); w = x(2); T = x(3); E = Symbol.for("lit-noChange"); A = Symbol.for("lit-nothing"); C = /* @__PURE__ */ new WeakMap(); P = l2.createTreeWalker(l2, 129); N = (t6, i7) => { const s6 = t6.length - 1, e9 = []; let n7, l5 = 2 === i7 ? "" : 3 === i7 ? "" : "")), e9]; }; S2 = class _S { constructor({ strings: t6, _$litType$: i7 }, e9) { let r8; this.parts = []; let l5 = 0, a3 = 0; const u5 = t6.length - 1, d4 = this.parts, [f4, v4] = N(t6, i7); if (this.el = _S.createElement(f4, e9), P.currentNode = this.el.content, 2 === i7 || 3 === i7) { const t7 = this.el.content.firstChild; t7.replaceWith(...t7.childNodes); } for (; null !== (r8 = P.nextNode()) && d4.length < u5; ) { if (1 === r8.nodeType) { if (r8.hasAttributes()) for (const t7 of r8.getAttributeNames()) if (t7.endsWith(h2)) { const i8 = v4[a3++], s6 = r8.getAttribute(t7).split(o3), e10 = /([.?@])?(.*)/.exec(i8); d4.push({ type: 1, index: l5, name: e10[2], strings: s6, ctor: "." === e10[1] ? I : "?" === e10[1] ? L : "@" === e10[1] ? z : H }), r8.removeAttribute(t7); } else t7.startsWith(o3) && (d4.push({ type: 6, index: l5 }), r8.removeAttribute(t7)); if (y2.test(r8.tagName)) { const t7 = r8.textContent.split(o3), i8 = t7.length - 1; if (i8 > 0) { r8.textContent = s2 ? s2.emptyScript : ""; for (let s6 = 0; s6 < i8; s6++) r8.append(t7[s6], c3()), P.nextNode(), d4.push({ type: 2, index: ++l5 }); r8.append(t7[i8], c3()); } } } else if (8 === r8.nodeType) if (r8.data === n3) d4.push({ type: 2, index: l5 }); else { let t7 = -1; for (; -1 !== (t7 = r8.data.indexOf(o3, t7 + 1)); ) d4.push({ type: 7, index: l5 }), t7 += o3.length - 1; } l5++; } } static createElement(t6, i7) { const s6 = l2.createElement("template"); return s6.innerHTML = t6, s6; } }; R = class { constructor(t6, i7) { this._$AV = [], this._$AN = void 0, this._$AD = t6, this._$AM = i7; } get parentNode() { return this._$AM.parentNode; } get _$AU() { return this._$AM._$AU; } u(t6) { const { el: { content: i7 }, parts: s6 } = this._$AD, e9 = (t6?.creationScope ?? l2).importNode(i7, true); P.currentNode = e9; let h7 = P.nextNode(), o9 = 0, n7 = 0, r8 = s6[0]; for (; void 0 !== r8; ) { if (o9 === r8.index) { let i8; 2 === r8.type ? i8 = new k(h7, h7.nextSibling, this, t6) : 1 === r8.type ? i8 = new r8.ctor(h7, r8.name, r8.strings, this, t6) : 6 === r8.type && (i8 = new Z(h7, this, t6)), this._$AV.push(i8), r8 = s6[++n7]; } o9 !== r8?.index && (h7 = P.nextNode(), o9++); } return P.currentNode = l2, e9; } p(t6) { let i7 = 0; for (const s6 of this._$AV) void 0 !== s6 && (void 0 !== s6.strings ? (s6._$AI(t6, s6, i7), i7 += s6.strings.length - 2) : s6._$AI(t6[i7])), i7++; } }; k = class _k { get _$AU() { return this._$AM?._$AU ?? this._$Cv; } constructor(t6, i7, s6, e9) { this.type = 2, this._$AH = A, this._$AN = void 0, this._$AA = t6, this._$AB = i7, this._$AM = s6, this.options = e9, this._$Cv = e9?.isConnected ?? true; } get parentNode() { let t6 = this._$AA.parentNode; const i7 = this._$AM; return void 0 !== i7 && 11 === t6?.nodeType && (t6 = i7.parentNode), t6; } get startNode() { return this._$AA; } get endNode() { return this._$AB; } _$AI(t6, i7 = this) { t6 = M(this, t6, i7), a2(t6) ? t6 === A || null == t6 || "" === t6 ? (this._$AH !== A && this._$AR(), this._$AH = A) : t6 !== this._$AH && t6 !== E && this._(t6) : void 0 !== t6._$litType$ ? this.$(t6) : void 0 !== t6.nodeType ? this.T(t6) : d2(t6) ? this.k(t6) : this._(t6); } O(t6) { return this._$AA.parentNode.insertBefore(t6, this._$AB); } T(t6) { this._$AH !== t6 && (this._$AR(), this._$AH = this.O(t6)); } _(t6) { this._$AH !== A && a2(this._$AH) ? this._$AA.nextSibling.data = t6 : this.T(l2.createTextNode(t6)), this._$AH = t6; } $(t6) { const { values: i7, _$litType$: s6 } = t6, e9 = "number" == typeof s6 ? this._$AC(t6) : (void 0 === s6.el && (s6.el = S2.createElement(V(s6.h, s6.h[0]), this.options)), s6); if (this._$AH?._$AD === e9) this._$AH.p(i7); else { const t7 = new R(e9, this), s7 = t7.u(this.options); t7.p(i7), this.T(s7), this._$AH = t7; } } _$AC(t6) { let i7 = C.get(t6.strings); return void 0 === i7 && C.set(t6.strings, i7 = new S2(t6)), i7; } k(t6) { u2(this._$AH) || (this._$AH = [], this._$AR()); const i7 = this._$AH; let s6, e9 = 0; for (const h7 of t6) e9 === i7.length ? i7.push(s6 = new _k(this.O(c3()), this.O(c3()), this, this.options)) : s6 = i7[e9], s6._$AI(h7), e9++; e9 < i7.length && (this._$AR(s6 && s6._$AB.nextSibling, e9), i7.length = e9); } _$AR(t6 = this._$AA.nextSibling, s6) { for (this._$AP?.(false, true, s6); t6 !== this._$AB; ) { const s7 = i3(t6).nextSibling; i3(t6).remove(), t6 = s7; } } setConnected(t6) { void 0 === this._$AM && (this._$Cv = t6, this._$AP?.(t6)); } }; H = class { get tagName() { return this.element.tagName; } get _$AU() { return this._$AM._$AU; } constructor(t6, i7, s6, e9, h7) { this.type = 1, this._$AH = A, this._$AN = void 0, this.element = t6, this.name = i7, this._$AM = e9, this.options = h7, s6.length > 2 || "" !== s6[0] || "" !== s6[1] ? (this._$AH = Array(s6.length - 1).fill(new String()), this.strings = s6) : this._$AH = A; } _$AI(t6, i7 = this, s6, e9) { const h7 = this.strings; let o9 = false; if (void 0 === h7) t6 = M(this, t6, i7, 0), o9 = !a2(t6) || t6 !== this._$AH && t6 !== E, o9 && (this._$AH = t6); else { const e10 = t6; let n7, r8; for (t6 = h7[0], n7 = 0; n7 < h7.length - 1; n7++) r8 = M(this, e10[s6 + n7], i7, n7), r8 === E && (r8 = this._$AH[n7]), o9 ||= !a2(r8) || r8 !== this._$AH[n7], r8 === A ? t6 = A : t6 !== A && (t6 += (r8 ?? "") + h7[n7 + 1]), this._$AH[n7] = r8; } o9 && !e9 && this.j(t6); } j(t6) { t6 === A ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, t6 ?? ""); } }; I = class extends H { constructor() { super(...arguments), this.type = 3; } j(t6) { this.element[this.name] = t6 === A ? void 0 : t6; } }; L = class extends H { constructor() { super(...arguments), this.type = 4; } j(t6) { this.element.toggleAttribute(this.name, !!t6 && t6 !== A); } }; z = class extends H { constructor(t6, i7, s6, e9, h7) { super(t6, i7, s6, e9, h7), this.type = 5; } _$AI(t6, i7 = this) { if ((t6 = M(this, t6, i7, 0) ?? A) === E) return; const s6 = this._$AH, e9 = t6 === A && s6 !== A || t6.capture !== s6.capture || t6.once !== s6.once || t6.passive !== s6.passive, h7 = t6 !== A && (s6 === A || e9); e9 && this.element.removeEventListener(this.name, this, s6), h7 && this.element.addEventListener(this.name, this, t6), this._$AH = t6; } handleEvent(t6) { "function" == typeof this._$AH ? this._$AH.call(this.options?.host ?? this.element, t6) : this._$AH.handleEvent(t6); } }; Z = class { constructor(t6, i7, s6) { this.element = t6, this.type = 6, this._$AN = void 0, this._$AM = i7, this.options = s6; } get _$AU() { return this._$AM._$AU; } _$AI(t6) { M(this, t6); } }; j = { M: h2, P: o3, A: n3, C: 1, L: N, R, D: d2, V: M, I: k, H, N: L, U: z, B: I, F: Z }; B = t2.litHtmlPolyfillSupport; B?.(S2, k), (t2.litHtmlVersions ??= []).push("3.3.2"); D = (t6, i7, s6) => { const e9 = s6?.renderBefore ?? i7; let h7 = e9._$litPart$; if (void 0 === h7) { const t7 = s6?.renderBefore ?? null; e9._$litPart$ = h7 = new k(i7.insertBefore(c3(), t7), t7, void 0, s6 ?? {}); } return h7._$AI(t6), h7; }; } }); // node_modules/lit-element/lit-element.js var s3, i4, o4; var init_lit_element = __esm({ "node_modules/lit-element/lit-element.js"() { init_process_shim(); init_reactive_element(); init_reactive_element(); init_lit_html(); init_lit_html(); s3 = globalThis; i4 = class extends y { constructor() { super(...arguments), this.renderOptions = { host: this }, this._$Do = void 0; } createRenderRoot() { const t6 = super.createRenderRoot(); return this.renderOptions.renderBefore ??= t6.firstChild, t6; } update(t6) { const r8 = this.render(); this.hasUpdated || (this.renderOptions.isConnected = this.isConnected), super.update(t6), this._$Do = D(r8, this.renderRoot, this.renderOptions); } connectedCallback() { super.connectedCallback(), this._$Do?.setConnected(true); } disconnectedCallback() { super.disconnectedCallback(), this._$Do?.setConnected(false); } render() { return E; } }; i4._$litElement$ = true, i4["finalized"] = true, s3.litElementHydrateSupport?.({ LitElement: i4 }); o4 = s3.litElementPolyfillSupport; o4?.({ LitElement: i4 }); (s3.litElementVersions ??= []).push("4.2.2"); } }); // node_modules/lit-html/is-server.js var init_is_server = __esm({ "node_modules/lit-html/is-server.js"() { init_process_shim(); } }); // node_modules/lit/index.js var init_lit = __esm({ "node_modules/lit/index.js"() { init_process_shim(); init_reactive_element(); init_lit_html(); init_lit_element(); init_is_server(); } }); // node_modules/lit-html/directive-helpers.js var t3, i5, r4, s4, v2, u3, m2, p3, M2, h3; var init_directive_helpers = __esm({ "node_modules/lit-html/directive-helpers.js"() { init_process_shim(); init_lit_html(); ({ I: t3 } = j); i5 = (o9) => o9; r4 = (o9) => void 0 === o9.strings; s4 = () => document.createComment(""); v2 = (o9, n7, e9) => { const l5 = o9._$AA.parentNode, d4 = void 0 === n7 ? o9._$AB : n7._$AA; if (void 0 === e9) { const i7 = l5.insertBefore(s4(), d4), n8 = l5.insertBefore(s4(), d4); e9 = new t3(i7, n8, o9, o9.options); } else { const t6 = e9._$AB.nextSibling, n8 = e9._$AM, c6 = n8 !== o9; if (c6) { let t7; e9._$AQ?.(o9), e9._$AM = o9, void 0 !== e9._$AP && (t7 = o9._$AU) !== n8._$AU && e9._$AP(t7); } if (t6 !== d4 || c6) { let o10 = e9._$AA; for (; o10 !== t6; ) { const t7 = i5(o10).nextSibling; i5(l5).insertBefore(o10, d4), o10 = t7; } } } return e9; }; u3 = (o9, t6, i7 = o9) => (o9._$AI(t6, i7), o9); m2 = {}; p3 = (o9, t6 = m2) => o9._$AH = t6; M2 = (o9) => o9._$AH; h3 = (o9) => { o9._$AR(), o9._$AA.remove(); }; } }); // node_modules/lit-html/directive.js var t4, e4, i6; var init_directive = __esm({ "node_modules/lit-html/directive.js"() { init_process_shim(); t4 = { ATTRIBUTE: 1, CHILD: 2, PROPERTY: 3, BOOLEAN_ATTRIBUTE: 4, EVENT: 5, ELEMENT: 6 }; e4 = (t6) => (...e9) => ({ _$litDirective$: t6, values: e9 }); i6 = class { constructor(t6) { } get _$AU() { return this._$AM._$AU; } _$AT(t6, e9, i7) { this._$Ct = t6, this._$AM = e9, this._$Ci = i7; } _$AS(t6, e9) { return this.update(t6, e9); } update(t6, e9) { return this.render(...e9); } }; } }); // node_modules/lit-html/async-directive.js function h4(i7) { void 0 !== this._$AN ? (o5(this), this._$AM = i7, r5(this)) : this._$AM = i7; } function n4(i7, t6 = false, e9 = 0) { const r8 = this._$AH, h7 = this._$AN; if (void 0 !== h7 && 0 !== h7.size) if (t6) if (Array.isArray(r8)) for (let i8 = e9; i8 < r8.length; i8++) s5(r8[i8], false), o5(r8[i8]); else null != r8 && (s5(r8, false), o5(r8)); else s5(this, i7); } var s5, o5, r5, c4, f3; var init_async_directive = __esm({ "node_modules/lit-html/async-directive.js"() { init_process_shim(); init_directive_helpers(); init_directive(); init_directive(); s5 = (i7, t6) => { const e9 = i7._$AN; if (void 0 === e9) return false; for (const i8 of e9) i8._$AO?.(t6, false), s5(i8, t6); return true; }; o5 = (i7) => { let t6, e9; do { if (void 0 === (t6 = i7._$AM)) break; e9 = t6._$AN, e9.delete(i7), i7 = t6; } while (0 === e9?.size); }; r5 = (i7) => { for (let t6; t6 = i7._$AM; i7 = t6) { let e9 = t6._$AN; if (void 0 === e9) t6._$AN = e9 = /* @__PURE__ */ new Set(); else if (e9.has(i7)) break; e9.add(i7), c4(t6); } }; c4 = (i7) => { i7.type == t4.CHILD && (i7._$AP ??= n4, i7._$AQ ??= h4); }; f3 = class extends i6 { constructor() { super(...arguments), this._$AN = void 0; } _$AT(i7, t6, e9) { super._$AT(i7, t6, e9), r5(this), this.isConnected = i7._$AU; } _$AO(i7, t6 = true) { i7 !== this.isConnected && (this.isConnected = i7, i7 ? this.reconnected?.() : this.disconnected?.()), t6 && (s5(this, i7), o5(this)); } setValue(t6) { if (r4(this._$Ct)) this._$Ct._$AI(t6, this); else { const i7 = [...this._$Ct._$AH]; i7[this._$Ci] = t6, this._$Ct._$AI(i7, this, 0); } } disconnected() { } reconnected() { } }; } }); // node_modules/lit-html/directives/ref.js var e5, h5, o6, n5; var init_ref = __esm({ "node_modules/lit-html/directives/ref.js"() { init_process_shim(); init_lit_html(); init_async_directive(); init_directive(); e5 = () => new h5(); h5 = class { }; o6 = /* @__PURE__ */ new WeakMap(); n5 = e4(class extends f3 { render(i7) { return A; } update(i7, [s6]) { const e9 = s6 !== this.G; return e9 && void 0 !== this.G && this.rt(void 0), (e9 || this.lt !== this.ct) && (this.G = s6, this.ht = i7.options?.host, this.rt(this.ct = i7.element)), A; } rt(t6) { if (this.isConnected || (t6 = void 0), "function" == typeof this.G) { const i7 = this.ht ?? globalThis; let s6 = o6.get(i7); void 0 === s6 && (s6 = /* @__PURE__ */ new WeakMap(), o6.set(i7, s6)), void 0 !== s6.get(this.G) && this.G.call(this.ht, void 0), s6.set(this.G, t6), void 0 !== t6 && this.G.call(this.ht, t6); } else this.G.value = t6; } get lt() { return "function" == typeof this.G ? o6.get(this.ht ?? globalThis)?.get(this.G) : this.G?.value; } disconnected() { this.lt === this.ct && this.rt(void 0); } reconnected() { this.rt(this.ct); } }); } }); // node_modules/lit/directives/ref.js var init_ref2 = __esm({ "node_modules/lit/directives/ref.js"() { init_process_shim(); init_ref(); } }); // ../mini-lit/dist/mini.js function fc(renderFn) { return (props) => renderFn(props || {}); } var init_mini = __esm({ "../mini-lit/dist/mini.js"() { "use strict"; init_process_shim(); init_lit(); init_ref2(); } }); // ../mini-lit/dist/component.js var init_component = __esm({ "../mini-lit/dist/component.js"() { "use strict"; init_process_shim(); init_lit(); init_mini(); init_mini(); } }); // ../mini-lit/dist/i18n.js function setTranslations(customTranslations) { userTranslations = customTranslations; translations = customTranslations; } function getCurrentLanguage() { const stored = localStorage.getItem("language"); if (stored && translations[stored]) { return stored; } const userLocale = navigator.language || navigator.userLanguage; const languageCode = userLocale ? userLocale.split("-")[0] : "en"; return translations[languageCode] ? languageCode : "en"; } function i18n(categoryOrKey, key) { const languageCode = getCurrentLanguage(); const implementation = translations[languageCode] || translations.en; if (key === void 0) { const value = implementation[categoryOrKey]; if (!value) { if (typeof value === "function") { return value; } console.error(`Unknown i18n key: ${categoryOrKey}`); return categoryOrKey; } return value; } else { const category = implementation[categoryOrKey]; if (!category || typeof category !== "object") { console.error(`Unknown i18n category: ${categoryOrKey}`); return key; } const value = category[key]; if (!value) { console.error(`Unknown i18n key: ${categoryOrKey}.${key}`); return key; } return value; } } var defaultEnglish, defaultGerman, userTranslations, translations, i18n_default; var init_i18n = __esm({ "../mini-lit/dist/i18n.js"() { "use strict"; init_process_shim(); defaultEnglish = { "*": "*", Copy: "Copy", "Copy code": "Copy code", "Copied!": "Copied!", Download: "Download", Close: "Close", Preview: "Preview", Code: "Code", "Loading...": "Loading...", "Select an option": "Select an option", "Mode 1": "Mode 1", "Mode 2": "Mode 2", Required: "Required", Optional: "Optional", "Input Required": "Input Required", Cancel: "Cancel", Confirm: "Confirm" }; defaultGerman = { "*": "*", Copy: "Kopieren", "Copy code": "Code kopieren", "Copied!": "Kopiert!", Download: "Herunterladen", Close: "Schlie\xDFen", Preview: "Vorschau", Code: "Code", "Loading...": "Laden...", "Select an option": "Option ausw\xE4hlen", "Mode 1": "Modus 1", "Mode 2": "Modus 2", Required: "Erforderlich", Optional: "Optional", "Input Required": "Eingabe erforderlich", Cancel: "Abbrechen", Confirm: "Best\xE4tigen" }; userTranslations = null; translations = { en: defaultEnglish, de: defaultGerman }; i18n_default = i18n; } }); // node_modules/lit-html/directives/unsafe-html.js var e6, o7; var init_unsafe_html = __esm({ "node_modules/lit-html/directives/unsafe-html.js"() { init_process_shim(); init_lit_html(); init_directive(); e6 = class extends i6 { constructor(i7) { if (super(i7), this.it = A, i7.type !== t4.CHILD) throw Error(this.constructor.directiveName + "() can only be used in child bindings"); } render(r8) { if (r8 === A || null == r8) return this._t = void 0, this.it = r8; if (r8 === E) return r8; if ("string" != typeof r8) throw Error(this.constructor.directiveName + "() called with a non-string value"); if (r8 === this.it) return this._t; this.it = r8; const s6 = [r8]; return s6.raw = s6, this._t = { _$litType$: this.constructor.resultType, strings: s6, values: [] }; } }; e6.directiveName = "unsafeHTML", e6.resultType = 1; o7 = e4(e6); } }); // node_modules/lit/directives/unsafe-html.js var init_unsafe_html2 = __esm({ "node_modules/lit/directives/unsafe-html.js"() { init_process_shim(); init_unsafe_html(); } }); // ../mini-lit/node_modules/lucide/dist/esm/defaultAttributes.js var defaultAttributes; var init_defaultAttributes = __esm({ "../mini-lit/node_modules/lucide/dist/esm/defaultAttributes.js"() { init_process_shim(); defaultAttributes = { xmlns: "http://www.w3.org/2000/svg", width: 24, height: 24, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round" }; } }); // ../mini-lit/node_modules/lucide/dist/esm/createElement.js var createSVGElement, createElement; var init_createElement = __esm({ "../mini-lit/node_modules/lucide/dist/esm/createElement.js"() { init_process_shim(); init_defaultAttributes(); createSVGElement = ([tag, attrs, children]) => { const element = document.createElementNS("http://www.w3.org/2000/svg", tag); Object.keys(attrs).forEach((name) => { element.setAttribute(name, String(attrs[name])); }); if (children?.length) { children.forEach((child) => { const childElement = createSVGElement(child); element.appendChild(childElement); }); } return element; }; createElement = (iconNode, customAttrs = {}) => { const tag = "svg"; const attrs = { ...defaultAttributes, ...customAttrs }; return createSVGElement([tag, attrs, iconNode]); }; } }); // ../mini-lit/node_modules/lucide/dist/esm/icons/check.js var Check; var init_check = __esm({ "../mini-lit/node_modules/lucide/dist/esm/icons/check.js"() { init_process_shim(); Check = [["path", { d: "M20 6 9 17l-5-5" }]]; } }); // ../mini-lit/node_modules/lucide/dist/esm/icons/code.js var Code; var init_code = __esm({ "../mini-lit/node_modules/lucide/dist/esm/icons/code.js"() { init_process_shim(); Code = [ ["path", { d: "m16 18 6-6-6-6" }], ["path", { d: "m8 6-6 6 6 6" }] ]; } }); // ../mini-lit/node_modules/lucide/dist/esm/icons/copy.js var Copy; var init_copy = __esm({ "../mini-lit/node_modules/lucide/dist/esm/icons/copy.js"() { init_process_shim(); Copy = [ ["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" }], ["path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" }] ]; } }); // ../mini-lit/node_modules/lucide/dist/esm/icons/download.js var Download; var init_download = __esm({ "../mini-lit/node_modules/lucide/dist/esm/icons/download.js"() { init_process_shim(); Download = [ ["path", { d: "M12 15V3" }], ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }], ["path", { d: "m7 10 5 5 5-5" }] ]; } }); // ../mini-lit/node_modules/lucide/dist/esm/icons/eye.js var Eye; var init_eye = __esm({ "../mini-lit/node_modules/lucide/dist/esm/icons/eye.js"() { init_process_shim(); Eye = [ [ "path", { d: "M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0" } ], ["circle", { cx: "12", cy: "12", r: "3" }] ]; } }); // ../mini-lit/node_modules/lucide/dist/esm/icons/monitor.js var Monitor; var init_monitor = __esm({ "../mini-lit/node_modules/lucide/dist/esm/icons/monitor.js"() { init_process_shim(); Monitor = [ ["rect", { width: "20", height: "14", x: "2", y: "3", rx: "2" }], ["line", { x1: "8", x2: "16", y1: "21", y2: "21" }], ["line", { x1: "12", x2: "12", y1: "17", y2: "21" }] ]; } }); // ../mini-lit/node_modules/lucide/dist/esm/icons/moon.js var Moon; var init_moon = __esm({ "../mini-lit/node_modules/lucide/dist/esm/icons/moon.js"() { init_process_shim(); Moon = [ [ "path", { d: "M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401" } ] ]; } }); // ../mini-lit/node_modules/lucide/dist/esm/icons/sun.js var Sun; var init_sun = __esm({ "../mini-lit/node_modules/lucide/dist/esm/icons/sun.js"() { init_process_shim(); Sun = [ ["circle", { cx: "12", cy: "12", r: "4" }], ["path", { d: "M12 2v2" }], ["path", { d: "M12 20v2" }], ["path", { d: "m4.93 4.93 1.41 1.41" }], ["path", { d: "m17.66 17.66 1.41 1.41" }], ["path", { d: "M2 12h2" }], ["path", { d: "M20 12h2" }], ["path", { d: "m6.34 17.66-1.41 1.41" }], ["path", { d: "m19.07 4.93-1.41 1.41" }] ]; } }); // ../mini-lit/node_modules/lucide/dist/esm/lucide.js var init_lucide = __esm({ "../mini-lit/node_modules/lucide/dist/esm/lucide.js"() { init_process_shim(); init_createElement(); init_check(); init_code(); init_copy(); init_download(); init_eye(); init_monitor(); init_moon(); init_sun(); } }); // ../mini-lit/dist/icons.js function icon(lucideIcon, size = "md", className) { return b2`${o7(iconDOM(lucideIcon, size, className).outerHTML)}`; } function iconDOM(lucideIcon, size = "md", className) { const element = createElement(lucideIcon, { class: sizeClasses[size] + (className ? " " + className : "") }); return element; } var sizeClasses; var init_icons = __esm({ "../mini-lit/dist/icons.js"() { "use strict"; init_process_shim(); init_lit(); init_unsafe_html2(); init_lucide(); sizeClasses = { xs: "w-3 h-3", sm: "w-4 h-4", md: "w-5 h-5", lg: "w-6 h-6", xl: "w-8 h-8" }; } }); // ../mini-lit/dist/index.js var init_dist = __esm({ "../mini-lit/dist/index.js"() { "use strict"; init_process_shim(); init_component(); init_i18n(); init_icons(); } }); // ../mini-lit/dist/Button.js var Button; var init_Button = __esm({ "../mini-lit/dist/Button.js"() { "use strict"; init_process_shim(); init_mini(); Button = fc(({ variant = "default", size = "md", disabled = false, type = "button", loading = false, onClick, title, className = "", children }) => { const sizeClasses2 = { sm: "h-8 rounded-md px-3 text-xs", md: "h-9 rounded-md px-4 text-sm", lg: "h-10 rounded-md px-8 text-sm", icon: "size-8 rounded-md" }; const variantClasses = { default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-xs hover:bg-destructive/90", outline: "border border-input bg-background text-foreground shadow-xs hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80", ghost: "text-foreground hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline" }; const baseClasses = "inline-flex items-center justify-center whitespace-nowrap text-sm font-medium transition-all cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"; const gapClass = size === "icon" ? "" : "gap-2"; const paddingAdjustClass = size === "icon" ? "" : "has-[>svg]:px-2.5"; const variantClass = variantClasses[variant] || variantClasses.default; const handleClick = (e9) => { if (disabled || loading) { e9.preventDefault(); e9.stopPropagation(); return; } onClick?.(e9); }; return b2` `; }); } }); // ../mini-lit/dist/Input.js var Input; var init_Input = __esm({ "../mini-lit/dist/Input.js"() { "use strict"; init_process_shim(); init_ref2(); init_i18n(); init_mini(); Input = fc(({ id = "", type = "text", size = "md", value = "", placeholder = "", label = "", error = "", disabled = false, readonly = false, required = false, name = "", autocomplete = "", min, max, step, inputRef, onInput, onChange, onKeyDown, onKeyUp, className = "" }) => { const sizeClasses2 = { sm: "h-8 px-3 py-1 text-sm", md: "h-9 px-3 py-1 text-sm md:text-sm", lg: "h-10 px-4 py-1 text-base" }; const baseClasses = "flex w-full min-w-0 rounded-md border bg-transparent text-foreground shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium"; const interactionClasses = "placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground"; const focusClasses = "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"; const darkClasses = "dark:bg-input/30"; const stateClasses = error ? "border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40" : "border-input"; const disabledClasses = "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"; const handleInput = (e9) => { onInput?.(e9); }; const handleChange = (e9) => { onChange?.(e9); }; return b2`
${description}
` : ""}\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index2).join("")) || { groups: {} };
if (groups.code !== void 0) {
const code2 = Number.parseFloat(groups.code);
escapeCode = code2 === END_CODE ? void 0 : code2;
} else if (groups.uri !== void 0) {
escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
}
}
const code = ansiStyles2.codes.get(Number(escapeCode));
if (pre[index2 + 1] === "\n") {
if (escapeUrl) {
returnValue += wrapAnsiHyperlink("");
}
if (escapeCode && code) {
returnValue += wrapAnsi(code);
}
} else if (character === "\n") {
if (escapeCode && code) {
returnValue += wrapAnsi(escapeCode);
}
if (escapeUrl) {
returnValue += wrapAnsiHyperlink(escapeUrl);
}
}
}
return returnValue;
};
wrapAnsi_1 = (string, columns, options) => {
return String(string).normalize().replace(/\r\n/g, "\n").split("\n").map((line) => exec(line, columns, options)).join("\n");
};
return wrapAnsi_1;
}
function requireBoxen() {
if (hasRequiredBoxen) return boxen$1.exports;
hasRequiredBoxen = 1;
const stringWidth2 = requireStringWidth();
const chalk$1 = import_chalk.default;
const widestLine2 = requireWidestLine();
const cliBoxes2 = requireCliBoxes();
const camelCase = requireCamelcase();
const ansiAlign = requireAnsiAlign();
const wrapAnsi = requireWrapAnsi();
const NL = "\n";
const PAD = " ";
const terminalColumns = () => {
const { env, stdout, stderr } = process;
if (stdout && stdout.columns) {
return stdout.columns;
}
if (stderr && stderr.columns) {
return stderr.columns;
}
if (env.COLUMNS) {
return Number.parseInt(env.COLUMNS, 10);
}
return 80;
};
const getObject = (detail) => {
return typeof detail === "number" ? {
top: detail,
right: detail * 3,
bottom: detail,
left: detail * 3
} : {
top: 0,
right: 0,
bottom: 0,
left: 0,
...detail
};
};
const getBorderChars = (borderStyle) => {
const sides = [
"topLeft",
"topRight",
"bottomRight",
"bottomLeft",
"vertical",
"horizontal"
];
let chararacters;
if (typeof borderStyle === "string") {
chararacters = cliBoxes2[borderStyle];
if (!chararacters) {
throw new TypeError(`Invalid border style: ${borderStyle}`);
}
} else {
for (const side of sides) {
if (!borderStyle[side] || typeof borderStyle[side] !== "string") {
throw new TypeError(`Invalid border style: ${side}`);
}
}
chararacters = borderStyle;
}
return chararacters;
};
const makeTitle = (text3, horizontal, alignement) => {
let title = "";
const textWidth = stringWidth2(text3);
switch (alignement) {
case "left":
title = text3 + horizontal.slice(textWidth);
break;
case "right":
title = horizontal.slice(textWidth) + text3;
break;
default:
horizontal = horizontal.slice(textWidth);
if (horizontal.length % 2 === 1) {
horizontal = horizontal.slice(Math.floor(horizontal.length / 2));
title = horizontal.slice(1) + text3 + horizontal;
} else {
horizontal = horizontal.slice(horizontal.length / 2);
title = horizontal + text3 + horizontal;
}
break;
}
return title;
};
const makeContentText = (text3, padding, columns, align) => {
text3 = ansiAlign(text3, { align });
let lines = text3.split(NL);
const textWidth = widestLine2(text3);
const max = columns - padding.left - padding.right;
if (textWidth > max) {
const newLines = [];
for (const line of lines) {
const createdLines = wrapAnsi(line, max, { hard: true });
const alignedLines = ansiAlign(createdLines, { align });
const alignedLinesArray = alignedLines.split("\n");
const longestLength = Math.max(...alignedLinesArray.map((s6) => stringWidth2(s6)));
for (const alignedLine of alignedLinesArray) {
let paddedLine;
switch (align) {
case "center":
paddedLine = PAD.repeat((max - longestLength) / 2) + alignedLine;
break;
case "right":
paddedLine = PAD.repeat(max - longestLength) + alignedLine;
break;
default:
paddedLine = alignedLine;
break;
}
newLines.push(paddedLine);
}
}
lines = newLines;
}
if (align === "center" && textWidth < max) {
lines = lines.map((line) => PAD.repeat((max - textWidth) / 2) + line);
} else if (align === "right" && textWidth < max) {
lines = lines.map((line) => PAD.repeat(max - textWidth) + line);
}
const paddingLeft = PAD.repeat(padding.left);
const paddingRight = PAD.repeat(padding.right);
lines = lines.map((line) => paddingLeft + line + paddingRight);
lines = lines.map((line) => {
if (columns - stringWidth2(line) > 0) {
switch (align) {
case "center":
return line + PAD.repeat(columns - stringWidth2(line));
case "right":
return line + PAD.repeat(columns - stringWidth2(line));
default:
return line + PAD.repeat(columns - stringWidth2(line));
}
}
return line;
});
if (padding.top > 0) {
lines = new Array(padding.top).fill(PAD.repeat(columns)).concat(lines);
}
if (padding.bottom > 0) {
lines = lines.concat(new Array(padding.bottom).fill(PAD.repeat(columns)));
}
return lines.join(NL);
};
const isHex = (color2) => color2.match(/^#(?:[0-f]{3}){1,2}$/i);
const isColorValid = (color2) => typeof color2 === "string" && (chalk$1[color2] || isHex(color2));
const getColorFn = (color2) => isHex(color2) ? chalk$1.hex(color2) : chalk$1[color2];
const getBGColorFn = (color2) => isHex(color2) ? chalk$1.bgHex(color2) : chalk$1[camelCase(["bg", color2])];
boxen$1.exports = (text3, options) => {
options = {
padding: 0,
borderStyle: "single",
dimBorder: false,
textAlignment: "left",
float: "left",
titleAlignment: "left",
...options
};
if (options.align) {
options.textAlignment = options.align;
}
const BORDERS_WIDTH = 2;
if (options.borderColor && !isColorValid(options.borderColor)) {
throw new Error(`${options.borderColor} is not a valid borderColor`);
}
if (options.backgroundColor && !isColorValid(options.backgroundColor)) {
throw new Error(`${options.backgroundColor} is not a valid backgroundColor`);
}
const chars = getBorderChars(options.borderStyle);
const padding = getObject(options.padding);
const margin = getObject(options.margin);
const colorizeBorder = (border) => {
const newBorder = options.borderColor ? getColorFn(options.borderColor)(border) : border;
return options.dimBorder ? chalk$1.dim(newBorder) : newBorder;
};
const colorizeContent = (content) => options.backgroundColor ? getBGColorFn(options.backgroundColor)(content) : content;
const columns = terminalColumns() - 1;
let contentWidth = widestLine2(wrapAnsi(text3, columns - BORDERS_WIDTH, { hard: true, trim: false })) + padding.left + padding.right;
let title = options.title && options.title.slice(0, columns - 4 - margin.left - margin.right);
if (title) {
title = ` ${title} `;
if (stringWidth2(title) > contentWidth) {
contentWidth = stringWidth2(title);
}
}
if (margin.left && margin.right && contentWidth + BORDERS_WIDTH + margin.left + margin.right > columns) {
const spaceForMargins = columns - contentWidth - BORDERS_WIDTH;
const multiplier = spaceForMargins / (margin.left + margin.right);
margin.left = Math.max(0, Math.floor(margin.left * multiplier));
margin.right = Math.max(0, Math.floor(margin.right * multiplier));
}
contentWidth = Math.min(contentWidth, columns - BORDERS_WIDTH - margin.left - margin.right);
text3 = makeContentText(text3, padding, contentWidth, options.textAlignment);
let marginLeft = PAD.repeat(margin.left);
if (options.float === "center") {
const marginWidth = Math.max((columns - contentWidth - BORDERS_WIDTH) / 2, 0);
marginLeft = PAD.repeat(marginWidth);
} else if (options.float === "right") {
const marginWidth = Math.max(columns - contentWidth - margin.right - BORDERS_WIDTH, 0);
marginLeft = PAD.repeat(marginWidth);
}
const horizontal = chars.horizontal.repeat(contentWidth);
const top = colorizeBorder(NL.repeat(margin.top) + marginLeft + chars.topLeft + (title ? makeTitle(title, horizontal, options.titleAlignment) : horizontal) + chars.topRight);
const bottom = colorizeBorder(marginLeft + chars.bottomLeft + horizontal + chars.bottomRight + NL.repeat(margin.bottom));
const side = colorizeBorder(chars.vertical);
const LINE_SEPARATOR = NL;
const lines = text3.split(NL);
const middle = lines.map((line) => {
return marginLeft + side + colorizeContent(line) + side;
}).join(LINE_SEPARATOR);
return top + LINE_SEPARATOR + middle + LINE_SEPARATOR + bottom;
};
boxen$1.exports._borderStyles = cliBoxes2;
return boxen$1.exports;
}
function makeTitledPrettyError(title, content, stack) {
return makePrettyError(import_chalk.default.redBright(title) + "\n\n" + content, stack);
}
function makePrettyError(content, stack) {
if (process_shim_default.browser || process_shim_default.env.LMS_NO_FANCY_ERRORS || (0, import_lms_isomorphic.terminalSize)().columns < 80) {
const error = new Error(content);
if (stack === void 0) {
changeErrorStackInPlace(error, "");
} else {
changeErrorStackInPlace(error, stack);
}
return error;
} else {
if (stack !== void 0) {
content += "\n\n\n " + import_chalk.default.bgWhite.black(" > STACK TRACE ") + "\n\n" + import_chalk.default.gray(stack);
}
const error = new Error("\n" + boxen(content, { padding: 1, margin: 1, borderColor: "redBright", title: "Error" }));
Object.defineProperty(error, "lmstudioRawError", { value: content, enumerable: false });
changeErrorStackInPlace(error, "");
return error;
}
}
function text(strings, ...values2) {
if (values2.length + 1 !== strings.length) {
throw new Error("text called with the wrong number of arguments.");
}
let compiled = compiledTemplatesCache.get(strings);
if (compiled === void 0) {
compiled = compile(strings);
compiledTemplatesCache.set(strings, compiled);
}
for (let i7 = 0; i7 < values2.length; i7++) {
if (typeof values2[i7] === "object") {
if (typeof values2[i7].stack === "string") {
compiled[i7 * 2 + 1] = values2[i7].stack;
} else {
try {
compiled[i7 * 2 + 1] = JSON.stringify(values2[i7]);
} catch (error) {
compiled[i7 * 2 + 1] = "[Object failed to stringify]";
}
}
} else {
compiled[i7 * 2 + 1] = String(values2[i7]);
}
}
return compiled.join("");
}
function removeLeadingNewlines(input) {
return input.replace(/^\n+/, "");
}
function removeTrailingNewlinesAndWhitespace(input) {
return input.replace(/[\n ]+$/, "");
}
function removeLeadingWhitespace(input) {
return input.replace(/^ +/, "");
}
function removeTrailingWhitespace(input) {
return input.replace(/ +$/, "");
}
function breakIntoLines(strings) {
const lines = [];
let currentLine = [];
for (const string of strings) {
let prevNewlineIndex = -1;
let nextNewlineIndex;
while ((nextNewlineIndex = string.indexOf("\n", prevNewlineIndex + 1)) !== -1) {
currentLine.push(string.substring(prevNewlineIndex + 1, nextNewlineIndex));
lines.push(currentLine);
currentLine = [];
prevNewlineIndex = nextNewlineIndex;
}
currentLine.push(string.substring(prevNewlineIndex + 1));
}
lines.push(currentLine);
return lines;
}
function countStringIndentations(string) {
let count = 0;
for (const char of string) {
if (char === " ") {
count++;
} else {
return count;
}
}
return Infinity;
}
function countLineIndentations(line) {
const firstPart = line[0];
const firstPartIndentation = countStringIndentations(firstPart);
if (firstPartIndentation === Infinity) {
if (line.length === 1) {
return Infinity;
} else {
return firstPart.length;
}
}
return firstPartIndentation;
}
function findMaxCommonIndentation(lines) {
let minIndentation = Infinity;
for (const line of lines) {
minIndentation = Math.min(minIndentation, countLineIndentations(line));
}
return minIndentation;
}
function removeIndentation(line, indentation) {
if (line.length < indentation) {
return "";
}
return line.slice(indentation);
}
function removeAllIndentation(lines, indentation) {
for (const line of lines) {
line[0] = removeIndentation(line[0], indentation);
}
}
function isEmptyLine(line) {
if (line.length !== 1) {
return false;
}
for (const char of line[0]) {
if (char !== " ") {
return false;
}
}
return true;
}
function mergeLines(lines) {
const linesAreEmpty = lines.map(isEmptyLine);
const paragraphs = [];
let currentParagraph = [];
for (let i7 = 0; i7 < lines.length; i7++) {
if (linesAreEmpty[i7]) {
if (currentParagraph.length !== 0) {
paragraphs.push(currentParagraph);
currentParagraph = [];
}
continue;
}
if (currentParagraph.length !== 0) {
const last = removeTrailingWhitespace(currentParagraph[currentParagraph.length - 1]);
const next = removeLeadingWhitespace(lines[i7][0]);
currentParagraph[currentParagraph.length - 1] = last + " " + next;
currentParagraph.push(...lines[i7].slice(1));
} else {
currentParagraph.push(...lines[i7]);
}
}
if (currentParagraph.length !== 0) {
paragraphs.push(currentParagraph);
}
return paragraphs;
}
function mergeParagraphs(paragraphs) {
const result = [];
if (paragraphs.length === 0) {
return [""];
}
result.push(...paragraphs[0]);
for (let i7 = 1; i7 < paragraphs.length; i7++) {
result[result.length - 1] += "\n\n" + paragraphs[i7][0];
result.push(...paragraphs[i7].slice(1));
}
return result;
}
function addHolesForVariables(strings) {
const result = [];
for (let i7 = 0; i7 < strings.length; i7++) {
result.push(strings[i7]);
if (i7 < strings.length - 1) {
result.push("");
}
}
return result;
}
function compile(readonlyStrings) {
const strings = [...readonlyStrings];
strings[0] = removeLeadingNewlines(strings[0]);
strings[strings.length - 1] = removeTrailingNewlinesAndWhitespace(strings[strings.length - 1]);
const lines = breakIntoLines(strings);
const commonIndentation = findMaxCommonIndentation(lines);
removeAllIndentation(lines, commonIndentation);
const paragraphs = mergeLines(lines);
return addHolesForVariables(mergeParagraphs(paragraphs));
}
function accessMaybeMutableInternals(maybeMutable) {
return maybeMutable;
}
function parseFileIdentifier(fileIdentifier) {
if (!fileIdentifier.includes(":")) {
fileIdentifier = `local:${fileIdentifier}`;
}
const colonIndex = fileIdentifier.indexOf(":");
const namespace = fileIdentifier.slice(0, colonIndex);
const content = fileIdentifier.slice(colonIndex + 1);
switch (namespace) {
case "local": {
if (content.includes("/") || content.includes("\\") || content.length === 0) {
throw new Error(`Invalid local file name: ${content}.`);
}
return {
type: "local",
fileName: content
};
}
case "base64": {
return {
type: "base64",
base64Data: content
};
}
default: {
throw new Error(`Unknown file identifier namespace: ${namespace}.`);
}
}
}
function promisifyAbortSignal(abortSignal) {
return new Promise((_resolve2, reject) => {
if (abortSignal.aborted) {
reject(abortSignal.reason);
return;
}
abortSignal.addEventListener("abort", () => {
reject(abortSignal.reason);
}, { once: true });
});
}
function raceWithAbortSignal(promise, abortSignal) {
return Promise.race([promise, promisifyAbortSignal(abortSignal)]);
}
function failOk(schema) {
return external_exports.any().transform((val2) => schema.safeParse(val2).success ? val2 : void 0);
}
function serializeError(error) {
if (typeof error === "object") {
const title = error.title ?? error.lmstudioRawError ?? error.message ?? "Unknown error";
return serializedLMSExtendedErrorSchema.parse({
title,
cause: error.cause,
suggestion: error.suggestion,
errorData: error.errorData,
displayData: error.displayData,
stack: error.stack,
rootTitle: title
});
} else {
const title = String(error);
return {
title,
rootTitle: title
};
}
}
function attachSerializedErrorData(error, serialized) {
const untypedError = error;
untypedError.title = serialized.title;
if (serialized.cause !== void 0) {
untypedError.cause = serialized.cause;
}
if (serialized.suggestion !== void 0) {
untypedError.suggestion = serialized.suggestion;
}
if (serialized.errorData !== void 0) {
untypedError.errorData = serialized.errorData;
}
}
function fromSerializedError(error, message = "Rehydrated error", replacementStack) {
const result = new Error(error.rootTitle);
attachSerializedErrorData(result, error);
if (error.displayData !== void 0) {
result.displayData = error.displayData;
}
if (replacementStack !== void 0) {
if (error.stack !== void 0) {
result.stack = `Error: ${message}
${replacementStack}
- Caused By: ${error.stack}`;
} else {
result.stack = `Error: ${message}
${replacementStack}`;
}
} else {
if (error.stack !== void 0) {
result.stack = `Error: ${message}
${result.stack.substring(error.stack.indexOf("\n") + 1)}
- Caused By: ` + error.stack;
} else {
result.message += ` - caused by error without stack (${error.title})`;
}
}
return result;
}
function convertGPUSettingToGPUSplitConfig(gpuSetting) {
return {
strategy: gpuSetting?.splitStrategy == "favorMainGpu" ? "priorityOrder" : gpuSetting?.splitStrategy ?? "evenly",
disabledGpus: gpuSetting?.disabledGpus ?? [],
priority: gpuSetting?.mainGpu ? [gpuSetting.mainGpu] : [],
customRatio: []
};
}
function safeCallCallback(logger2, name, callback2, args) {
if (callback2 === void 0) {
return;
}
try {
const maybePromise = callback2(...args);
if (typeof maybePromise === "object" && typeof maybePromise.catch === "function") {
maybePromise.catch((error) => {
logger2.error(`Error in the ${name} callback (triggered asynchronously):`, error);
});
}
} catch (error) {
logger2.error(`Error in the ${name} callback:`, error);
}
}
function isSimpleLogger(logger2) {
return logger2?.isSimpleLogger === true;
}
function isChatMessageInputAsOpposeToChatMessageData(chatMessageInput) {
return !Array.isArray(chatMessageInput.content);
}
function isChatMessageInputAsOpposeToChatHistoryData(chatMessageInput) {
return !("messages" in chatMessageInput);
}
function chatMessageInputToChatMessageData(chatMessageInput) {
const { role, content, images } = chatMessageInput;
const parts = [];
if (images === void 0 || images.length === 0) {
if (content === void 0) {
parts.push({
type: "text",
text: ""
});
}
} else {
for (const file of images) {
parts.push({
type: "file",
identifier: file.identifier,
name: file.name,
fileType: file.type,
sizeBytes: file.sizeBytes
});
}
}
if (content !== void 0) {
parts.push({
type: "text",
text: content
});
}
return {
role: role ?? "user",
content: parts
};
}
function kvConfigToMap(config) {
return new Map(config.fields.map((f4) => [f4.key, f4.value]));
}
function mapToKVConfig(map3) {
return {
fields: Array.from(map3.entries()).map(([key, value]) => ({ key, value }))
};
}
function collapseKVStackRaw(configs) {
const map3 = /* @__PURE__ */ new Map();
for (const config of configs) {
for (const { key, value } of config.fields) {
map3.set(key, value);
}
}
return mapToKVConfig(map3);
}
function singleLayerKVConfigStackOf(name, config) {
return {
layers: [
{
layerName: name,
config
}
]
};
}
function addKVConfigToStack(stack, newLayerName, newLayerConfig) {
return {
layers: [
...stack.layers,
{
layerName: newLayerName,
config: newLayerConfig
}
]
};
}
function deepEquals(a3, b4) {
if (a3 === b4) {
return true;
}
if (typeof a3 !== "object" || typeof b4 !== "object") {
return false;
}
if (a3 === null || b4 === null) {
return false;
}
if (Array.isArray(a3) !== Array.isArray(b4)) {
return false;
}
if (Array.isArray(a3)) {
if (a3.length !== b4?.length) {
return false;
}
for (let i7 = 0; i7 < a3.length; i7++) {
if (!deepEquals(a3[i7], b4[i7])) {
return false;
}
}
return true;
}
const aKeys = new Set(Object.keys(a3));
const bKeys = new Set(Object.keys(b4));
if (aKeys.size !== bKeys.size) {
return false;
}
for (const key of aKeys) {
if (!bKeys.has(key)) {
return false;
}
if (!deepEquals(a3[key], b4[key])) {
return false;
}
}
return true;
}
function quoteString(str2, empty) {
if (str2 === void 0 || str2 === "") {
return empty ?? '""';
}
return JSON.stringify(str2);
}
function quoteStringWithManualEscape(str2, empty) {
return quoteString(str2?.replace(/\\n/g, "\n"), empty);
}
function maybeFalseNumberToCheckboxNumeric(maybeFalseNumber, valueWhenUnchecked) {
if (maybeFalseNumber === void 0) {
return void 0;
}
if (maybeFalseNumber === false) {
return { checked: false, value: valueWhenUnchecked };
}
return { checked: true, value: maybeFalseNumber };
}
function llmPredictionConfigToKVConfig(config) {
const top = llmPredictionConfigSchematics.buildPartialConfig({
"temperature": config.temperature,
"contextOverflowPolicy": config.contextOverflowPolicy,
"maxPredictedTokens": maybeFalseNumberToCheckboxNumeric(config.maxTokens, 1),
"stopStrings": config.stopStrings,
"toolCallStopStrings": config.toolCallStopStrings,
"structured": config.structured,
"tools": config.rawTools,
"toolNaming": config.toolNaming,
"topKSampling": config.topKSampling,
"repeatPenalty": maybeFalseNumberToCheckboxNumeric(config.repeatPenalty, 1.1),
"minPSampling": maybeFalseNumberToCheckboxNumeric(config.minPSampling, 0.05),
"topPSampling": maybeFalseNumberToCheckboxNumeric(config.topPSampling, 0.95),
"llama.xtcProbability": maybeFalseNumberToCheckboxNumeric(config.xtcProbability, 0),
"llama.xtcThreshold": maybeFalseNumberToCheckboxNumeric(config.xtcThreshold, 0),
"logProbs": maybeFalseNumberToCheckboxNumeric(config.logProbs, 0),
"llama.cpuThreads": config.cpuThreads,
"promptTemplate": config.promptTemplate,
"speculativeDecoding.draftModel": config.draftModel,
"speculativeDecoding.numDraftTokensExact": config.speculativeDecodingNumDraftTokensExact,
"speculativeDecoding.minDraftLengthToConsider": config.speculativeDecodingMinDraftLengthToConsider,
"speculativeDecoding.minContinueDraftingProbability": config.speculativeDecodingMinContinueDraftingProbability,
"reasoning.parsing": config.reasoningParsing
});
if (config.raw !== void 0) {
return collapseKVStackRaw([config.raw, top]);
}
return top;
}
function requireHelpers() {
if (hasRequiredHelpers) return helpers;
hasRequiredHelpers = 1;
var ValidationError = helpers.ValidationError = function ValidationError2(message, instance, schema, path6, name, argument) {
if (Array.isArray(path6)) {
this.path = path6;
this.property = path6.reduce(function(sum, item) {
return sum + makeSuffix(item);
}, "instance");
} else if (path6 !== void 0) {
this.property = path6;
}
if (message) {
this.message = message;
}
if (schema) {
var id = schema.$id || schema.id;
this.schema = id || schema;
}
if (instance !== void 0) {
this.instance = instance;
}
this.name = name;
this.argument = argument;
this.stack = this.toString();
};
ValidationError.prototype.toString = function toString2() {
return this.property + " " + this.message;
};
var ValidatorResult = helpers.ValidatorResult = function ValidatorResult2(instance, schema, options, ctx) {
this.instance = instance;
this.schema = schema;
this.options = options;
this.path = ctx.path;
this.propertyPath = ctx.propertyPath;
this.errors = [];
this.throwError = options && options.throwError;
this.throwFirst = options && options.throwFirst;
this.throwAll = options && options.throwAll;
this.disableFormat = options && options.disableFormat === true;
};
ValidatorResult.prototype.addError = function addError(detail) {
var err;
if (typeof detail == "string") {
err = new ValidationError(detail, this.instance, this.schema, this.path);
} else {
if (!detail) throw new Error("Missing error detail");
if (!detail.message) throw new Error("Missing error message");
if (!detail.name) throw new Error("Missing validator type");
err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument);
}
this.errors.push(err);
if (this.throwFirst) {
throw new ValidatorResultError(this);
} else if (this.throwError) {
throw err;
}
return err;
};
ValidatorResult.prototype.importErrors = function importErrors(res) {
if (typeof res == "string" || res && res.validatorType) {
this.addError(res);
} else if (res && res.errors) {
this.errors = this.errors.concat(res.errors);
}
};
function stringizer(v4, i7) {
return i7 + ": " + v4.toString() + "\n";
}
ValidatorResult.prototype.toString = function toString2(res) {
return this.errors.map(stringizer).join("");
};
Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() {
return !this.errors.length;
} });
helpers.ValidatorResultError = ValidatorResultError;
function ValidatorResultError(result) {
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, ValidatorResultError);
}
this.instance = result.instance;
this.schema = result.schema;
this.options = result.options;
this.errors = result.errors;
}
ValidatorResultError.prototype = new Error();
ValidatorResultError.prototype.constructor = ValidatorResultError;
ValidatorResultError.prototype.name = "Validation Error";
var SchemaError = helpers.SchemaError = function SchemaError2(msg, schema) {
this.message = msg;
this.schema = schema;
Error.call(this, msg);
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, SchemaError2);
}
};
SchemaError.prototype = Object.create(
Error.prototype,
{
constructor: { value: SchemaError, enumerable: false },
name: { value: "SchemaError", enumerable: false }
}
);
var SchemaContext = helpers.SchemaContext = function SchemaContext2(schema, options, path6, base, schemas) {
this.schema = schema;
this.options = options;
if (Array.isArray(path6)) {
this.path = path6;
this.propertyPath = path6.reduce(function(sum, item) {
return sum + makeSuffix(item);
}, "instance");
} else {
this.propertyPath = path6;
}
this.base = base;
this.schemas = schemas;
};
SchemaContext.prototype.resolve = function resolve2(target) {
return (() => resolveUrl(this.base, target))();
};
SchemaContext.prototype.makeChild = function makeChild(schema, propertyName) {
var path6 = propertyName === void 0 ? this.path : this.path.concat([propertyName]);
var id = schema.$id || schema.id;
let base = (() => resolveUrl(this.base, id || ""))();
var ctx = new SchemaContext(schema, this.options, path6, base, Object.create(this.schemas));
if (id && !ctx.schemas[base]) {
ctx.schemas[base] = schema;
}
return ctx;
};
var FORMAT_REGEXPS = helpers.FORMAT_REGEXPS = {
// 7.3.1. Dates, Times, and Duration
"date-time": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,
"date": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,
"time": /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,
"duration": /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i,
// 7.3.2. Email Addresses
// TODO: fix the email production
"email": /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,
"idn-email": /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u,
// 7.3.3. Hostnames
// 7.3.4. IP Addresses
"ip-address": /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
// FIXME whitespace is invalid
"ipv6": /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,
// 7.3.5. Resource Identifiers
// TODO: A more accurate regular expression for "uri" goes:
// [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)?
"uri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
"uri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/,
"iri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
"iri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u,
"uuid": /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
// 7.3.6. uri-template
"uri-template": /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu,
// 7.3.7. JSON Pointers
"json-pointer": /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu,
"relative-json-pointer": /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu,
// hostname regex from: http://stackoverflow.com/a/1420225/5628
"hostname": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
"host-name": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
"utc-millisec": function(input) {
return typeof input === "string" && parseFloat(input) === parseInt(input, 10) && !isNaN(input);
},
// 7.3.8. regex
"regex": function(input) {
var result = true;
try {
new RegExp(input);
} catch (e9) {
result = false;
}
return result;
},
// Other definitions
// "style" was removed from JSON Schema in draft-4 and is deprecated
"style": /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/,
// "color" was removed from JSON Schema in draft-4 and is deprecated
"color": /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,
"phone": /^\+(?:[0-9] ?){6,14}[0-9]$/,
"alpha": /^[a-zA-Z]+$/,
"alphanumeric": /^[a-zA-Z0-9]+$/
};
FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex;
FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex;
FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS["ip-address"];
helpers.isFormat = function isFormat(input, format2, validator2) {
if (typeof input === "string" && FORMAT_REGEXPS[format2] !== void 0) {
if (FORMAT_REGEXPS[format2] instanceof RegExp) {
return FORMAT_REGEXPS[format2].test(input);
}
if (typeof FORMAT_REGEXPS[format2] === "function") {
return FORMAT_REGEXPS[format2](input);
}
} else if (validator2 && validator2.customFormats && typeof validator2.customFormats[format2] === "function") {
return validator2.customFormats[format2](input);
}
return true;
};
var makeSuffix = helpers.makeSuffix = function makeSuffix2(key) {
key = key.toString();
if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) {
return "." + key;
}
if (key.match(/^\d+$/)) {
return "[" + key + "]";
}
return "[" + JSON.stringify(key) + "]";
};
helpers.deepCompareStrict = function deepCompareStrict(a3, b4) {
if (typeof a3 !== typeof b4) {
return false;
}
if (Array.isArray(a3)) {
if (!Array.isArray(b4)) {
return false;
}
if (a3.length !== b4.length) {
return false;
}
return a3.every(function(v4, i7) {
return deepCompareStrict(a3[i7], b4[i7]);
});
}
if (typeof a3 === "object") {
if (!a3 || !b4) {
return a3 === b4;
}
var aKeys = Object.keys(a3);
var bKeys = Object.keys(b4);
if (aKeys.length !== bKeys.length) {
return false;
}
return aKeys.every(function(v4) {
return deepCompareStrict(a3[v4], b4[v4]);
});
}
return a3 === b4;
};
function deepMerger(target, dst, e9, i7) {
if (typeof e9 === "object") {
dst[i7] = deepMerge(target[i7], e9);
} else {
if (target.indexOf(e9) === -1) {
dst.push(e9);
}
}
}
function copyist(src, dst, key) {
dst[key] = src[key];
}
function copyistWithDeepMerge(target, src, dst, key) {
if (typeof src[key] !== "object" || !src[key]) {
dst[key] = src[key];
} else {
if (!target[key]) {
dst[key] = src[key];
} else {
dst[key] = deepMerge(target[key], src[key]);
}
}
}
function deepMerge(target, src) {
var array = Array.isArray(src);
var dst = array && [] || {};
if (array) {
target = target || [];
dst = dst.concat(target);
src.forEach(deepMerger.bind(null, target, dst));
} else {
if (target && typeof target === "object") {
Object.keys(target).forEach(copyist.bind(null, target, dst));
}
Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst));
}
return dst;
}
helpers.deepMerge = deepMerge;
helpers.objectGetPath = function objectGetPath(o9, s6) {
var parts = s6.split("/").slice(1);
var k2;
while (typeof (k2 = parts.shift()) == "string") {
var n7 = decodeURIComponent(k2.replace(/~0/, "~").replace(/~1/g, "/"));
if (!(n7 in o9)) return;
o9 = o9[n7];
}
return o9;
};
function pathEncoder(v4) {
return "/" + encodeURIComponent(v4).replace(/~/g, "%7E");
}
helpers.encodePath = function encodePointer(a3) {
return a3.map(pathEncoder).join("");
};
helpers.getDecimalPlaces = function getDecimalPlaces(number) {
var decimalPlaces = 0;
if (isNaN(number)) return decimalPlaces;
if (typeof number !== "number") {
number = Number(number);
}
var parts = number.toString().split("e");
if (parts.length === 2) {
if (parts[1][0] !== "-") {
return decimalPlaces;
} else {
decimalPlaces = Number(parts[1].slice(1));
}
}
var decimalParts = parts[0].split(".");
if (decimalParts.length === 2) {
decimalPlaces += decimalParts[1].length;
}
return decimalPlaces;
};
helpers.isSchema = function isSchema(val2) {
return typeof val2 === "object" && val2 || typeof val2 === "boolean";
};
var resolveUrl = helpers.resolveUrl = function resolveUrl2(from2, to2) {
const resolvedUrl = new URL(to2, new URL(from2, "resolve://"));
if (resolvedUrl.protocol === "resolve:") {
const { pathname, search: search2, hash } = resolvedUrl;
return pathname + search2 + hash;
}
return resolvedUrl.toString();
};
return helpers;
}
function requireAttribute() {
if (hasRequiredAttribute) return attribute_1;
hasRequiredAttribute = 1;
var helpers2 = requireHelpers();
var ValidatorResult = helpers2.ValidatorResult;
var SchemaError = helpers2.SchemaError;
var attribute = {};
attribute.ignoreProperties = {
// informative properties
"id": true,
"default": true,
"description": true,
"title": true,
// arguments to other properties
"additionalItems": true,
"then": true,
"else": true,
// special-handled properties
"$schema": true,
"$ref": true,
"extends": true
};
var validators = attribute.validators = {};
validators.type = function validateType(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
var result = new ValidatorResult(instance, schema, options, ctx);
var types2 = Array.isArray(schema.type) ? schema.type : [schema.type];
if (!types2.some(this.testType.bind(this, instance, schema, options, ctx))) {
var list = types2.map(function(v4) {
if (!v4) return;
var id = v4.$id || v4.id;
return id ? "<" + id + ">" : v4 + "";
});
result.addError({
name: "type",
argument: list,
message: "is not of a type(s) " + list
});
}
return result;
};
function testSchemaNoThrow(instance, options, ctx, callback2, schema) {
var throwError = options.throwError;
var throwAll = options.throwAll;
options.throwError = false;
options.throwAll = false;
var res = this.validateSchema(instance, schema, options, ctx);
options.throwError = throwError;
options.throwAll = throwAll;
if (!res.valid && callback2 instanceof Function) {
callback2(res);
}
return res.valid;
}
validators.anyOf = function validateAnyOf(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
var result = new ValidatorResult(instance, schema, options, ctx);
var inner2 = new ValidatorResult(instance, schema, options, ctx);
if (!Array.isArray(schema.anyOf)) {
throw new SchemaError("anyOf must be an array");
}
if (!schema.anyOf.some(
testSchemaNoThrow.bind(
this,
instance,
options,
ctx,
function(res) {
inner2.importErrors(res);
}
)
)) {
var list = schema.anyOf.map(function(v4, i7) {
var id = v4.$id || v4.id;
if (id) return "<" + id + ">";
return v4.title && JSON.stringify(v4.title) || v4["$ref"] && "<" + v4["$ref"] + ">" || "[subschema " + i7 + "]";
});
if (options.nestedErrors) {
result.importErrors(inner2);
}
result.addError({
name: "anyOf",
argument: list,
message: "is not any of " + list.join(",")
});
}
return result;
};
validators.allOf = function validateAllOf(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
if (!Array.isArray(schema.allOf)) {
throw new SchemaError("allOf must be an array");
}
var result = new ValidatorResult(instance, schema, options, ctx);
var self2 = this;
schema.allOf.forEach(function(v4, i7) {
var valid = self2.validateSchema(instance, v4, options, ctx);
if (!valid.valid) {
var id = v4.$id || v4.id;
var msg = id || v4.title && JSON.stringify(v4.title) || v4["$ref"] && "<" + v4["$ref"] + ">" || "[subschema " + i7 + "]";
result.addError({
name: "allOf",
argument: { id: msg, length: valid.errors.length, valid },
message: "does not match allOf schema " + msg + " with " + valid.errors.length + " error[s]:"
});
result.importErrors(valid);
}
});
return result;
};
validators.oneOf = function validateOneOf(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
if (!Array.isArray(schema.oneOf)) {
throw new SchemaError("oneOf must be an array");
}
var result = new ValidatorResult(instance, schema, options, ctx);
var inner2 = new ValidatorResult(instance, schema, options, ctx);
var count = schema.oneOf.filter(
testSchemaNoThrow.bind(
this,
instance,
options,
ctx,
function(res) {
inner2.importErrors(res);
}
)
).length;
var list = schema.oneOf.map(function(v4, i7) {
var id = v4.$id || v4.id;
return id || v4.title && JSON.stringify(v4.title) || v4["$ref"] && "<" + v4["$ref"] + ">" || "[subschema " + i7 + "]";
});
if (count !== 1) {
if (options.nestedErrors) {
result.importErrors(inner2);
}
result.addError({
name: "oneOf",
argument: list,
message: "is not exactly one from " + list.join(",")
});
}
return result;
};
validators.if = function validateIf(instance, schema, options, ctx) {
if (instance === void 0) return null;
if (!helpers2.isSchema(schema.if)) throw new Error('Expected "if" keyword to be a schema');
var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema.if);
var result = new ValidatorResult(instance, schema, options, ctx);
var res;
if (ifValid) {
if (schema.then === void 0) return;
if (!helpers2.isSchema(schema.then)) throw new Error('Expected "then" keyword to be a schema');
res = this.validateSchema(instance, schema.then, options, ctx.makeChild(schema.then));
result.importErrors(res);
} else {
if (schema.else === void 0) return;
if (!helpers2.isSchema(schema.else)) throw new Error('Expected "else" keyword to be a schema');
res = this.validateSchema(instance, schema.else, options, ctx.makeChild(schema.else));
result.importErrors(res);
}
return result;
};
function getEnumerableProperty(object, key) {
if (Object.hasOwnProperty.call(object, key)) return object[key];
if (!(key in object)) return;
while (object = Object.getPrototypeOf(object)) {
if (Object.propertyIsEnumerable.call(object, key)) return object[key];
}
}
validators.propertyNames = function validatePropertyNames(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var subschema = schema.propertyNames !== void 0 ? schema.propertyNames : {};
if (!helpers2.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)');
for (var property in instance) {
if (getEnumerableProperty(instance, property) !== void 0) {
var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema));
result.importErrors(res);
}
}
return result;
};
validators.properties = function validateProperties(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var properties = schema.properties || {};
for (var property in properties) {
var subschema = properties[property];
if (subschema === void 0) {
continue;
} else if (subschema === null) {
throw new SchemaError('Unexpected null, expected schema in "properties"');
}
if (typeof options.preValidateProperty == "function") {
options.preValidateProperty(instance, property, subschema, options, ctx);
}
var prop = getEnumerableProperty(instance, property);
var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property));
if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
result.importErrors(res);
}
return result;
};
function testAdditionalProperty(instance, schema, options, ctx, property, result) {
if (!this.types.object(instance)) return;
if (schema.properties && schema.properties[property] !== void 0) {
return;
}
if (schema.additionalProperties === false) {
result.addError({
name: "additionalProperties",
argument: property,
message: "is not allowed to have the additional property " + JSON.stringify(property)
});
} else {
var additionalProperties = schema.additionalProperties || {};
if (typeof options.preValidateProperty == "function") {
options.preValidateProperty(instance, property, additionalProperties, options, ctx);
}
var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property));
if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
result.importErrors(res);
}
}
validators.patternProperties = function validatePatternProperties(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var patternProperties = schema.patternProperties || {};
for (var property in instance) {
var test = true;
for (var pattern in patternProperties) {
var subschema = patternProperties[pattern];
if (subschema === void 0) {
continue;
} else if (subschema === null) {
throw new SchemaError('Unexpected null, expected schema in "patternProperties"');
}
try {
var regexp = new RegExp(pattern, "u");
} catch (_e2) {
regexp = new RegExp(pattern);
}
if (!regexp.test(property)) {
continue;
}
test = false;
if (typeof options.preValidateProperty == "function") {
options.preValidateProperty(instance, property, subschema, options, ctx);
}
var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property));
if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
result.importErrors(res);
}
if (test) {
testAdditionalProperty.call(this, instance, schema, options, ctx, property, result);
}
}
return result;
};
validators.additionalProperties = function validateAdditionalProperties(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
if (schema.patternProperties) {
return null;
}
var result = new ValidatorResult(instance, schema, options, ctx);
for (var property in instance) {
testAdditionalProperty.call(this, instance, schema, options, ctx, property, result);
}
return result;
};
validators.minProperties = function validateMinProperties(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var keys2 = Object.keys(instance);
if (!(keys2.length >= schema.minProperties)) {
result.addError({
name: "minProperties",
argument: schema.minProperties,
message: "does not meet minimum property length of " + schema.minProperties
});
}
return result;
};
validators.maxProperties = function validateMaxProperties(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var keys2 = Object.keys(instance);
if (!(keys2.length <= schema.maxProperties)) {
result.addError({
name: "maxProperties",
argument: schema.maxProperties,
message: "does not meet maximum property length of " + schema.maxProperties
});
}
return result;
};
validators.items = function validateItems(instance, schema, options, ctx) {
var self2 = this;
if (!this.types.array(instance)) return;
if (schema.items === void 0) return;
var result = new ValidatorResult(instance, schema, options, ctx);
instance.every(function(value, i7) {
if (Array.isArray(schema.items)) {
var items = schema.items[i7] === void 0 ? schema.additionalItems : schema.items[i7];
} else {
var items = schema.items;
}
if (items === void 0) {
return true;
}
if (items === false) {
result.addError({
name: "items",
message: "additionalItems not permitted"
});
return false;
}
var res = self2.validateSchema(value, items, options, ctx.makeChild(items, i7));
if (res.instance !== result.instance[i7]) result.instance[i7] = res.instance;
result.importErrors(res);
return true;
});
return result;
};
validators.contains = function validateContains(instance, schema, options, ctx) {
var self2 = this;
if (!this.types.array(instance)) return;
if (schema.contains === void 0) return;
if (!helpers2.isSchema(schema.contains)) throw new Error('Expected "contains" keyword to be a schema');
var result = new ValidatorResult(instance, schema, options, ctx);
var count = instance.some(function(value, i7) {
var res = self2.validateSchema(value, schema.contains, options, ctx.makeChild(schema.contains, i7));
return res.errors.length === 0;
});
if (count === false) {
result.addError({
name: "contains",
argument: schema.contains,
message: "must contain an item matching given schema"
});
}
return result;
};
validators.minimum = function validateMinimum(instance, schema, options, ctx) {
if (!this.types.number(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (schema.exclusiveMinimum && schema.exclusiveMinimum === true) {
if (!(instance > schema.minimum)) {
result.addError({
name: "minimum",
argument: schema.minimum,
message: "must be greater than " + schema.minimum
});
}
} else {
if (!(instance >= schema.minimum)) {
result.addError({
name: "minimum",
argument: schema.minimum,
message: "must be greater than or equal to " + schema.minimum
});
}
}
return result;
};
validators.maximum = function validateMaximum(instance, schema, options, ctx) {
if (!this.types.number(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (schema.exclusiveMaximum && schema.exclusiveMaximum === true) {
if (!(instance < schema.maximum)) {
result.addError({
name: "maximum",
argument: schema.maximum,
message: "must be less than " + schema.maximum
});
}
} else {
if (!(instance <= schema.maximum)) {
result.addError({
name: "maximum",
argument: schema.maximum,
message: "must be less than or equal to " + schema.maximum
});
}
}
return result;
};
validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema, options, ctx) {
if (typeof schema.exclusiveMinimum === "boolean") return;
if (!this.types.number(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var valid = instance > schema.exclusiveMinimum;
if (!valid) {
result.addError({
name: "exclusiveMinimum",
argument: schema.exclusiveMinimum,
message: "must be strictly greater than " + schema.exclusiveMinimum
});
}
return result;
};
validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema, options, ctx) {
if (typeof schema.exclusiveMaximum === "boolean") return;
if (!this.types.number(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var valid = instance < schema.exclusiveMaximum;
if (!valid) {
result.addError({
name: "exclusiveMaximum",
argument: schema.exclusiveMaximum,
message: "must be strictly less than " + schema.exclusiveMaximum
});
}
return result;
};
var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema, options, ctx, validationType, errorMessage) {
if (!this.types.number(instance)) return;
var validationArgument = schema[validationType];
if (validationArgument == 0) {
throw new SchemaError(validationType + " cannot be zero");
}
var result = new ValidatorResult(instance, schema, options, ctx);
var instanceDecimals = helpers2.getDecimalPlaces(instance);
var divisorDecimals = helpers2.getDecimalPlaces(validationArgument);
var maxDecimals = Math.max(instanceDecimals, divisorDecimals);
var multiplier = Math.pow(10, maxDecimals);
if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) {
result.addError({
name: validationType,
argument: validationArgument,
message: errorMessage + JSON.stringify(validationArgument)
});
}
return result;
};
validators.multipleOf = function validateMultipleOf(instance, schema, options, ctx) {
return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "multipleOf", "is not a multiple of (divisible by) ");
};
validators.divisibleBy = function validateDivisibleBy(instance, schema, options, ctx) {
return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "divisibleBy", "is not divisible by (multiple of) ");
};
validators.required = function validateRequired(instance, schema, options, ctx) {
var result = new ValidatorResult(instance, schema, options, ctx);
if (instance === void 0 && schema.required === true) {
result.addError({
name: "required",
message: "is required"
});
} else if (this.types.object(instance) && Array.isArray(schema.required)) {
schema.required.forEach(function(n7) {
if (getEnumerableProperty(instance, n7) === void 0) {
result.addError({
name: "required",
argument: n7,
message: "requires property " + JSON.stringify(n7)
});
}
});
}
return result;
};
validators.pattern = function validatePattern(instance, schema, options, ctx) {
if (!this.types.string(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var pattern = schema.pattern;
try {
var regexp = new RegExp(pattern, "u");
} catch (_e2) {
regexp = new RegExp(pattern);
}
if (!instance.match(regexp)) {
result.addError({
name: "pattern",
argument: schema.pattern,
message: "does not match pattern " + JSON.stringify(schema.pattern.toString())
});
}
return result;
};
validators.format = function validateFormat(instance, schema, options, ctx) {
if (instance === void 0) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (!result.disableFormat && !helpers2.isFormat(instance, schema.format, this)) {
result.addError({
name: "format",
argument: schema.format,
message: "does not conform to the " + JSON.stringify(schema.format) + " format"
});
}
return result;
};
validators.minLength = function validateMinLength(instance, schema, options, ctx) {
if (!this.types.string(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var hsp = instance.match(/[\uDC00-\uDFFF]/g);
var length = instance.length - (hsp ? hsp.length : 0);
if (!(length >= schema.minLength)) {
result.addError({
name: "minLength",
argument: schema.minLength,
message: "does not meet minimum length of " + schema.minLength
});
}
return result;
};
validators.maxLength = function validateMaxLength(instance, schema, options, ctx) {
if (!this.types.string(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var hsp = instance.match(/[\uDC00-\uDFFF]/g);
var length = instance.length - (hsp ? hsp.length : 0);
if (!(length <= schema.maxLength)) {
result.addError({
name: "maxLength",
argument: schema.maxLength,
message: "does not meet maximum length of " + schema.maxLength
});
}
return result;
};
validators.minItems = function validateMinItems(instance, schema, options, ctx) {
if (!this.types.array(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (!(instance.length >= schema.minItems)) {
result.addError({
name: "minItems",
argument: schema.minItems,
message: "does not meet minimum length of " + schema.minItems
});
}
return result;
};
validators.maxItems = function validateMaxItems(instance, schema, options, ctx) {
if (!this.types.array(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (!(instance.length <= schema.maxItems)) {
result.addError({
name: "maxItems",
argument: schema.maxItems,
message: "does not meet maximum length of " + schema.maxItems
});
}
return result;
};
function testArrays(v4, i7, a3) {
var j3, len = a3.length;
for (j3 = i7 + 1, len; j3 < len; j3++) {
if (helpers2.deepCompareStrict(v4, a3[j3])) {
return false;
}
}
return true;
}
validators.uniqueItems = function validateUniqueItems(instance, schema, options, ctx) {
if (schema.uniqueItems !== true) return;
if (!this.types.array(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (!instance.every(testArrays)) {
result.addError({
name: "uniqueItems",
message: "contains duplicate item"
});
}
return result;
};
validators.dependencies = function validateDependencies(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
for (var property in schema.dependencies) {
if (instance[property] === void 0) {
continue;
}
var dep = schema.dependencies[property];
var childContext = ctx.makeChild(dep, property);
if (typeof dep == "string") {
dep = [dep];
}
if (Array.isArray(dep)) {
dep.forEach(function(prop) {
if (instance[prop] === void 0) {
result.addError({
// FIXME there's two different "dependencies" errors here with slightly different outputs
// Can we make these the same? Or should we create different error types?
name: "dependencies",
argument: childContext.propertyPath,
message: "property " + prop + " not found, required by " + childContext.propertyPath
});
}
});
} else {
var res = this.validateSchema(instance, dep, options, childContext);
if (result.instance !== res.instance) result.instance = res.instance;
if (res && res.errors.length) {
result.addError({
name: "dependencies",
argument: childContext.propertyPath,
message: "does not meet dependency required by " + childContext.propertyPath
});
result.importErrors(res);
}
}
}
return result;
};
validators["enum"] = function validateEnum(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
if (!Array.isArray(schema["enum"])) {
throw new SchemaError("enum expects an array", schema);
}
var result = new ValidatorResult(instance, schema, options, ctx);
if (!schema["enum"].some(helpers2.deepCompareStrict.bind(null, instance))) {
result.addError({
name: "enum",
argument: schema["enum"],
message: "is not one of enum values: " + schema["enum"].map(String).join(",")
});
}
return result;
};
validators["const"] = function validateEnum(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
var result = new ValidatorResult(instance, schema, options, ctx);
if (!helpers2.deepCompareStrict(schema["const"], instance)) {
result.addError({
name: "const",
argument: schema["const"],
message: "does not exactly match expected constant: " + schema["const"]
});
}
return result;
};
validators.not = validators.disallow = function validateNot(instance, schema, options, ctx) {
var self2 = this;
if (instance === void 0) return null;
var result = new ValidatorResult(instance, schema, options, ctx);
var notTypes = schema.not || schema.disallow;
if (!notTypes) return null;
if (!Array.isArray(notTypes)) notTypes = [notTypes];
notTypes.forEach(function(type) {
if (self2.testType(instance, schema, options, ctx, type)) {
var id = type && (type.$id || type.id);
var schemaId = id || type;
result.addError({
name: "not",
argument: schemaId,
message: "is of prohibited type " + schemaId
});
}
});
return result;
};
attribute_1 = attribute;
return attribute_1;
}
function requireScan() {
if (hasRequiredScan) return scan;
hasRequiredScan = 1;
var helpers2 = requireHelpers();
scan.SchemaScanResult = SchemaScanResult;
function SchemaScanResult(found, ref) {
this.id = found;
this.ref = ref;
}
scan.scan = function scan2(base, schema) {
function scanSchema(baseuri, schema2) {
if (!schema2 || typeof schema2 != "object") return;
if (schema2.$ref) {
let resolvedUri = helpers2.resolveUrl(baseuri, schema2.$ref);
ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri] + 1 : 0;
return;
}
var id = schema2.$id || schema2.id;
let resolvedBase = helpers2.resolveUrl(baseuri, id);
var ourBase = id ? resolvedBase : baseuri;
if (ourBase) {
if (ourBase.indexOf("#") < 0) ourBase += "#";
if (found[ourBase]) {
if (!helpers2.deepCompareStrict(found[ourBase], schema2)) {
throw new Error("Schema <" + ourBase + "> already exists with different definition");
}
return found[ourBase];
}
found[ourBase] = schema2;
if (ourBase[ourBase.length - 1] == "#") {
found[ourBase.substring(0, ourBase.length - 1)] = schema2;
}
}
scanArray(ourBase + "/items", Array.isArray(schema2.items) ? schema2.items : [schema2.items]);
scanArray(ourBase + "/extends", Array.isArray(schema2.extends) ? schema2.extends : [schema2.extends]);
scanSchema(ourBase + "/additionalItems", schema2.additionalItems);
scanObject(ourBase + "/properties", schema2.properties);
scanSchema(ourBase + "/additionalProperties", schema2.additionalProperties);
scanObject(ourBase + "/definitions", schema2.definitions);
scanObject(ourBase + "/patternProperties", schema2.patternProperties);
scanObject(ourBase + "/dependencies", schema2.dependencies);
scanArray(ourBase + "/disallow", schema2.disallow);
scanArray(ourBase + "/allOf", schema2.allOf);
scanArray(ourBase + "/anyOf", schema2.anyOf);
scanArray(ourBase + "/oneOf", schema2.oneOf);
scanSchema(ourBase + "/not", schema2.not);
}
function scanArray(baseuri, schemas) {
if (!Array.isArray(schemas)) return;
for (var i7 = 0; i7 < schemas.length; i7++) {
scanSchema(baseuri + "/" + i7, schemas[i7]);
}
}
function scanObject(baseuri, schemas) {
if (!schemas || typeof schemas != "object") return;
for (var p4 in schemas) {
scanSchema(baseuri + "/" + p4, schemas[p4]);
}
}
var found = {};
var ref = {};
scanSchema(base, schema);
return new SchemaScanResult(found, ref);
};
return scan;
}
function requireValidator() {
if (hasRequiredValidator) return validator;
hasRequiredValidator = 1;
var attribute = requireAttribute();
var helpers2 = requireHelpers();
var scanSchema = requireScan().scan;
var ValidatorResult = helpers2.ValidatorResult;
var ValidatorResultError = helpers2.ValidatorResultError;
var SchemaError = helpers2.SchemaError;
var SchemaContext = helpers2.SchemaContext;
var anonymousBase = "/";
var Validator2 = function Validator3() {
this.customFormats = Object.create(Validator3.prototype.customFormats);
this.schemas = {};
this.unresolvedRefs = [];
this.types = Object.create(types2);
this.attributes = Object.create(attribute.validators);
};
Validator2.prototype.customFormats = {};
Validator2.prototype.schemas = null;
Validator2.prototype.types = null;
Validator2.prototype.attributes = null;
Validator2.prototype.unresolvedRefs = null;
Validator2.prototype.addSchema = function addSchema(schema, base) {
var self2 = this;
if (!schema) {
return null;
}
var scan2 = scanSchema(base || anonymousBase, schema);
var ourUri = base || schema.$id || schema.id;
for (var uri in scan2.id) {
this.schemas[uri] = scan2.id[uri];
}
for (var uri in scan2.ref) {
this.unresolvedRefs.push(uri);
}
this.unresolvedRefs = this.unresolvedRefs.filter(function(uri2) {
return typeof self2.schemas[uri2] === "undefined";
});
return this.schemas[ourUri];
};
Validator2.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) {
if (!Array.isArray(schemas)) return;
for (var i7 = 0; i7 < schemas.length; i7++) {
this.addSubSchema(baseuri, schemas[i7]);
}
};
Validator2.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) {
if (!schemas || typeof schemas != "object") return;
for (var p4 in schemas) {
this.addSubSchema(baseuri, schemas[p4]);
}
};
Validator2.prototype.setSchemas = function setSchemas(schemas) {
this.schemas = schemas;
};
Validator2.prototype.getSchema = function getSchema(urn) {
return this.schemas[urn];
};
Validator2.prototype.validate = function validate(instance, schema, options, ctx) {
if (typeof schema !== "boolean" && typeof schema !== "object" || schema === null) {
throw new SchemaError("Expected `schema` to be an object or boolean");
}
if (!options) {
options = {};
}
var id = schema.$id || schema.id;
let base = helpers2.resolveUrl(options.base, id || "");
if (!ctx) {
ctx = new SchemaContext(schema, options, [], base, Object.create(this.schemas));
if (!ctx.schemas[base]) {
ctx.schemas[base] = schema;
}
var found = scanSchema(base, schema);
for (var n7 in found.id) {
var sch = found.id[n7];
ctx.schemas[n7] = sch;
}
}
if (options.required && instance === void 0) {
var result = new ValidatorResult(instance, schema, options, ctx);
result.addError("is required, but is undefined");
return result;
}
var result = this.validateSchema(instance, schema, options, ctx);
if (!result) {
throw new Error("Result undefined");
} else if (options.throwAll && result.errors.length) {
throw new ValidatorResultError(result);
}
return result;
};
function shouldResolve(schema) {
var ref = typeof schema === "string" ? schema : schema.$ref;
if (typeof ref == "string") return ref;
return false;
}
Validator2.prototype.validateSchema = function validateSchema(instance, schema, options, ctx) {
var result = new ValidatorResult(instance, schema, options, ctx);
if (typeof schema === "boolean") {
if (schema === true) {
schema = {};
} else if (schema === false) {
schema = { type: [] };
}
} else if (!schema) {
throw new Error("schema is undefined");
}
if (schema["extends"]) {
if (Array.isArray(schema["extends"])) {
var schemaobj = { schema, ctx };
schema["extends"].forEach(this.schemaTraverser.bind(this, schemaobj));
schema = schemaobj.schema;
schemaobj.schema = null;
schemaobj.ctx = null;
schemaobj = null;
} else {
schema = helpers2.deepMerge(schema, this.superResolve(schema["extends"], ctx));
}
}
var switchSchema = shouldResolve(schema);
if (switchSchema) {
var resolved = this.resolve(schema, switchSchema, ctx);
var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas);
return this.validateSchema(instance, resolved.subschema, options, subctx);
}
var skipAttributes = options && options.skipAttributes || [];
for (var key in schema) {
if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) {
var validatorErr = null;
var validator2 = this.attributes[key];
if (validator2) {
validatorErr = validator2.call(this, instance, schema, options, ctx);
} else if (options.allowUnknownAttributes === false) {
throw new SchemaError("Unsupported attribute: " + key, schema);
}
if (validatorErr) {
result.importErrors(validatorErr);
}
}
}
if (typeof options.rewrite == "function") {
var value = options.rewrite.call(this, instance, schema, options, ctx);
result.instance = value;
}
return result;
};
Validator2.prototype.schemaTraverser = function schemaTraverser(schemaobj, s6) {
schemaobj.schema = helpers2.deepMerge(schemaobj.schema, this.superResolve(s6, schemaobj.ctx));
};
Validator2.prototype.superResolve = function superResolve(schema, ctx) {
var ref = shouldResolve(schema);
if (ref) {
return this.resolve(schema, ref, ctx).subschema;
}
return schema;
};
Validator2.prototype.resolve = function resolve2(schema, switchSchema, ctx) {
switchSchema = ctx.resolve(switchSchema);
if (ctx.schemas[switchSchema]) {
return { subschema: ctx.schemas[switchSchema], switchSchema };
}
let parsed = new URL(switchSchema, "thismessage::/");
let fragment2 = parsed.hash;
var document2 = fragment2 && fragment2.length && switchSchema.substr(0, switchSchema.length - fragment2.length);
if (!document2 || !ctx.schemas[document2]) {
throw new SchemaError("no such schema <" + switchSchema + ">", schema);
}
var subschema = helpers2.objectGetPath(ctx.schemas[document2], fragment2.substr(1));
if (subschema === void 0) {
throw new SchemaError("no such schema " + fragment2 + " located in <" + document2 + ">", schema);
}
return { subschema, switchSchema };
};
Validator2.prototype.testType = function validateType(instance, schema, options, ctx, type) {
if (type === void 0) {
return;
} else if (type === null) {
throw new SchemaError('Unexpected null in "type" keyword');
}
if (typeof this.types[type] == "function") {
return this.types[type].call(this, instance);
}
if (type && typeof type == "object") {
var res = this.validateSchema(instance, type, options, ctx);
return res === void 0 || !(res && res.errors.length);
}
return true;
};
var types2 = Validator2.prototype.types = {};
types2.string = function testString(instance) {
return typeof instance == "string";
};
types2.number = function testNumber(instance) {
return typeof instance == "number" && isFinite(instance);
};
types2.integer = function testInteger(instance) {
return typeof instance == "number" && instance % 1 === 0;
};
types2.boolean = function testBoolean(instance) {
return typeof instance == "boolean";
};
types2.array = function testArray(instance) {
return Array.isArray(instance);
};
types2["null"] = function testNull(instance) {
return instance === null;
};
types2.date = function testDate(instance) {
return instance instanceof Date;
};
types2.any = function testAny(instance) {
return true;
};
types2.object = function testObject(instance) {
return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date);
};
validator = Validator2;
return validator;
}
function requireLib() {
if (hasRequiredLib) return lib;
hasRequiredLib = 1;
var Validator2 = lib.Validator = requireValidator();
lib.ValidatorResult = requireHelpers().ValidatorResult;
lib.ValidatorResultError = requireHelpers().ValidatorResultError;
lib.ValidationError = requireHelpers().ValidationError;
lib.SchemaError = requireHelpers().SchemaError;
lib.SchemaScanResult = requireScan().SchemaScanResult;
lib.scan = requireScan().scan;
lib.validate = function(instance, schema, options) {
var v4 = new Validator2();
return v4.validate(instance, schema, options);
};
return lib;
}
function jsonSchemaValidationErrorToAIReadableText(root, validationErrors) {
return validationErrors.map((validatioNError) => {
const fullPath = [root, ...validatioNError.path].join(".");
return `${fullPath} ${validatioNError.message}`;
}).join("\n");
}
function internalCreateRemoteTool({ name, description, pluginIdentifier, parametersJsonSchema, implementation }) {
return {
name,
description,
type: "remoteTool",
pluginIdentifier,
parametersJsonSchema,
checkParameters: (params) => {
const jsonSchemaValidator = new libExports.Validator();
const validationResult = jsonSchemaValidator.validate(params, parametersJsonSchema);
if (validationResult.errors.length > 0) {
throw new Error(text`
Failed to parse arguments for tool "${name}":
${jsonSchemaValidationErrorToAIReadableText("params", validationResult.errors)}
`);
}
},
implementation
};
}
function functionToolToLLMTool(tool) {
return {
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: zodToJsonSchema(tool.parametersSchema)
}
};
}
function rawFunctionToolToLLMTool(tool) {
return {
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.parametersJsonSchema
}
};
}
function remoteToolToLLMTool(tool) {
return {
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.parametersJsonSchema
}
};
}
function toolToLLMTool(tool) {
const type = tool.type;
switch (type) {
case "function":
return functionToolToLLMTool(tool);
case "rawFunction":
case "unimplementedRawFunction":
return rawFunctionToolToLLMTool(tool);
case "remoteTool":
return remoteToolToLLMTool(tool);
default: {
const exhaustiveCheck = type;
throw new Error(`Unhandled type: ${exhaustiveCheck}`);
}
}
}
function valuesOfObj(record) {
if ("values" in Object) {
return Object.values(record);
}
var values2 = [];
for (var key in record) {
if (record.hasOwnProperty(key)) {
values2.push(record[key]);
}
}
return values2;
}
function find(record, predicate) {
var values2 = valuesOfObj(record);
if ("find" in values2) {
return values2.find(predicate);
}
var valuesNotNever = values2;
for (var i7 = 0; i7 < valuesNotNever.length; i7++) {
var value = valuesNotNever[i7];
if (predicate(value)) {
return value;
}
}
return void 0;
}
function forEach(record, run) {
Object.entries(record).forEach(function(_a7) {
var _b = __read$3(_a7, 2), key = _b[0], value = _b[1];
return run(value, key);
});
}
function includes(arr, value) {
return arr.indexOf(value) !== -1;
}
function findArr(record, predicate) {
for (var i7 = 0; i7 < record.length; i7++) {
var value = record[i7];
if (predicate(value)) {
return value;
}
}
return void 0;
}
function simpleTransformation(isApplicable, annotation, transform, untransform) {
return {
isApplicable,
annotation,
transform,
untransform
};
}
function compositeTransformation(isApplicable, annotation, transform, untransform) {
return {
isApplicable,
annotation,
transform,
untransform
};
}
function isInstanceOfRegisteredClass(potentialClass, superJson) {
if (potentialClass === null || potentialClass === void 0 ? void 0 : potentialClass.constructor) {
var isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
return isRegistered;
}
return false;
}
function validatePath(path6) {
if (includes(path6, "__proto__")) {
throw new Error("__proto__ is not allowed as a property");
}
if (includes(path6, "prototype")) {
throw new Error("prototype is not allowed as a property");
}
if (includes(path6, "constructor")) {
throw new Error("constructor is not allowed as a property");
}
}
function traverse(tree, walker2, origin) {
if (origin === void 0) {
origin = [];
}
if (!tree) {
return;
}
if (!isArray$1(tree)) {
forEach(tree, function(subtree, key) {
return traverse(subtree, walker2, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key))));
});
return;
}
var _a7 = __read$1(tree, 2), nodeValue = _a7[0], children = _a7[1];
if (children) {
forEach(children, function(child, key) {
traverse(child, walker2, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key))));
});
}
walker2(nodeValue, origin);
}
function applyValueAnnotations(plain, annotations, superJson) {
traverse(annotations, function(type, path6) {
plain = setDeep(plain, path6, function(v4) {
return untransformValue(v4, type, superJson);
});
});
return plain;
}
function applyReferentialEqualityAnnotations(plain, annotations) {
function apply(identicalPaths, path6) {
var object = getDeep(plain, parsePath(path6));
identicalPaths.map(parsePath).forEach(function(identicalObjectPath) {
plain = setDeep(plain, identicalObjectPath, function() {
return object;
});
});
}
if (isArray$1(annotations)) {
var _a7 = __read$1(annotations, 2), root = _a7[0], other = _a7[1];
root.forEach(function(identicalPath) {
plain = setDeep(plain, parsePath(identicalPath), function() {
return plain;
});
});
if (other) {
forEach(other, apply);
}
} else {
forEach(annotations, apply);
}
return plain;
}
function addIdentity(object, path6, identities) {
var existingSet = identities.get(object);
if (existingSet) {
existingSet.push(path6);
} else {
identities.set(object, [path6]);
}
}
function generateReferentialEqualityAnnotations(identitites, dedupe) {
var result = {};
var rootEqualityPaths = void 0;
identitites.forEach(function(paths) {
if (paths.length <= 1) {
return;
}
if (!dedupe) {
paths = paths.map(function(path6) {
return path6.map(String);
}).sort(function(a3, b4) {
return a3.length - b4.length;
});
}
var _a7 = __read$1(paths), representativePath = _a7[0], identicalPaths = _a7.slice(1);
if (representativePath.length === 0) {
rootEqualityPaths = identicalPaths.map(stringifyPath);
} else {
result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
}
});
if (rootEqualityPaths) {
if (isEmptyObject(result)) {
return [rootEqualityPaths];
} else {
return [rootEqualityPaths, result];
}
} else {
return isEmptyObject(result) ? void 0 : result;
}
}
function getType(payload) {
return Object.prototype.toString.call(payload).slice(8, -1);
}
function isArray4(payload) {
return getType(payload) === "Array";
}
function isPlainObject(payload) {
if (getType(payload) !== "Object")
return false;
const prototype = Object.getPrototypeOf(payload);
return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
}
function assignProp(carry2, key, newVal, originalObject, includeNonenumerable) {
const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
if (propType === "enumerable")
carry2[key] = newVal;
if (includeNonenumerable && propType === "nonenumerable") {
Object.defineProperty(carry2, key, {
value: newVal,
enumerable: false,
writable: true,
configurable: true
});
}
}
function copy(target, options = {}) {
if (isArray4(target)) {
return target.map((item) => copy(item, options));
}
if (!isPlainObject(target)) {
return target;
}
const props = Object.getOwnPropertyNames(target);
const symbols2 = Object.getOwnPropertySymbols(target);
return [...props, ...symbols2].reduce((carry2, key) => {
if (isArray4(options.props) && !options.props.includes(key)) {
return carry2;
}
const val2 = target[key];
const newVal = copy(val2, options);
assignProp(carry2, key, newVal, target, options.nonenumerable);
return carry2;
}, {});
}
function serialize(type, value) {
switch (type) {
case "raw":
return value;
case "superjson":
return serialize$1(value);
}
}
function deserialize(type, value) {
switch (type) {
case "raw":
return value;
case "superjson":
return deserialize$1(value);
}
}
function defaultErrorDeserializer(serialized, directCause, stack) {
return fromSerializedError(serialized, directCause, stack);
}
function getHostedEnv() {
let anyWindow;
try {
anyWindow = window;
} catch (error) {
anyWindow = void 0;
}
if (anyWindow !== void 0 && anyWindow.lmsHostedEnv !== void 0) {
return anyWindow.lmsHostedEnv;
}
return null;
}
function createBaseModelBackendInterface(specificModelInstanceInfoSchemaInput, specificModelInfoSchemaInput) {
const specificModelInstanceInfoSchema = specificModelInstanceInfoSchemaInput;
const specificModelInfoSchema = specificModelInfoSchemaInput;
return new BackendInterface().addChannelEndpoint("loadModel", {
creationParameter: external_exports.object({
modelKey: external_exports.string(),
identifier: external_exports.string().optional(),
/**
* If provided, when the model is not used for this amount of time, it will be unloaded.
*/
ttlMs: external_exports.number().int().min(1).optional(),
loadConfigStack: kvConfigStackSchema
}),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("resolved"),
info: specificModelInfoSchema,
ambiguous: external_exports.array(external_exports.string()).optional()
}),
external_exports.object({
type: external_exports.literal("progress"),
progress: external_exports.number()
}),
external_exports.object({
type: external_exports.literal("success"),
info: specificModelInstanceInfoSchema
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("cancel")
})
])
}).addRpcEndpoint("unloadModel", {
parameter: external_exports.object({
identifier: external_exports.string()
}),
returns: external_exports.void()
}).addRpcEndpoint("listLoaded", {
parameter: external_exports.undefined(),
returns: external_exports.array(specificModelInstanceInfoSchema)
}).addRpcEndpoint("getModelInfo", {
parameter: external_exports.object({
specifier: modelSpecifierSchema,
throwIfNotFound: external_exports.boolean()
}),
returns: specificModelInstanceInfoSchema.optional()
}).addRpcEndpoint("getLoadConfig", {
parameter: external_exports.object({
specifier: modelSpecifierSchema
}),
returns: kvConfigSchema
}).addChannelEndpoint("getOrLoad", {
creationParameter: external_exports.object({
identifier: external_exports.string(),
/**
* If provided and a new instance is loaded as a result of this call, it will be unloaded
* after idling for this amount of time.
*/
loadTtlMs: external_exports.number().int().min(1).optional(),
loadConfigStack: kvConfigStackSchema
}),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("alreadyLoaded"),
info: specificModelInstanceInfoSchema
}),
external_exports.object({
type: external_exports.literal("startLoading"),
identifier: external_exports.string(),
info: specificModelInfoSchema
}),
external_exports.object({
// We are unloading other JIT model
type: external_exports.literal("unloadingOtherJITModel"),
info: modelInstanceInfoSchema
}),
external_exports.object({
type: external_exports.literal("loadProgress"),
progress: external_exports.number()
}),
external_exports.object({
type: external_exports.literal("loadSuccess"),
info: specificModelInstanceInfoSchema
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("cancel")
})
])
});
}
function createDiagnosticsBackendInterface() {
return new BackendInterface().addChannelEndpoint("streamLogs", {
creationParameter: external_exports.void(),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("stop")
})
]),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("log"),
log: diagnosticsLogEventSchema
})
])
});
}
function createEmbeddingBackendInterface() {
const baseModelBackendInterface = createBaseModelBackendInterface(embeddingModelInstanceInfoSchema, embeddingModelInfoSchema);
return baseModelBackendInterface.addRpcEndpoint("embedString", {
parameter: external_exports.object({
modelSpecifier: modelSpecifierSchema,
inputString: external_exports.string()
}),
returns: external_exports.object({
embedding: external_exports.array(external_exports.number())
})
}).addRpcEndpoint("tokenize", {
parameter: external_exports.object({
specifier: modelSpecifierSchema,
inputString: external_exports.string()
}),
returns: external_exports.object({
tokens: external_exports.array(external_exports.number())
})
}).addRpcEndpoint("countTokens", {
parameter: external_exports.object({
specifier: modelSpecifierSchema,
inputString: external_exports.string()
}),
returns: external_exports.object({
tokenCount: external_exports.number().int()
})
});
}
function createFilesBackendInterface() {
return new BackendInterface().addRpcEndpoint("getLocalFileAbsolutePath", {
parameter: external_exports.object({
fileName: external_exports.string()
}),
returns: external_exports.object({
path: external_exports.string()
})
}).addRpcEndpoint("uploadFileBase64", {
parameter: external_exports.object({
name: external_exports.string(),
contentBase64: external_exports.string()
}),
returns: external_exports.object({
identifier: external_exports.string(),
fileType: fileTypeSchema,
sizeBytes: external_exports.number().int()
})
}).addChannelEndpoint("retrieve", {
creationParameter: external_exports.object({
query: external_exports.string(),
fileIdentifiers: external_exports.array(external_exports.string()),
config: kvConfigSchema
}),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("stop")
})
]),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("onFileProcessList"),
indices: external_exports.array(external_exports.number().int())
}),
external_exports.object({
type: external_exports.literal("onFileProcessingStart"),
index: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("onFileProcessingEnd"),
index: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("onFileProcessingStepStart"),
index: external_exports.number().int(),
step: retrievalFileProcessingStepSchema
}),
external_exports.object({
type: external_exports.literal("onFileProcessingStepProgress"),
index: external_exports.number().int(),
step: retrievalFileProcessingStepSchema,
progress: external_exports.number()
}),
external_exports.object({
type: external_exports.literal("onFileProcessingStepEnd"),
index: external_exports.number().int(),
step: retrievalFileProcessingStepSchema
}),
external_exports.object({
type: external_exports.literal("onSearchingStart")
}),
external_exports.object({
type: external_exports.literal("onSearchingEnd")
}),
external_exports.object({
type: external_exports.literal("result"),
result: internalRetrievalResultSchema
})
])
}).addChannelEndpoint("parseDocument", {
creationParameter: external_exports.object({
fileIdentifier: external_exports.string(),
parseOpts: documentParsingOptsSchema
}),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("parserLoaded"),
parser: documentParsingLibraryIdentifierSchema
}),
external_exports.object({
type: external_exports.literal("progress"),
progress: external_exports.number()
}),
external_exports.object({
type: external_exports.literal("result"),
content: external_exports.string(),
parser: documentParsingLibraryIdentifierSchema
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("cancel")
})
])
}).addRpcEndpoint("getDocumentParsingLibrary", {
parameter: external_exports.object({
fileIdentifier: external_exports.string()
}),
returns: external_exports.object({
library: external_exports.string(),
version: external_exports.string()
})
});
}
function createLlmBackendInterface() {
const baseModelBackendInterface = createBaseModelBackendInterface(llmInstanceInfoSchema, llmInfoSchema);
return baseModelBackendInterface.addChannelEndpoint("predict", {
creationParameter: external_exports.object({
modelSpecifier: modelSpecifierSchema,
history: chatHistoryDataSchema,
predictionConfigStack: kvConfigStackSchema,
/**
* Which preset to use. Supports limited fuzzy matching.
*/
fuzzyPresetIdentifier: external_exports.string().optional(),
ignoreServerSessionConfig: external_exports.boolean().optional()
}),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("fragment"),
fragment: llmPredictionFragmentSchema,
logprobs: external_exports.array(external_exports.array(external_exports.object({ text: external_exports.string(), logprob: external_exports.number() }))).optional()
}),
external_exports.object({
type: external_exports.literal("promptProcessingProgress"),
progress: external_exports.number()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationStart"),
/**
* The LLM specific call id of the tool call.
*/
toolCallId: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationNameReceived"),
name: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationArgumentFragmentGenerated"),
content: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationEnd"),
toolCallRequest: toolCallRequestSchema,
/**
* The raw output that represents this tool call. It is recommended to present this to
* the user as is, if desired.
*
* @remarks It is not guaranteed to be valid JSON as the model does not necessarily use
* JSON to represent tool calls.
*/
rawContent: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationFailed"),
error: serializedLMSExtendedErrorSchema,
/**
* The raw output that was generated by the model before the tool call. The exact nature
* of this fields depends on the error. It sometimes include the entire tool calls
* section, or sometimes just the single tool call that failed.
*
* It is recommended to present this to the user as is, if desired.
*/
rawContent: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("success"),
stats: llmPredictionStatsSchema,
modelInfo: llmInstanceInfoSchema,
loadModelConfig: kvConfigSchema,
predictionConfig: kvConfigSchema
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("cancel")
})
])
}).addRpcEndpoint("applyPromptTemplate", {
parameter: external_exports.object({
specifier: modelSpecifierSchema,
history: chatHistoryDataSchema,
predictionConfigStack: kvConfigStackSchema,
opts: llmApplyPromptTemplateOptsSchema
}),
returns: external_exports.object({
formatted: external_exports.string()
})
}).addRpcEndpoint("tokenize", {
parameter: external_exports.object({
specifier: modelSpecifierSchema,
inputString: external_exports.string()
}),
returns: external_exports.object({
tokens: external_exports.array(external_exports.number())
})
}).addRpcEndpoint("countTokens", {
parameter: external_exports.object({
specifier: modelSpecifierSchema,
inputString: external_exports.string()
}),
returns: external_exports.object({
tokenCount: external_exports.number().int()
})
}).addRpcEndpoint("preloadDraftModel", {
parameter: external_exports.object({
specifier: modelSpecifierSchema,
draftModelKey: external_exports.string()
}),
returns: external_exports.void()
});
}
function createPluginsBackendInterface() {
return new BackendInterface().addChannelEndpoint("startToolUseSession", {
creationParameter: external_exports.object({
pluginIdentifier: external_exports.string(),
pluginConfigSpecifier: pluginConfigSpecifierSchema
}),
toClientPacket: external_exports.discriminatedUnion("type", [
/**
* The session has been started successfully. The client can now use the session. Note,
* there are no sessionError message because if a session fails to start, the channel
* will error instead.
*/
external_exports.object({
type: external_exports.literal("sessionReady"),
toolDefinitions: external_exports.array(llmToolSchema)
}),
/**
* A tool call has been completed.
*/
external_exports.object({
type: external_exports.literal("toolCallComplete"),
callId: external_exports.number(),
result: jsonSerializableSchema
}),
/**
* A tool call has failed.
*/
external_exports.object({
type: external_exports.literal("toolCallError"),
callId: external_exports.number(),
error: serializedLMSExtendedErrorSchema
}),
/**
* Status update for a tool call.
*/
external_exports.object({
type: external_exports.literal("toolCallStatus"),
callId: external_exports.number(),
statusText: external_exports.string()
}),
/**
* Warning message for a tool call.
*/
external_exports.object({
type: external_exports.literal("toolCallWarn"),
callId: external_exports.number(),
warnText: external_exports.string()
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
/**
* Request to start a tool call. This call can be aborted using the `abortToolCall`
* packet. When the tool call is completed, either the `toolCallResult` or `toolCallError`
* packet will be sent.
*/
external_exports.object({
type: external_exports.literal("callTool"),
callId: external_exports.number(),
name: external_exports.string(),
arguments: jsonSerializableSchema
}),
/**
* Request to abort a tool call. Upon calling this, no toolCallComplete or toolCallError
* packets will be sent for the call. We assume abort is done immediately.
*/
external_exports.object({
type: external_exports.literal("abortToolCall"),
callId: external_exports.number()
}),
/**
* Client requests to discard the session. Upon calling this, the channel will be closed.
*/
external_exports.object({
type: external_exports.literal("discardSession")
})
])
}).addChannelEndpoint("generateWithGenerator", {
creationParameter: external_exports.object({
pluginIdentifier: external_exports.string(),
pluginConfigSpecifier: pluginConfigSpecifierSchema,
tools: external_exports.array(llmToolSchema),
history: chatHistoryDataSchema
}),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("fragment"),
fragment: llmPredictionFragmentSchema
}),
external_exports.object({
type: external_exports.literal("promptProcessingProgress"),
progress: external_exports.number()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationStart"),
/**
* The LLM specific call id of the tool call.
*/
toolCallId: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationNameReceived"),
name: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationArgumentFragmentGenerated"),
content: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationEnd"),
toolCallRequest: toolCallRequestSchema
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationFailed")
}),
external_exports.object({
type: external_exports.literal("success")
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("cancel")
})
])
}).addChannelEndpoint("registerDevelopmentPlugin", {
creationParameter: external_exports.object({
manifest: pluginManifestSchema
}),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("ready"),
clientIdentifier: external_exports.string(),
clientPasskey: external_exports.string()
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("end")
})
])
}).addRpcEndpoint("reindexPlugins", {
parameter: external_exports.void(),
returns: external_exports.void()
}).addChannelEndpoint("setPromptPreprocessor", {
creationParameter: external_exports.void(),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("preprocess"),
taskId: external_exports.string(),
input: chatMessageDataSchema,
config: kvConfigSchema,
pluginConfig: kvConfigSchema,
globalPluginConfig: kvConfigSchema,
workingDirectoryPath: external_exports.string().nullable(),
/**
* An array of all the plugins that are enabled for this prediction.
*/
enabledPluginInfos: external_exports.array(remotePluginInfoSchema),
/** Processing Context Identifier */
pci: external_exports.string(),
token: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("abort"),
taskId: external_exports.string()
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("complete"),
taskId: external_exports.string(),
processed: chatMessageDataSchema
}),
external_exports.object({
type: external_exports.literal("aborted"),
taskId: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("error"),
taskId: external_exports.string(),
error: serializedLMSExtendedErrorSchema
})
])
}).addChannelEndpoint("setPredictionLoopHandler", {
creationParameter: external_exports.void(),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("handlePredictionLoop"),
taskId: external_exports.string(),
config: kvConfigSchema,
pluginConfig: kvConfigSchema,
globalPluginConfig: kvConfigSchema,
workingDirectoryPath: external_exports.string().nullable(),
/**
* An array of all the plugins that are enabled for this prediction.
*/
enabledPluginInfos: external_exports.array(remotePluginInfoSchema),
/** Processing Context Identifier */
pci: external_exports.string(),
token: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("abort"),
taskId: external_exports.string()
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("complete"),
taskId: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("aborted"),
taskId: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("error"),
taskId: external_exports.string(),
error: serializedLMSExtendedErrorSchema
})
])
}).addChannelEndpoint("setToolsProvider", {
creationParameter: external_exports.void(),
toClientPacket: external_exports.discriminatedUnion("type", [
/**
* Starts a "tool providing session". Once this is received, the plugin should call the
* tools provider and pass the tools to the server using the `sessionInitialized` packet.
*
* If the initialization failed, the plugin should send the `sessionInitializationFailed`
* packet.
*/
external_exports.object({
type: external_exports.literal("initSession"),
pluginConfig: kvConfigSchema,
globalPluginConfig: kvConfigSchema,
workingDirectoryPath: external_exports.string().nullable(),
sessionId: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("discardSession"),
sessionId: external_exports.string()
}),
/**
* Call a tool within a session. The plugin should call the tool and return the result
* using the `toolCallComplete` packet.
*
* If the tool call fails in an unrecoverable way the plugin can send the `toolCallError`
* packet.
*/
external_exports.object({
type: external_exports.literal("callTool"),
sessionId: external_exports.string(),
callId: external_exports.string(),
toolName: external_exports.string(),
parameters: jsonSerializableSchema
}),
/**
* Abort a tool call. The plugin should abort the tool call and confirm the abort using
* the `toolCallAborted` packet.
*/
external_exports.object({
type: external_exports.literal("abortToolCall"),
sessionId: external_exports.string(),
callId: external_exports.string()
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
/**
* The plugin has provided a list of tools in a new session.
*/
external_exports.object({
type: external_exports.literal("sessionInitialized"),
sessionId: external_exports.string(),
toolDefinitions: external_exports.array(llmToolSchema)
}),
external_exports.object({
type: external_exports.literal("sessionInitializationFailed"),
sessionId: external_exports.string(),
error: serializedLMSExtendedErrorSchema
}),
external_exports.object({
type: external_exports.literal("toolCallComplete"),
sessionId: external_exports.string(),
callId: external_exports.string(),
result: jsonSerializableSchema
}),
external_exports.object({
type: external_exports.literal("toolCallError"),
sessionId: external_exports.string(),
callId: external_exports.string(),
error: serializedLMSExtendedErrorSchema
}),
external_exports.object({
type: external_exports.literal("toolCallStatus"),
sessionId: external_exports.string(),
callId: external_exports.string(),
statusText: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("toolCallWarn"),
sessionId: external_exports.string(),
callId: external_exports.string(),
warnText: external_exports.string()
})
])
}).addChannelEndpoint("setGenerator", {
creationParameter: external_exports.void(),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("generate"),
taskId: external_exports.string(),
input: chatHistoryDataSchema,
pluginConfig: kvConfigSchema,
globalPluginConfig: kvConfigSchema,
toolDefinitions: external_exports.array(llmToolSchema),
workingDirectoryPath: external_exports.string().nullable()
}),
external_exports.object({
type: external_exports.literal("abort"),
taskId: external_exports.string()
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("complete"),
taskId: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("aborted"),
taskId: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("error"),
taskId: external_exports.string(),
error: serializedLMSExtendedErrorSchema
}),
external_exports.object({
type: external_exports.literal("fragmentGenerated"),
taskId: external_exports.string(),
content: external_exports.string(),
opts: llmPredictionFragmentInputOptsSchema
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationStarted"),
taskId: external_exports.string(),
toolCallId: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationNameReceived"),
taskId: external_exports.string(),
toolName: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationArgumentFragmentGenerated"),
taskId: external_exports.string(),
content: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationEnded"),
taskId: external_exports.string(),
toolCallRequest: toolCallRequestSchema
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationFailed"),
taskId: external_exports.string(),
error: serializedLMSExtendedErrorSchema
})
])
}).addRpcEndpoint("processingHandleUpdate", {
parameter: external_exports.object({
/** Processing Context Identifier */
pci: external_exports.string(),
token: external_exports.string(),
update: processingUpdateSchema
}),
returns: external_exports.void()
}).addRpcEndpoint("processingHandleRequest", {
parameter: external_exports.object({
/** Processing Context Identifier */
pci: external_exports.string(),
token: external_exports.string(),
request: processingRequestSchema
}),
returns: external_exports.object({
response: processingRequestResponseSchema
})
}).addRpcEndpoint("processingPullHistory", {
parameter: external_exports.object({
/** Processing Context Identifier */
pci: external_exports.string(),
token: external_exports.string(),
includeCurrent: external_exports.boolean()
}),
returns: chatHistoryDataSchema
}).addRpcEndpoint("processingGetOrLoadTokenSource", {
parameter: external_exports.object({
/** Processing Context Identifier */
pci: external_exports.string(),
token: external_exports.string()
}),
returns: external_exports.object({
tokenSourceIdentifier: tokenSourceIdentifierSchema
})
}).addRpcEndpoint("processingHasStatus", {
parameter: external_exports.object({
/** Processing Context Identifier */
pci: external_exports.string(),
token: external_exports.string()
}),
returns: external_exports.boolean()
}).addRpcEndpoint("processingNeedsNaming", {
parameter: external_exports.object({
/** Processing Context Identifier */
pci: external_exports.string(),
token: external_exports.string()
}),
returns: external_exports.boolean()
}).addRpcEndpoint("processingSuggestName", {
parameter: external_exports.object({
/** Processing Context Identifier */
pci: external_exports.string(),
token: external_exports.string(),
name: external_exports.string()
}),
returns: external_exports.void()
}).addRpcEndpoint("processingSetSenderName", {
parameter: external_exports.object({
/** Processing Context Identifier */
pci: external_exports.string(),
token: external_exports.string(),
name: external_exports.string()
}),
returns: external_exports.void()
}).addRpcEndpoint("setConfigSchematics", {
parameter: external_exports.object({
schematics: serializedKVConfigSchematicsSchema
}),
returns: external_exports.void()
}).addRpcEndpoint("setGlobalConfigSchematics", {
parameter: external_exports.object({
schematics: serializedKVConfigSchematicsSchema
}),
returns: external_exports.void()
}).addRpcEndpoint("pluginInitCompleted", {
parameter: external_exports.void(),
returns: external_exports.void()
});
}
function createRepositoryBackendInterface() {
return new BackendInterface().addRpcEndpoint("searchModels", {
parameter: external_exports.object({
opts: modelSearchOptsSchema
}),
returns: external_exports.object({
results: external_exports.array(modelSearchResultEntryDataSchema)
})
}).addRpcEndpoint("getModelDownloadOptions", {
parameter: external_exports.object({
modelSearchResultIdentifier: modelSearchResultIdentifierSchema
}),
returns: external_exports.object({
results: external_exports.array(modelSearchResultDownloadOptionDataSchema)
})
}).addChannelEndpoint("downloadModel", {
creationParameter: external_exports.object({
downloadIdentifier: external_exports.string()
}),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("downloadProgress"),
update: downloadProgressUpdateSchema
}),
external_exports.object({
type: external_exports.literal("startFinalizing")
}),
external_exports.object({
type: external_exports.literal("success"),
defaultIdentifier: external_exports.string()
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("cancel")
})
])
}).addChannelEndpoint("downloadArtifact", {
creationParameter: external_exports.object({
artifactOwner: kebabCaseSchema,
artifactName: kebabCaseWithDotsSchema,
revisionNumber: external_exports.number().int().nullable(),
path: external_exports.string()
}),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("downloadProgress"),
update: downloadProgressUpdateSchema
}),
external_exports.object({
type: external_exports.literal("startFinalizing")
}),
external_exports.object({
type: external_exports.literal("success")
})
]),
toServerPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("cancel")
})
])
}).addRpcEndpoint("installPluginDependencies", {
parameter: external_exports.object({
pluginFolder: external_exports.string()
}),
returns: external_exports.void()
}).addRpcEndpoint("getLocalArtifactFiles", {
parameter: external_exports.object({
path: external_exports.string()
}),
returns: external_exports.object({
fileList: localArtifactFileListSchema
})
}).addChannelEndpoint("pushArtifact", {
creationParameter: external_exports.object({
path: external_exports.string(),
description: external_exports.string().max(1e3).optional(),
/**
* Request to make the artifact private. Only effective if the artifact did not exist
* before. Will not change the visibility of an existing artifact.
*/
makePrivate: external_exports.boolean().optional(),
/**
* If true, will write the revision number of the artifact after the push back to the
* artifact manifest.json.
*/
writeRevision: external_exports.boolean().optional(),
overrides: jsonSerializableSchema.optional()
}),
toServerPacket: external_exports.void(),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("message"),
message: external_exports.string()
})
])
}).addChannelEndpoint("ensureAuthenticated", {
creationParameter: external_exports.void(),
toServerPacket: external_exports.void(),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("authenticationUrl"),
url: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("authenticated")
})
])
}).addRpcEndpoint("loginWithPreAuthenticatedKeys", {
parameter: external_exports.object({
keyId: external_exports.string(),
publicKey: external_exports.string(),
privateKey: external_exports.string()
}),
returns: external_exports.object({
userName: external_exports.string()
})
}).addChannelEndpoint("createArtifactDownloadPlan", {
creationParameter: external_exports.object({
owner: kebabCaseSchema,
name: kebabCaseWithDotsSchema
}),
toServerPacket: external_exports.discriminatedUnion("type", [
/**
* If called before committing the plan, the plan is aborted. If called after committing
* the plan, the download is canceled.
*/
external_exports.object({
type: external_exports.literal("cancel")
}),
/**
* Can only be called after plan ready. Once called, starts the plan.
*/
external_exports.object({
type: external_exports.literal("commit")
})
]),
toClientPacket: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("planUpdated"),
plan: artifactDownloadPlanSchema
}),
external_exports.object({
type: external_exports.literal("planReady"),
plan: artifactDownloadPlanSchema
}),
external_exports.object({
type: external_exports.literal("downloadProgress"),
update: downloadProgressUpdateSchema
}),
external_exports.object({
type: external_exports.literal("startFinalizing")
}),
external_exports.object({
type: external_exports.literal("success")
})
])
});
}
function createSystemBackendInterface() {
return new BackendInterface().addRpcEndpoint("listDownloadedModels", {
parameter: external_exports.void(),
returns: external_exports.array(modelInfoSchema)
}).addChannelEndpoint("alive", {
creationParameter: external_exports.void(),
toServerPacket: external_exports.void(),
toClientPacket: external_exports.void()
}).addRpcEndpoint("notify", {
parameter: backendNotificationSchema,
returns: external_exports.void()
}).addRpcEndpoint("version", {
parameter: external_exports.void(),
returns: external_exports.object({
/**
* `major.minor.patch`
*/
version: external_exports.string(),
/**
* LM Studio build number
*/
build: external_exports.number()
})
}).addRpcEndpoint("setExperimentFlag", {
parameter: external_exports.object({
code: external_exports.string(),
value: external_exports.boolean()
}),
returns: external_exports.void()
}).addRpcEndpoint("getExperimentFlags", {
parameter: external_exports.void(),
returns: external_exports.array(external_exports.string())
}).addRpcEndpoint("startHttpServer", {
parameter: external_exports.object({
port: external_exports.number().int().min(1).max(65535).optional(),
cors: external_exports.boolean().optional()
}),
returns: external_exports.void()
}).addRpcEndpoint("stopHttpServer", {
parameter: external_exports.void(),
returns: external_exports.void()
});
}
function createAuthenticatedIpcTransportFactory(apiNamespace, hostedEnv, clientIdentifier, clientPasskey) {
const [onMessage, emitOnMessage] = BufferedEvent.create();
const [onClose, emitOnClose] = BufferedEvent.create();
const sendToServer = hostedEnv.getApiIpcTunnel(apiNamespace, {
authVersion: 1,
clientIdentifier,
clientPasskey
}, emitOnMessage, emitOnClose);
return GenericClientTransport.createFactory(onMessage, onClose, sendToServer);
}
function createAuthenticatedWsTransportFactory(apiNamespace, wsAddress, clientIdentifier, clientPasskey) {
return AuthenticatedWsClientTransport.createAuthenticatedWsClientTransportFactory({
url: Promise.resolve(wsAddress).then((wsAddress2) => `${wsAddress2}/${apiNamespace}`),
clientIdentifier,
clientPasskey
});
}
function createAuthenticatedClientPort(backendInterface, wsAddress, apiNamespace, clientIdentifier, clientPasskey, logger2, { errorDeserializer, verboseErrorMessage } = {}) {
const hostedEnv = getHostedEnv();
if (hostedEnv !== null) {
if (wsAddress !== void 0) {
logger2.debug("Ignoring wsAddress parameter when constructing the client because the client is running in a hosted environment. This is not an error.");
}
return new ClientPort(backendInterface, createAuthenticatedIpcTransportFactory(apiNamespace, hostedEnv, clientIdentifier, clientPasskey), { parentLogger: logger2, errorDeserializer, verboseErrorMessage });
} else {
return new ClientPort(backendInterface, createAuthenticatedWsTransportFactory(apiNamespace, wsAddress, clientIdentifier, clientPasskey), { parentLogger: logger2, errorDeserializer, verboseErrorMessage });
}
}
function makeLoadModelOptsSchema(loadModelConfigSchema) {
return external_exports.object({
identifier: external_exports.string().optional(),
config: loadModelConfigSchema.optional(),
signal: external_exports.instanceof(AbortSignal).optional(),
ttl: external_exports.number().optional(),
verbose: external_exports.union([external_exports.boolean(), logLevelSchema]).optional(),
onProgress: external_exports.function().optional()
});
}
function numberToCheckboxNumeric(value, uncheckedValue, valueWhenUnchecked) {
if (value === void 0) {
return void 0;
}
if (value === uncheckedValue) {
return { checked: false, value: valueWhenUnchecked };
}
return { checked: true, value };
}
function getProcessingStepName(processingStep) {
switch (processingStep) {
case "loading":
return "Loading";
case "chunking":
return "Chunking";
case "embedding":
return "Embedding";
default: {
const exhaustiveCheck = processingStep;
throw new Error(`Unexpected processing step: ${exhaustiveCheck}`);
}
}
}
function deserializeOtherError(serialized, stack) {
let content = import_chalk.default.redBright(` ${serialized.title} `);
if (serialized.suggestion !== void 0) {
content += "\n\n\n " + import_chalk.default.bgWhite.black(" (!) SUGGESTION ") + "\n\n" + import_chalk.default.white(serialized.suggestion);
}
if (serialized.cause !== void 0) {
content += "\n\n\n " + import_chalk.default.bgWhite.black(" (X) CAUSE ") + "\n\n" + import_chalk.default.gray(serialized.cause);
}
return makePrettyError(content, stack);
}
function registerErrorDeserializer(code, deserializer) {
errorDeserializersMap.set(code, deserializer);
}
function formatAvailableLLMs(availablePathsSample, totalModels) {
if (availablePathsSample.length === 0) {
return import_chalk.default.gray(" You don't have any LLMs downloaded.");
}
let text3 = availablePathsSample.map((path6) => import_chalk.default.cyanBright(" \u2022 " + path6)).join("\n");
if (availablePathsSample.length < totalModels) {
text3 += import_chalk.default.gray(`
... (and ${totalModels - availablePathsSample.length} more)`);
}
return text3;
}
function formatLoadedModels(loadedModelsSample, totalLoadedModels) {
if (loadedModelsSample.length === 0) {
return import_chalk.default.gray(" You don't have any models loaded.");
}
let text3 = loadedModelsSample.map((path6) => import_chalk.default.cyanBright(" \u2022 " + path6)).join("\n");
if (loadedModelsSample.length < totalLoadedModels) {
text3 += import_chalk.default.gray(`
... (and ${totalLoadedModels - loadedModelsSample.length} more)`);
}
return text3;
}
function getModelDomainTypeDisplayNameSingular(domain) {
switch (domain) {
case "llm":
return "an LLM";
case "embedding":
return "an embedding model";
case "imageGen":
return "an image generation model";
case "transcription":
return "a transcription model";
case "tts":
return "a text-to-speech model";
default: {
const exhaustiveCheck = domain;
console.error(`Unexpected domain type: ${exhaustiveCheck}`);
return "Unknown Model Domain";
}
}
}
function formatQuery(query) {
const requirements = [];
if (query.domain !== void 0) {
requirements.push(text`
The model must be ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(query.domain))}
`);
}
if (query.identifier !== void 0) {
requirements.push(`The identifier must be exactly "${import_chalk.default.yellowBright(query.identifier)}"`);
}
if (query.path !== void 0) {
requirements.push(`The path must match "${import_chalk.default.yellowBright(query.path)}"`);
}
if (requirements.length === 0) {
return import_chalk.default.gray(" \u2022 Any Model");
}
return requirements.map((req) => import_chalk.default.white(" \u2022 " + req)).join("\n");
}
function formatAvailablePresets(presets, totalAvailablePresets) {
if (presets.length === 0) {
return import_chalk.default.gray(" You don't have any presets available.");
}
let text3 = presets.map(({ identifier, name }) => import_chalk.default.cyanBright(` \u2022 ${name} (${import_chalk.default.cyan(identifier)})`)).join("\n");
if (presets.length < totalAvailablePresets) {
text3 += import_chalk.default.gray(`
... (and ${totalAvailablePresets - presets.length} more)`);
}
return text3;
}
function friendlyErrorDeserializer(serialized, _directCause, stack) {
if (serialized.displayData === void 0) {
return deserializeOtherError(serialized, stack);
}
let error;
const specificDeserializer = errorDeserializersMap.get(serialized.displayData.code);
if (specificDeserializer !== void 0) {
error = specificDeserializer(serialized.displayData, stack);
attachSerializedErrorData(error, serialized);
return error;
} else {
return deserializeOtherError(serialized, stack);
}
}
function cacheQuantizationTypeToCheckbox({ value, falseDefault }) {
return value === void 0 ? void 0 : value === false ? { checked: false, value: falseDefault } : { checked: true, value };
}
async function internalAct(chat, tools, baseOpts, stack, logger2, startTime, predictImpl, makePredictionResult) {
const abortController = new AbortController();
const mutableChat = Chat3.from(chat);
let currentCallId = -1;
let hasCalledUnimplementedTool = false;
if (baseOpts.signal !== void 0) {
if (baseOpts.signal.aborted) {
abortController.abort(baseOpts.signal.reason);
} else {
baseOpts.signal.addEventListener("abort", () => {
abortController.abort(baseOpts.signal?.reason);
}, { once: true });
}
}
let shouldContinue = false;
let predictionsPerformed = 0;
const toolsMap = /* @__PURE__ */ new Map();
for (const tool of tools) {
if (toolsMap.has(tool.name)) {
logger2.warnText`
Duplicate tool (${tool.name}) found in the tools array. The last tool with the same name
will be used.
`;
}
toolsMap.set(tool.name, tool);
}
do {
let allowTools = true;
if (
// If there is a defined number of max predictions,
baseOpts.maxPredictionRounds !== void 0 && // ... and this is the last chance to perform predictions, don't allow the model to use
// tools.
predictionsPerformed + 1 >= baseOpts.maxPredictionRounds
) {
allowTools = false;
}
let finished2 = false;
let firstTokenTriggered = false;
const contentArray = [];
const reasoningContentArray = [];
const nonReasoningContentArray = [];
const toolCallRequests = [];
let nextToolCallIndex = 0;
const toolCallResults = [];
const toolCallPromises = [];
const { promise: predictionPromise, resolve: predictionResolve, reject: predictionReject } = makePromise();
const { promise: finalPromise, resolve: finalResolve, reject: finalReject } = makePromise();
const internalHandleInvalidToolCallRequest = async (error, request, toolCallIndex) => {
let result;
try {
result = await (baseOpts.handleInvalidToolRequest ?? defaultHandleInvalidToolRequest)(error, request);
} catch (error2) {
if (abortController.signal.aborted) {
throw abortController.signal.reason;
}
abortController.abort();
throw error2;
}
if (result === void 0) {
return;
}
let resultString;
try {
resultString = JSON.stringify(result);
} catch (error2) {
abortController.abort();
throw makePrettyError("handleInvalidToolRequest returned a value that cannot be converted to JSON.", stack);
}
if (request === void 0) {
logger2.warnText`
The "handleInvalidToolRequest" callback has returned a result, but the tool request has
completely failed to parse, thus LM Studio cannot provide the result to the tool call.
Please avoid returning a result when the second parameter of the callback is undefined.
See the documentation for "handleInvalidToolRequest" for more information.
`;
} else {
toolCallResults.push({
index: toolCallIndex,
data: {
type: "toolCallResult",
toolCallId: request.id,
content: resultString
}
});
nextToolCallIndex++;
}
};
abortController.signal.throwIfAborted();
safeCallCallback(logger2, "onRoundStart", baseOpts.onRoundStart, [predictionsPerformed]);
let isGeneratingToolCall = false;
const roundAbortController = new AbortController();
const queue = baseOpts.allowParallelToolExecution ? new NoQueueQueue() : new FIFOQueue();
let receivedEagerToolNameReporting = false;
let receivedToolArgumentsStreaming = false;
predictImpl({
allowTools,
history: accessMaybeMutableInternals(mutableChat)._internalGetData(),
signal: roundAbortController.signal,
handleFragment: (fragment2) => {
if (!firstTokenTriggered) {
firstTokenTriggered = true;
safeCallCallback(logger2, "onFirstToken", baseOpts.onFirstToken, [predictionsPerformed]);
}
safeCallCallback(logger2, "onFragment", baseOpts.onPredictionFragment, [
{ roundIndex: predictionsPerformed, ...fragment2 }
]);
contentArray.push(fragment2.content);
if (!fragment2.isStructural) {
if (fragment2.reasoningType === "reasoning") {
reasoningContentArray.push(fragment2.content);
} else {
nonReasoningContentArray.push(fragment2.content);
}
}
},
handlePromptProcessingProgress: (progress) => {
safeCallCallback(logger2, "onPromptProcessingProgress", baseOpts.onPromptProcessingProgress, [predictionsPerformed, progress]);
},
handleToolCallGenerationStart: (toolCallId) => {
currentCallId = callIdGiver.next();
receivedEagerToolNameReporting = false;
receivedToolArgumentsStreaming = false;
isGeneratingToolCall = true;
safeCallCallback(logger2, "onToolCallRequestStart", baseOpts.onToolCallRequestStart, [
predictionsPerformed,
currentCallId,
{ toolCallId }
]);
},
handleToolCallGenerationNameReceived: (name) => {
receivedEagerToolNameReporting = true;
safeCallCallback(logger2, "onToolCallRequestNameReceived", baseOpts.onToolCallRequestNameReceived, [predictionsPerformed, currentCallId, name]);
},
handleToolCallGenerationArgumentFragmentGenerated: (content) => {
receivedToolArgumentsStreaming = true;
safeCallCallback(logger2, "onToolCallRequestArgumentFragmentGenerated", baseOpts.onToolCallRequestArgumentFragmentGenerated, [predictionsPerformed, currentCallId, content]);
},
handleToolCallGenerationEnd: (request, rawContent) => {
const callId = currentCallId;
isGeneratingToolCall = false;
const toolCallIndex = nextToolCallIndex;
nextToolCallIndex++;
if (!receivedEagerToolNameReporting) {
safeCallCallback(logger2, "onToolCallRequestNameReceived", baseOpts.onToolCallRequestNameReceived, [predictionsPerformed, callId, request.name]);
}
if (!receivedToolArgumentsStreaming) {
safeCallCallback(logger2, "onToolCallRequestArgumentFragmentGenerated", baseOpts.onToolCallRequestArgumentFragmentGenerated, [predictionsPerformed, callId, JSON.stringify(request.arguments ?? {}, null, 2)]);
}
const pushedRequest = { ...request };
toolCallRequests.push(pushedRequest);
const tool = toolsMap.get(request.name);
if (tool === void 0) {
const toolCallRequestError = new ToolCallRequestError(`Cannot find tool with name ${request.name}.`, rawContent);
toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, request, toolCallIndex).catch(finalReject));
safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [
predictionsPerformed,
callId,
toolCallRequestError
]);
return;
}
try {
tool.checkParameters(pushedRequest.arguments);
} catch (error) {
const toolCallRequestError = new ToolCallRequestError(error.message, rawContent);
toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, request, toolCallIndex).catch(finalReject));
safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [
predictionsPerformed,
callId,
toolCallRequestError
]);
return;
}
const toolCallContext = new SimpleToolCallContext(new SimpleLogger(`Tool(${request.name})`, logger2), abortController.signal, callId);
const isQueued = queue.needsQueueing();
safeCallCallback(logger2, "onToolCallRequestEnd", baseOpts.onToolCallRequestEnd, [
predictionsPerformed,
callId,
{
isQueued,
toolCallRequest: request,
rawContent
}
]);
toolCallPromises.push(queue.runInQueue(async () => {
if (isQueued) {
safeCallCallback(logger2, "onToolCallRequestDequeued", baseOpts.onToolCallRequestDequeued, [predictionsPerformed, callId]);
}
if (baseOpts.guardToolCall !== void 0) {
const resultContainer = [null];
await baseOpts.guardToolCall(predictionsPerformed, callId, new GuardToolCallController(request, tool, resultContainer));
if (resultContainer[0] === null) {
throw makeTitledPrettyError("Tool call guard did not allow or deny the tool call.", text`
The \`guardToolCall\` handler must call one of the methods on the controller
to allow or deny the tool call.
`, stack);
}
const guardResult = resultContainer[0];
const guardResultType = guardResult.type;
switch (guardResultType) {
case "allow": {
break;
}
case "allowAndOverrideParameters": {
pushedRequest.arguments = guardResult.parameters;
break;
}
case "deny": {
toolCallResults.push({
index: toolCallIndex,
data: {
type: "toolCallResult",
toolCallId: request.id,
content: JSON.stringify({
error: guardResult.reason
})
}
});
return;
}
}
}
safeCallCallback(logger2, "onToolCallRequestFinalized", baseOpts.onToolCallRequestFinalized, [
predictionsPerformed,
callId,
{
toolCallRequest: request,
rawContent
}
]);
let result;
try {
result = await tool.implementation(pushedRequest.arguments ?? {}, toolCallContext);
} catch (error) {
if (!(error instanceof UnimplementedToolError)) {
throw error;
}
hasCalledUnimplementedTool = true;
}
let resultString;
if (result === void 0) {
resultString = "undefined";
} else {
try {
resultString = JSON.stringify(result);
} catch (error) {
throw makePrettyError(`Return value of tool ${tool.name} cannot be converted to JSON.`, stack);
}
}
toolCallResults.push({
index: toolCallIndex,
data: {
type: "toolCallResult",
toolCallId: request.id,
content: resultString
}
});
}, abortController.signal).catch(finalReject));
},
handleToolCallGenerationFailed: (error, rawContent) => {
isGeneratingToolCall = false;
const toolCallRequestError = new ToolCallRequestError(error.message, rawContent);
toolCallPromises.push(internalHandleInvalidToolCallRequest(
toolCallRequestError,
// We don't have a request in this because the model has failed miserably.
void 0,
// Tool call index. Doesn't matter because if there is no request, there cannot be
// a replacement.
0
).catch(finalReject));
safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [
predictionsPerformed,
currentCallId,
toolCallRequestError
]);
},
handlePredictionEnd: (endPacket) => {
const predictionResult = makePredictionResult({
endPacket,
content: contentArray.join(""),
reasoningContent: reasoningContentArray.join(""),
nonReasoningContent: nonReasoningContentArray.join(""),
predictionsPerformed
});
safeCallCallback(logger2, "onPredictionCompleted", baseOpts.onPredictionCompleted, [
predictionResult
]);
predictionResolve();
},
handleError: (error) => {
if (isGeneratingToolCall) {
const toolCallRequestError = new ToolCallRequestError(`Generation failed: ${error.message}`, void 0);
isGeneratingToolCall = false;
safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [
predictionsPerformed,
currentCallId,
toolCallRequestError
]);
}
finished2 = true;
predictionReject(error);
}
});
const abortListener = () => {
if (finished2) {
return;
}
finished2 = true;
roundAbortController.abort(abortController.signal.reason);
};
abortController.signal.addEventListener("abort", abortListener);
predictionPromise.then(() => {
const assistantMessage = ChatMessage.from({
role: "assistant",
content: [
{
type: "text",
text: contentArray.join("")
},
...toolCallRequests.map((toolCallRequest) => ({
type: "toolCallRequest",
toolCallRequest
}))
]
});
mutableChat.append(assistantMessage.asMutableCopy());
safeCallCallback(logger2, "onMessage", baseOpts.onMessage, [assistantMessage]);
}).then(() => Promise.all(toolCallPromises)).then(() => finalResolve(), finalReject);
await finalPromise;
shouldContinue = false;
if (toolCallResults.length > 0) {
toolCallResults.sort((a3, b4) => a3.index - b4.index);
const toolMessage = ChatMessage.from({
role: "tool",
content: toolCallResults.map((r8) => r8.data)
});
mutableChat.append(toolMessage.asMutableCopy());
safeCallCallback(logger2, "onMessage", baseOpts.onMessage, [toolMessage]);
shouldContinue = true;
}
safeCallCallback(logger2, "onRoundEnd", baseOpts.onRoundEnd, [predictionsPerformed]);
predictionsPerformed++;
if (baseOpts.maxPredictionRounds !== void 0 && predictionsPerformed >= baseOpts.maxPredictionRounds) {
shouldContinue = false;
}
shouldContinue &&= !hasCalledUnimplementedTool;
} while (shouldContinue);
return new ActResult(predictionsPerformed, (performance.now() - startTime) / 1e3);
}
function splitPredictionOpts(opts) {
const { onPromptProcessingProgress, onFirstToken, onPredictionFragment, onToolCallRequestStart, onToolCallRequestNameReceived, onToolCallRequestArgumentFragmentGenerated, onToolCallRequestEnd, onToolCallRequestFailure, signal, preset, ...config } = opts;
return [
config,
{
onPromptProcessingProgress,
onFirstToken,
onPredictionFragment,
onToolCallRequestStart,
onToolCallRequestNameReceived,
onToolCallRequestArgumentFragmentGenerated,
onToolCallRequestEnd,
onToolCallRequestFailure,
signal,
preset
}
];
}
function splitRespondOpts(opts) {
const { onMessage, ...remaining } = opts;
const [config, llmPredictionOpts] = splitPredictionOpts(remaining);
return [
config,
llmPredictionOpts,
{
onMessage
}
];
}
function splitActOpts(opts) {
const { onFirstToken, onPredictionFragment, onMessage, onRoundStart, onRoundEnd, onPredictionCompleted, onPromptProcessingProgress, onToolCallRequestStart, onToolCallRequestNameReceived, onToolCallRequestArgumentFragmentGenerated, onToolCallRequestEnd, onToolCallRequestFinalized, onToolCallRequestFailure, onToolCallRequestDequeued, guardToolCall, handleInvalidToolRequest, maxPredictionRounds, signal, preset, allowParallelToolExecution, ...config } = opts;
return [
config,
{
onFirstToken,
onPredictionFragment,
onMessage,
onRoundStart,
onRoundEnd,
onPredictionCompleted,
onPromptProcessingProgress,
onToolCallRequestStart,
onToolCallRequestNameReceived,
onToolCallRequestArgumentFragmentGenerated,
onToolCallRequestEnd,
onToolCallRequestFinalized,
onToolCallRequestFailure,
onToolCallRequestDequeued,
guardToolCall,
handleInvalidToolRequest,
maxPredictionRounds,
signal,
preset,
allowParallelToolExecution
}
];
}
function stringifyAny(message) {
switch (typeof message) {
case "string":
return message;
case "number":
return message.toString();
case "boolean":
return message ? "true" : "false";
case "undefined":
return "undefined";
case "object":
if (message === null) {
return "null";
}
if (message instanceof Error) {
return message.stack;
}
return JSON.stringify(message, null, 2);
case "bigint":
return message.toString();
case "symbol":
return message.toString();
case "function":
return message.toString();
default:
return "unknown";
}
}
function concatenateDebugMessages(...messages) {
return messages.map(stringifyAny).join(" ");
}
function createId() {
return `${Date.now()}-${Math.random()}`;
}
var import_chalk, import_lms_isomorphic, Subscribable, Event2, NOTHING, DRAFTABLE, DRAFT_STATE, getPrototypeOf, objectCtorString, plugins, currentScope, objectTraps, arrayTraps, Immer2, immer, produceWithPatches, applyPatches, equals, Signal, LazySignal, apiServerPorts, waitForNextMicroTask, BufferedEvent, CancelEvent, Cleaner, IdGiver, boxen$1, stringWidth, ansiRegex, hasRequiredAnsiRegex, stripAnsi, hasRequiredStripAnsi, isFullwidthCodePoint, hasRequiredIsFullwidthCodePoint, emojiRegex4, hasRequiredEmojiRegex, hasRequiredStringWidth, widestLine, hasRequiredWidestLine, cliBoxes, single, double, round, bold, singleDouble, doubleSingle, classic, require$$0, hasRequiredCliBoxes, camelcase, hasRequiredCamelcase, ansiAlign_1, hasRequiredAnsiAlign, ansiStyles, colorName, hasRequiredColorName, conversions, hasRequiredConversions, route, hasRequiredRoute, colorConvert, hasRequiredColorConvert, hasRequiredAnsiStyles, wrapAnsi_1, hasRequiredWrapAnsi, hasRequiredBoxen, boxenExports, boxen, compiledTemplatesCache, MaybeMutable, OWLSignal, allowableEnvVarKeys, allowableEnvVarKeysSchema, allowableEnvVarsSchema, kebabCaseRegex, kebabCaseSchema, kebabCaseWithDotsRegex, kebabCaseWithDotsSchema, fileNameRegex, fileNameSchema, relativePathNoLeadingDotSlashRegex, huggingFaceModelDownloadSourceSchema, modelDownloadSourceSchema, artifactDependencyPurposeSchema, artifactDependencyBaseSchema, artifactModelDependencySchema, artifactArtifactDependencySchema, artifactDependencySchema, artifactManifestBaseSchema, artifactIdentifierRegex, artifactIdentifierSchema, modelManifestSchema, pluginRunnerTypeSchema, pluginManifestSchema, presetManifestSchema, artifactTypeSchema, backendNotificationSchema, fileTypeSchema, jsonSerializableSchema, chatMessagePartTextDataSchema, chatMessagePartFileDataSchema, functionToolCallRequestSchema, toolCallRequestSchema, chatMessagePartToolCallRequestDataSchema, chatMessagePartToolCallResultDataSchema, chatMessageDataSchema, chatHistoryDataSchema, citationSourceSchema, colorPalette, colorPaletteSchema, diagnosticsLogEventDataSchema, diagnosticsLogEventSchema, llmLlamaAccelerationOffloadRatioSchema, llmSplitStrategySchema, gpuSettingSchema, llmLlamaCacheQuantizationTypes, llmLlamaCacheQuantizationTypeSchema, llmMlxKvCacheBitsTypeSchema, llmMlxKvCacheGroupSizeTypesSchema, llmMlxKvCacheQuantizationSchema, llmLoadModelConfigSchema, embeddingLoadModelConfigSchema, modelCompatibilityTypeSchema, quantizationSchema, modelInfoBaseSchema, modelInstanceInfoBaseSchema, embeddingModelAdditionalInfoSchema, embeddingModelInstanceAdditionalInfoSchema, embeddingModelInfoSchema, embeddingModelInstanceInfoSchema, modelDomainTypeSchema, reasonableKeyStringSchema, modelQuerySchema, modelSpecifierSchema, genericErrorDisplayDataSchema, llmErrorDisplayDataSchema, errorDisplayDataSchema, serializedLMSExtendedErrorSchema, documentParsingLibraryIdentifierSchema, documentParsingOptsSchema, gpuSplitStrategies, gpuSplitStrategySchema, defaultGPUSplitConfig, gpuSplitConfigSchema, kvConfigFieldSchema, kvConfigSchema, kvConfigLayerNameSchema, kvConfigStackLayerSchema, kvConfigStackSchema, kvConfigFieldDependencySchema, contentBlockStyleSchema, llmToolParametersSchema, llmToolSchema, llmToolUseSettingSchema, llmApplyPromptTemplateOptsSchema, llmContextReferenceSchema, llmAdditionalInfoSchema, llmInstanceAdditionalInfoSchema, llmInfoSchema, llmInstanceInfoSchema, toolNamingSchema, zodSchemaSchema, llmManualPromptTemplateSchema, llmJinjaPromptTemplateSchema, llmPromptTemplateTypeSchema, llmPromptTemplateSchema, llmStructuredPredictionTypeSchema, llmStructuredPredictionSettingSchema, llmContextOverflowPolicySchema, llmReasoningParsingSchema, llmPredictionConfigInputSchema, llmLlamaMirostatSamplingConfigSchema, llmLlamaSingleLogitBiasModificationSchema, llmLlamaLogitBiasConfigSchema, llmPredictionFragmentReasoningTypeSchema, llmPredictionFragmentSchema, llmPredictionFragmentInputOptsSchema, llmPredictionStopReasonSchema, llmPredictionStatsSchema, llmGenInfoSchema, blockLocationSchema, statusStepStatusSchema, statusStepStateSchema, processingUpdateStatusCreateSchema, processingUpdateStatusUpdateSchema, processingUpdateStatusRemoveSchema, processingUpdateCitationBlockCreateSchema, processingUpdateDebugInfoBlockCreateSchema, processingUpdateContentBlockCreateSchema, processingUpdateContentBlockAppendTextSchema, processingUpdateContentBlockAppendToolResultSchema, processingUpdateContentBlockAppendToolRequestSchema, processingUpdateContentBlockReplaceToolRequestSchema, processingUpdateContentBlockReplaceTextSchema, processingUpdateContentBlockSetPrefixSchema, processingUpdateContentBlockSetSuffixSchema, processingUpdateContentBlockAttachGenInfoSchema, processingUpdateContentBlockSetStyleSchema, toolStatusStepStateStatusSchema, toolStatusStepStateSchema, processingUpdateToolStatusCreateSchema, processingUpdateToolStatusUpdateSchema, processingUpdateToolStatusArgumentFragmentSchema, processingUpdateSetSenderNameSchema, processingUpdateSchema, processingRequestConfirmToolCallSchema, processingRequestTextInputSchema, processingRequestSchema, processingRequestResponseConfirmToolCallSchema, processingRequestResponseTextInputSchema, processingRequestResponseSchema, tokenSourceIdentifierSchema, modelInfoSchema, modelInstanceInfoSchema, pluginConfigSpecifierSchema, remotePluginInfoSchema, artifactDownloadPlanModelInfoSchema, artifactDownloadPlanNodeStateSchema, artifactDownloadPlanNodeSchema, artifactDownloadPlanSchema, localArtifactFileEntrySchema, localArtifactFileListSchema, downloadProgressUpdateSchema, modelSearchResultDownloadOptionFitEstimationSchema, modelSearchResultDownloadOptionDataSchema, modelSearchResultIdentifierSchema, modelSearchResultEntryDataSchema, modelSearchOptsSchema, internalRetrievalResultEntrySchema, internalRetrievalResultSchema, retrievalChunkingMethodSchema, retrievalFileProcessingStepSchema, acceleratorTypeSchema, acceleratorSchema, serializedKVConfigSchematicsFieldSchema, serializedKVConfigSchematicsSchema, booleanOrMixedSchema, virtualModelDefinitionMetadataOverridesSchema, virtualModelDefinitionConcreteModelBaseSchema, virtualModelCustomFieldSetJinjaVariableEffectSchema, virtualModelCustomFieldPrependSystemPromptEffectSchema, virtualModelCustomFieldAppendSystemPromptEffectSchema, virtualModelCustomFieldDefinitionBaseSchema, virtualModelBooleanCustomFieldDefinitionSchema, virtualModelStringCustomFieldDefinitionSchema, virtualModelSelectCustomFieldDefinitionSchema, virtualModelCustomFieldDefinitionSchema, virtualModelConditionEqualsSchema, virtualModelConditionSchema, virtualModelSuggestionSchema, logLevelSchema, defaultInfoPrefix, defaultWarnPrefix, defaultErrorPrefix, defaultDebugPrefix, SimpleLogger, _a5, finished, StreamablePromise, Validator, sharedValidator, FileHandle, chatMessageInputSchema, chatHistoryInputSchema, Chat3, chatHistoryLikeSchema, ChatMessage, chatMessageLikeSchema, KVFieldValueTypesLibraryBuilder, KVFieldValueTypeLibrary, KVConfigSchematicsBuilder, createParsedKVConfig, KVConfigSchematics, KVConfigBuilder, ParsedKVConfig, PartialParsedKVConfig, emptyKVConfig, baseKVValueTypesLibraryBuilder, kvValueTypesLibrary, globalConfigSchematics, llmPredictionConfigSchematics, llmSharedPredictionConfigSchematics, llmLoadSchematics, llmSharedLoadConfigSchematics, llamaLoadConfigSchematics, llmLlamaLoadConfigSchematics, llmLlamaMoeAdditionalLoadConfigSchematics, llmLlamaMoeLoadConfigSchematics, embeddingLoadSchematics, embeddingSharedLoadConfigSchematics, retrievalSchematics, embeddingLlamaLoadConfigSchematics, lib, helpers, hasRequiredHelpers, attribute_1, hasRequiredAttribute, scan, hasRequiredScan, validator, hasRequiredValidator, hasRequiredLib, libExports, toolBaseSchema, SimpleToolCallContext, functionToolSchema, rawFunctionToolSchema, unimplementedRawFunctionToolSchema, remoteToolSchema, UnimplementedToolError, ToolCallRequestError, BackendInterface, ConnectionStatus, logger, Channel, DoubleIndexedKV, Registry, __extends, ClassRegistry, __read$3, CustomTransformerRegistry, getType$1, isUndefined, isNull, isPlainObject$1, isEmptyObject, isArray$1, isString, isNumber, isBoolean, isRegExp, isMap, isSet, isSymbol, isDate, isError, isNaNValue, isPrimitive, isBigint, isInfinite, isTypedArray, isURL, escapeKey, stringifyPath, parsePath, __assign$1, __read$2, __spreadArray$2, simpleRules, symbolRule, constructorToName, typedArrayRule, classRule, customRule, compositeRules, transformValue, simpleRulesByAnnotation, untransformValue, getNthKey, getDeep, setDeep, __read$1, __spreadArray$1, isDeep, walker, __assign, __read, __spreadArray, SuperJSON, serialize$1, deserialize$1, serializedOpaqueSchema, clientToServerMessageSchema, serverToClientMessageSchema, Transport, ClientTransport, wsAuthenticationResultSchema, WsClientTransportStatus, WsClientTransport, AuthenticatedWsClientTransport, ClientPort, GenericClientTransport, DiagnosticsNamespace, ModelNamespace, DynamicHandle, EmbeddingDynamicHandle, EmbeddingModel, EmbeddingNamespace, parseDocumentOptsSchema, retrievalCallbacksSchema, retrievalOptsSchema, FilesNamespace, errorDeserializersMap, ActResult, callIdGiver, NoQueueQueue, FIFOQueue, GuardToolCallController, llmActBaseOptsSchema, defaultHandleInvalidToolRequest, PredictionResult, StructuredPredictionResult, OngoingPrediction, llmPredictionOptsSchema, llmRespondOptsSchema, llmActionOptsSchema, noFormattingTemplate, LLMDynamicHandle, LLM, LLMNamespace, GeneratorPredictionResult, OngoingGeneratorPrediction, llmGeneratorPredictionOptsSchema, llmGeneratorActOptsSchema, LLMGeneratorHandle, generatorSchema, BaseController, GeneratorController, __addDisposableResource$1, __disposeResources$1, ProcessingConnector, ProcessingController, PredictionProcessStatusController, PredictionProcessCitationBlockController, PredictionProcessDebugInfoBlockController, PredictionProcessContentBlockController, PredictionProcessToolStatusController, ToolsProviderController, GeneratorConnectorImpl, PluginSelfRegistrationHost, __addDisposableResource, __disposeResources, SingleRemoteToolUseSession, MultiRemoteToolUseSession, pluginToolsOptsSchema, registerDevelopmentPluginOptsSchema, PluginsNamespace, artifactDownloadPlannerDownloadOptsSchema, ArtifactDownloadPlanner, downloadOptsSchema, ModelSearchResultDownloadOption, ModelSearchResultEntry, downloadArtifactOptsSchema, pushArtifactOptsSchema, ensureAuthenticatedOptsSchema, loginWithPreAuthenticatedKeysOptsSchema, createArtifactDownloadPlannerOptsSchema, RepositoryNamespace, startHttpServerOptsSchema, SystemNamespace, constructorOptsSchema, LMStudioClient;
var init_dist3 = __esm({
"../pi-mono/node_modules/@lmstudio/sdk/dist/index.mjs"() {
init_process_shim();
init_zod();
init_process_shim();
import_chalk = __toESM(require_source2(), 1);
import_lms_isomorphic = __toESM(require_browser2(), 1);
init_esm2();
Subscribable = class {
subscribeWithCleaner(cleaner, listener) {
const unsubscribe = this.subscribe(listener);
cleaner.register(unsubscribe);
}
subscribeOnce(listener) {
const unsubscribe = this.subscribe((data) => {
unsubscribe();
listener(data);
});
return unsubscribe;
}
subscribeOnceWithCleaner(cleaner, listener) {
const unsubscribe = this.subscribeOnce(listener);
cleaner.register(unsubscribe);
}
derive(deriver, outputEqualsPredicate = (a3, b4) => a3 === b4) {
if (isSignalLike(this)) {
return LazySignal.deriveFrom([this], deriver);
}
const thisWithGetter = this;
if (thisWithGetter.get !== void 0) {
const initialValue = thisWithGetter.get();
if (initialValue === LazySignal.NOT_AVAILABLE) {
return LazySignal.createWithoutInitialValue((setDownstream) => {
return thisWithGetter.subscribe((data) => {
if (isAvailable(data)) {
setDownstream(deriver(data));
}
});
});
}
const thisNarrowed = thisWithGetter;
return LazySignal.create(deriver(thisNarrowed.get()), (setDownstream) => {
return thisNarrowed.subscribe((data) => {
setDownstream(deriver(data));
});
}, outputEqualsPredicate);
}
return LazySignal.createWithoutInitialValue((setDownstream) => {
return this.subscribe((data) => {
if (isAvailable(data)) {
setDownstream(deriver(data));
}
});
}, outputEqualsPredicate);
}
};
Event2 = class _Event extends Subscribable {
/**
* Internal state that tracks whether the event has any subscribers.
*/
constructor() {
super();
this.subscribers = /* @__PURE__ */ new Set();
this.onSubscribed = null;
this.onUnsubscribed = null;
}
emit(data) {
queueMicrotask(() => {
for (const subscriber of this.subscribers) {
subscriber(data);
}
});
}
static create() {
const event = new _Event();
const emitter = (data) => {
event.emit(data);
};
return [event, emitter];
}
subscribe(listener) {
const previousSize = this.subscribers.size;
this.subscribers.add(listener);
if (previousSize === 0 && this.subscribers.size === 1) {
this.onSubscribed?.();
}
return () => {
const previousSize2 = this.subscribers.size;
this.subscribers.delete(listener);
if (previousSize2 === 1 && this.subscribers.size === 0) {
this.onUnsubscribed?.();
}
};
}
batch({ minIdleTimeMs = 200, maxBatchTimeMs = 1e3 }) {
const [batchedEvent, emitBatchedEvent] = _Event.create();
batchedEvent.onSubscribed = () => {
let batch = [];
let emitBatchTimeout = null;
let firstEventTime = 0;
const emitBatch = () => {
emitBatchTimeout = null;
emitBatchedEvent(batch);
batch = [];
};
batchedEvent.onUnsubscribed = this.subscribe((data) => {
batch.push(data);
if (emitBatchTimeout === null) {
firstEventTime = Date.now();
emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, maxBatchTimeMs));
} else {
clearTimeout(emitBatchTimeout);
const timeSinceFirstEvent = Date.now() - firstEventTime;
emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, Math.max(0, maxBatchTimeMs - timeSinceFirstEvent)));
}
});
};
return batchedEvent;
}
};
NOTHING = Symbol.for("immer-nothing");
DRAFTABLE = Symbol.for("immer-draftable");
DRAFT_STATE = Symbol.for("immer-state");
getPrototypeOf = Object.getPrototypeOf;
objectCtorString = Object.prototype.constructor.toString();
plugins = {};
objectTraps = {
get(state, prop) {
if (prop === DRAFT_STATE)
return state;
const source = latest(state);
if (!has2(source, prop)) {
return readPropFromProto(state, source, prop);
}
const value = source[prop];
if (state.finalized_ || !isDraftable(value)) {
return value;
}
if (value === peek(state.base_, prop)) {
prepareCopy(state);
return state.copy_[prop] = createProxy(value, state);
}
return value;
},
has(state, prop) {
return prop in latest(state);
},
ownKeys(state) {
return Reflect.ownKeys(latest(state));
},
set(state, prop, value) {
const desc = getDescriptorFromProto(latest(state), prop);
if (desc?.set) {
desc.set.call(state.draft_, value);
return true;
}
if (!state.modified_) {
const current2 = peek(latest(state), prop);
const currentState = current2?.[DRAFT_STATE];
if (currentState && currentState.base_ === value) {
state.copy_[prop] = value;
state.assigned_[prop] = false;
return true;
}
if (is(value, current2) && (value !== void 0 || has2(state.base_, prop)))
return true;
prepareCopy(state);
markChanged(state);
}
if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
(value !== void 0 || prop in state.copy_) || // special case: NaN
Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
return true;
state.copy_[prop] = value;
state.assigned_[prop] = true;
return true;
},
deleteProperty(state, prop) {
if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
state.assigned_[prop] = false;
prepareCopy(state);
markChanged(state);
} else {
delete state.assigned_[prop];
}
if (state.copy_) {
delete state.copy_[prop];
}
return true;
},
// Note: We never coerce `desc.value` into an Immer draft, because we can't make
// the same guarantee in ES5 mode.
getOwnPropertyDescriptor(state, prop) {
const owner = latest(state);
const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
if (!desc)
return desc;
return {
writable: true,
configurable: state.type_ !== 1 || prop !== "length",
enumerable: desc.enumerable,
value: owner[prop]
};
},
defineProperty() {
die(11);
},
getPrototypeOf(state) {
return getPrototypeOf(state.base_);
},
setPrototypeOf() {
die(12);
}
};
arrayTraps = {};
each(objectTraps, (key, fn) => {
arrayTraps[key] = function() {
arguments[0] = arguments[0][0];
return fn.apply(this, arguments);
};
});
arrayTraps.deleteProperty = function(state, prop) {
if (false)
die(13);
return arrayTraps.set.call(this, state, prop, void 0);
};
arrayTraps.set = function(state, prop, value) {
if (false)
die(14);
return objectTraps.set.call(this, state[0], prop, value, state[0]);
};
Immer2 = class {
constructor(config) {
this.autoFreeze_ = true;
this.useStrictShallowCopy_ = false;
this.produce = (base, recipe, patchListener) => {
if (typeof base === "function" && typeof recipe !== "function") {
const defaultBase = recipe;
recipe = base;
const self2 = this;
return function curriedProduce(base2 = defaultBase, ...args) {
return self2.produce(base2, (draft) => recipe.call(this, draft, ...args));
};
}
if (typeof recipe !== "function")
die(6);
if (patchListener !== void 0 && typeof patchListener !== "function")
die(7);
let result;
if (isDraftable(base)) {
const scope = enterScope(this);
const proxy = createProxy(base, void 0);
let hasError = true;
try {
result = recipe(proxy);
hasError = false;
} finally {
if (hasError)
revokeScope(scope);
else
leaveScope(scope);
}
usePatchesInScope(scope, patchListener);
return processResult(result, scope);
} else if (!base || typeof base !== "object") {
result = recipe(base);
if (result === void 0)
result = base;
if (result === NOTHING)
result = void 0;
if (this.autoFreeze_)
freeze(result, true);
if (patchListener) {
const p4 = [];
const ip = [];
getPlugin("Patches").generateReplacementPatches_(base, result, p4, ip);
patchListener(p4, ip);
}
return result;
} else
die(1, base);
};
this.produceWithPatches = (base, recipe) => {
if (typeof base === "function") {
return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
}
let patches, inversePatches;
const result = this.produce(base, recipe, (p4, ip) => {
patches = p4;
inversePatches = ip;
});
return [result, patches, inversePatches];
};
if (typeof config?.autoFreeze === "boolean")
this.setAutoFreeze(config.autoFreeze);
if (typeof config?.useStrictShallowCopy === "boolean")
this.setUseStrictShallowCopy(config.useStrictShallowCopy);
}
createDraft(base) {
if (!isDraftable(base))
die(8);
if (isDraft(base))
base = current(base);
const scope = enterScope(this);
const proxy = createProxy(base, void 0);
proxy[DRAFT_STATE].isManual_ = true;
leaveScope(scope);
return proxy;
}
finishDraft(draft, patchListener) {
const state = draft && draft[DRAFT_STATE];
if (!state || !state.isManual_)
die(9);
const { scope_: scope } = state;
usePatchesInScope(scope, patchListener);
return processResult(void 0, scope);
}
/**
* Pass true to automatically freeze all copies created by Immer.
*
* By default, auto-freezing is enabled.
*/
setAutoFreeze(value) {
this.autoFreeze_ = value;
}
/**
* Pass true to enable strict shallow copy.
*
* By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
*/
setUseStrictShallowCopy(value) {
this.useStrictShallowCopy_ = value;
}
applyPatches(base, patches) {
let i7;
for (i7 = patches.length - 1; i7 >= 0; i7--) {
const patch = patches[i7];
if (patch.path.length === 0 && patch.op === "replace") {
base = patch.value;
break;
}
}
if (i7 > -1) {
patches = patches.slice(i7 + 1);
}
const applyPatchesImpl = getPlugin("Patches").applyPatches_;
if (isDraft(base)) {
return applyPatchesImpl(base, patches);
}
return this.produce(
base,
(draft) => applyPatchesImpl(draft, patches)
);
}
};
immer = new Immer2();
immer.produce;
produceWithPatches = immer.produceWithPatches.bind(
immer
);
immer.setAutoFreeze.bind(immer);
immer.setUseStrictShallowCopy.bind(immer);
applyPatches = immer.applyPatches.bind(immer);
immer.createDraft.bind(immer);
immer.finishDraft.bind(immer);
enableMapSet();
enablePatches();
equals = (a3, b4) => a3 === b4;
Signal = class _Signal extends Subscribable {
/**
* Creates a signal.
*
* @param value - The initial value of the signal.
* @param equalsPredicate - A function to compare two values. The subscribers will only be called
* if the value changes according to the `equalsPredicate`. By default, it uses the `===`
* operator.
* @returns This method returns a tuple with two elements:
* - The signal
* - A function to update the value
**/
static create(value, equalsPredicate = equals) {
const signal = new _Signal(value, equalsPredicate);
const update = (updater, tags) => {
signal.update(updater, tags);
};
const setter = makeSetterWithPatches(update);
return [signal, setter];
}
static createReadonly(value) {
return _Signal.create(value)[0];
}
constructor(value, equalsPredicate) {
super();
this.value = value;
this.equalsPredicate = equalsPredicate;
this.subscribers = /* @__PURE__ */ new Set();
this.queuedUpdaters = [];
this.isEmitting = false;
}
/**
* Returns the current value of the signal.
*/
get() {
return this.value;
}
pull() {
return this.value;
}
notifyFull(value, patches, tags) {
for (const { type, callback: callback2 } of this.subscribers) {
if (type === "full") {
callback2(value, patches, tags);
}
}
}
notifyAll(value, patches, tags) {
for (const { type, callback: callback2 } of this.subscribers) {
if (type === "regular") {
callback2(value);
} else {
callback2(value, patches, tags);
}
}
}
notifyAndUpdateIfChanged(value, patches, tags) {
if (!this.equalsPredicate(this.value, value)) {
this.value = value;
this.notifyAll(value, patches, tags);
} else if (tags.length > 0) {
this.notifyFull(value, patches, tags);
}
}
isReplaceRoot(patch) {
return patch.path.length === 0 && patch.op === "replace";
}
update(updater, tags) {
this.queuedUpdaters.push([updater, tags]);
if (this.isEmitting) {
return;
}
this.isEmitting = true;
try {
while (this.queuedUpdaters.length > 0) {
let value = this.value;
let patches = [];
const tags2 = [];
while (this.queuedUpdaters.length > 0) {
const [updater2, newTags] = this.queuedUpdaters.shift();
const [newValue, newPatches] = updater2(value);
value = newValue;
const rootReplacerIndex = newPatches.findIndex(this.isReplaceRoot);
if (rootReplacerIndex !== -1) {
patches = newPatches.slice(rootReplacerIndex);
} else {
patches.push(...newPatches);
}
if (newTags !== void 0) {
tags2.push(...newTags);
}
}
this.notifyAndUpdateIfChanged(value, patches, tags2);
}
} finally {
this.isEmitting = false;
}
}
/**
* Subscribes to the signal. The callback will be called whenever the value changes. All callbacks
* are called synchronously upon updating. It will NOT be immediately called with the current
* value. (Use `get()` to get the current value.) Returns a function to unsubscribe.
*
* Edge cases involving manipulating the signal in the callback:
*
* - If the callback adds new subscribers, they will also be called within the same update.
* - If the callback causes removal of subscribers that have not been called yet, they will no
* longer be called.
* - If the callback causes an update of the value, the update will be queued. If multiple updates
* are queued, only the last one will be executed.
*
* Edge cases involving adding the same callback multiple times.
*
* - Callbacks are tracked with a set. Adding the same subscriber will not cause it to be called
* multiple times.
*/
subscribe(callback2) {
const subscriber = {
type: "regular",
callback: callback2
};
this.subscribers.add(subscriber);
return () => {
this.subscribers.delete(subscriber);
};
}
/**
* Subscribes to the signal with the callback and trigger the callback immediately with the
* current value.
*/
subscribeAndNow(callback2) {
const unsubscribe = this.subscribe(callback2);
callback2(this.value);
return unsubscribe;
}
subscribeFull(callback2) {
const subscriber = {
type: "full",
callback: callback2
};
this.subscribers.add(subscriber);
return () => {
this.subscribers.delete(subscriber);
};
}
/**
* Wait until the signal satisfies a predicate. If the predicate is already satisfied, it will
* return immediately. Otherwise, it will wait until the signal satisfies the predicate.
*/
async until(predicate) {
const current2 = this.get();
if (predicate(current2)) {
return current2;
}
const { promise, resolve: resolve2 } = makePromise();
const unsubscribe = this.subscribe((data) => {
if (predicate(data)) {
resolve2(data);
unsubscribe();
}
});
return await promise;
}
};
LazySignal = class _LazySignal extends Subscribable {
static {
this.NOT_AVAILABLE = Symbol("notAvailable");
}
static create(initialValue, subscribeUpstream, equalsPredicate = (a3, b4) => a3 === b4) {
return new _LazySignal(initialValue, subscribeUpstream, equalsPredicate);
}
static createWithoutInitialValue(subscribeUpstream, equalsPredicate = (a3, b4) => a3 === b4) {
const fullEqualsPredicate = (a3, b4) => {
if (a3 === _LazySignal.NOT_AVAILABLE || b4 === _LazySignal.NOT_AVAILABLE) {
return a3 === b4;
}
return equalsPredicate(a3, b4);
};
return new _LazySignal(_LazySignal.NOT_AVAILABLE, subscribeUpstream, fullEqualsPredicate);
}
static deriveFrom(sourceSignals, deriver, outputEqualsPredicate) {
let fullEqualsPredicate = void 0;
if (outputEqualsPredicate !== void 0) {
fullEqualsPredicate = (a3, b4) => {
if (a3 === _LazySignal.NOT_AVAILABLE || b4 === _LazySignal.NOT_AVAILABLE) {
return a3 === b4;
}
return outputEqualsPredicate(a3, b4);
};
}
const derive = () => {
const sourceValues = sourceSignals.map((signal) => signal.get());
if (sourceValues.some((value) => value === _LazySignal.NOT_AVAILABLE)) {
return _LazySignal.NOT_AVAILABLE;
}
return deriver(...sourceValues);
};
return new _LazySignal(derive(), (setDownstream) => {
const unsubscriber = sourceSignals.map((signal) => signal.subscribe(() => {
const value = derive();
if (isAvailable(value)) {
setDownstream(value);
}
}));
const newValue = derive();
if (isAvailable(newValue)) {
setDownstream(newValue);
}
return () => {
unsubscriber.forEach((unsub) => unsub());
};
}, fullEqualsPredicate);
}
static asyncDeriveFrom(strategy, sourceSignals, deriver, outputEqualsPredicate) {
let fullEqualsPredicate = void 0;
if (outputEqualsPredicate !== void 0) {
fullEqualsPredicate = (a3, b4) => {
if (a3 === _LazySignal.NOT_AVAILABLE || b4 === _LazySignal.NOT_AVAILABLE) {
return a3 === b4;
}
return outputEqualsPredicate(a3, b4);
};
}
let lastAppliedUpdateId = -1;
let lastIssuedUpdateId = -1;
return new _LazySignal(_LazySignal.NOT_AVAILABLE, (setDownstream) => {
const deriveAndUpdate = () => {
lastIssuedUpdateId++;
const updateId = lastIssuedUpdateId;
const sourceValues = sourceSignals.map((signal) => signal.get());
if (sourceValues.some((value) => value === _LazySignal.NOT_AVAILABLE)) {
return;
}
deriver(...sourceValues).then((result) => {
if (!isAvailable(result)) {
return;
}
switch (strategy) {
case "eager": {
if (updateId > lastAppliedUpdateId) {
lastAppliedUpdateId = updateId;
setDownstream(result);
}
break;
}
default: {
const exhaustiveCheck = strategy;
throw new Error(`Unknown strategy: ${exhaustiveCheck}`);
}
}
});
};
const unsubscriber = sourceSignals.map((signal) => signal.subscribe(() => {
deriveAndUpdate();
}));
deriveAndUpdate();
return () => {
unsubscriber.forEach((unsub) => unsub());
};
}, fullEqualsPredicate);
}
constructor(initialValue, subscribeUpstream, equalsPredicate = (a3, b4) => a3 === b4) {
super();
this.subscribeUpstream = subscribeUpstream;
this.dataIsStale = true;
this.upstreamUnsubscribe = null;
this.subscribersCount = 0;
this.isSubscribedToUpstream = false;
this.updateReceivedSynchronousCallbacks = /* @__PURE__ */ new Set();
[this.signal, this.setValue] = Signal.create(initialValue, equalsPredicate);
[this.updateReceivedEvent, this.emitUpdateReceivedEvent] = Event2.create();
}
/**
* Returns whether the value is currently stale.
*
* A value is stale whenever the upstream subscription is not active. This can happen in three
* cases:
*
* 1. When no subscriber is attached to this signal, the signal will not subscribe to the
* upstream. In this case, the value is always stale.
* 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the
* value is also stale.
* 3. When the upstream has emitted an error. In this case, the subscription to the upstream is
* terminated and the value is stale.
*
* If you wish to get the current value and ensure that it is not stale, use the method
* {@link LazySignal#pull}.
*/
isStale() {
return this.dataIsStale;
}
subscribeToUpstream() {
this.isSubscribedToUpstream = true;
let subscribed = true;
let becameStale = false;
const unsubscribeFromUpstream = this.subscribeUpstream(makeSetterWithPatches((updater, tags) => {
if (!subscribed) {
return;
}
this.setValue.withPatchUpdater(updater, tags);
this.dataIsStale = becameStale;
this.emitUpdateReceivedEvent();
for (const callback2 of this.updateReceivedSynchronousCallbacks) {
callback2();
}
}), (error) => {
if (!subscribed) {
return;
}
Promise.reject(error);
this.dataIsStale = true;
this.isSubscribedToUpstream = false;
this.upstreamUnsubscribe = null;
subscribed = false;
});
this.upstreamUnsubscribe = () => {
if (subscribed) {
subscribed = false;
becameStale = true;
unsubscribeFromUpstream();
}
};
}
unsubscribeFromUpstream() {
this.isSubscribedToUpstream = false;
if (this.upstreamUnsubscribe !== null) {
this.upstreamUnsubscribe();
this.upstreamUnsubscribe = null;
this.dataIsStale = true;
}
}
/**
* Gets the current value of the signal. If the value is not available, it will return
* {@link LazySignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created
* without an initial value and the upstream has not emitted a value yet.)
*
* In addition, the value returned by this method may be stale. Use {@link LazySignal#isStale} to
* check if the value is stale.
*
* If you wish to get the current value and ensure that it is not stale, use the method
* {@link LazySignal#pull}.
*/
get() {
return this.signal.get();
}
/**
* Pulls the current value of the signal. If the value is stale, it will subscribe and wait for
* the next value from the upstream and return it.
*/
async pull() {
const { promise, resolve: resolve2 } = makePromise();
if (!this.isStale()) {
resolve2(this.get());
} else {
const unsubscribe = this.subscribe(() => {
});
this.updateReceivedEvent.subscribeOnce(() => {
resolve2(this.get());
});
promise.then(unsubscribe);
}
return promise;
}
/**
* If the data is not stale, the callback will be called synchronously with the current value.
*
* If the data is stale, it will pull the current value and call the callback with the value.
*/
runOnNextFreshData(callback2) {
if (!this.isStale()) {
callback2(this.get());
} else {
let unsubscribe = null;
const updateCallback = () => {
this.updateReceivedSynchronousCallbacks.delete(updateCallback);
callback2(this.get());
unsubscribe?.();
};
this.updateReceivedSynchronousCallbacks.add(updateCallback);
unsubscribe = this.subscribe(() => {
});
}
}
async ensureAvailable() {
await this.pull();
return this;
}
subscribe(subscriber) {
if (!this.isSubscribedToUpstream) {
this.subscribeToUpstream();
}
this.subscribersCount++;
const unsubscribe = this.signal.subscribe(subscriber);
let unsubscribeCalled = false;
return () => {
if (unsubscribeCalled) {
return;
}
unsubscribe();
unsubscribeCalled = true;
this.subscribersCount--;
if (this.subscribersCount === 0 && this.isSubscribedToUpstream) {
this.unsubscribeFromUpstream();
}
};
}
subscribeFull(subscriber) {
if (!this.isSubscribedToUpstream) {
this.subscribeToUpstream();
}
this.subscribersCount++;
const unsubscribe = this.signal.subscribeFull(subscriber);
let unsubscribeCalled = false;
return () => {
if (unsubscribeCalled) {
return;
}
unsubscribe();
unsubscribeCalled = true;
this.subscribersCount--;
if (this.subscribersCount === 0 && this.isSubscribedToUpstream) {
this.unsubscribeFromUpstream();
}
};
}
/**
* Subscribes to the signal. Will not cause the signal to subscribe to the upstream.
*/
passiveSubscribe(subscriber) {
return this.signal.subscribe(subscriber);
}
passiveSubscribeFull(subscriber) {
return this.signal.subscribeFull(subscriber);
}
async until(predicate) {
const current2 = this.get();
if (isAvailable(current2) && predicate(current2)) {
return current2;
}
const { promise, resolve: resolve2 } = makePromise();
const unsubscribe = this.subscribe((data) => {
if (isAvailable(data) && predicate(data)) {
resolve2(data);
unsubscribe();
}
});
return await promise;
}
};
apiServerPorts = [41343, 52993, 16141, 39414, 22931];
waitForNextMicroTask = Symbol();
BufferedEvent = class _BufferedEvent extends Subscribable {
static create() {
const event = new _BufferedEvent();
const emitter = (data) => {
event.emit(data);
};
return [event, emitter];
}
constructor() {
super();
this.subscriber = null;
this.queued = [];
this.isNotifying = false;
}
emit(data) {
if (this.queued.length === 0 && this.queued.at(-1) !== waitForNextMicroTask) {
this.queued.push(waitForNextMicroTask);
}
this.queued.push(data);
if (!this.isNotifying) {
this.notifier();
}
}
async notifier() {
this.isNotifying = true;
while (this.subscriber !== null && this.queued.length > 0) {
const data = this.queued.shift();
if (data === waitForNextMicroTask) {
await Promise.resolve();
} else {
this.subscriber(data);
}
}
this.isNotifying = false;
}
subscribe(listener) {
if (this.subscriber !== null) {
throw new Error("Cannot have more than one subscriber");
}
this.subscriber = listener;
if (!this.isNotifying && this.queued.length > 0) {
this.queued = [
waitForNextMicroTask,
...this.queued.filter((data) => data !== waitForNextMicroTask)
];
this.notifier();
}
return () => {
this.subscriber = null;
};
}
/**
* Convert this buffered event to an event by stop buffering and triggering events on the new
* returned event.
*/
flow() {
const [event, emit] = Event2.create();
this.subscribe(emit);
return event;
}
};
CancelEvent = class extends Subscribable {
constructor() {
super(...arguments);
this.canceled = false;
this.listeners = /* @__PURE__ */ new Set();
}
subscribe(listener) {
if (this.canceled) {
let callbackCanceled = false;
Promise.resolve().then(() => {
if (!callbackCanceled) {
listener();
}
});
return () => {
callbackCanceled = true;
};
}
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
cancel() {
if (this.canceled) {
throw new Error("Already canceled");
}
this.canceled = true;
for (const listener of this.listeners) {
listener();
}
}
isCanceled() {
return this.canceled;
}
};
Cleaner = class {
constructor() {
this.eagerCleaned = false;
this.disposed = false;
this.cleanups = [];
}
register(fn) {
if (this.eagerCleaned) {
throw new Error("Cannot register a cleanup after eagerClean() was called.");
}
if (this.disposed) {
throw new Error("Cannot register a cleanup after the Cleaner was disposed.");
}
this.cleanups.push(fn);
}
runCleanersInternal() {
for (const cleanup of this.cleanups) {
cleanup();
}
this.cleanups.length = 0;
}
[Symbol.dispose]() {
if (this.eagerCleaned) {
return;
}
if (this.disposed) {
throw new Error("Cannot dispose a Cleaner that was already disposed.");
}
this.runCleanersInternal();
}
eagerClean() {
if (this.eagerCleaned) {
throw new Error("Cannot call eagerClean() twice.");
}
if (this.disposed) {
throw new Error("Cannot call eagerClean() after the Cleaner was disposed.");
}
this.eagerCleaned = true;
this.runCleanersInternal();
}
};
IdGiver = class {
constructor(firstId = 0) {
this.nextId = firstId;
}
next() {
const id = this.nextId;
this.nextId++;
return id;
}
};
boxen$1 = { exports: {} };
stringWidth = { exports: {} };
isFullwidthCodePoint = { exports: {} };
widestLine = { exports: {} };
cliBoxes = { exports: {} };
single = {
topLeft: "\u250C",
topRight: "\u2510",
bottomRight: "\u2518",
bottomLeft: "\u2514",
vertical: "\u2502",
horizontal: "\u2500"
};
double = {
topLeft: "\u2554",
topRight: "\u2557",
bottomRight: "\u255D",
bottomLeft: "\u255A",
vertical: "\u2551",
horizontal: "\u2550"
};
round = {
topLeft: "\u256D",
topRight: "\u256E",
bottomRight: "\u256F",
bottomLeft: "\u2570",
vertical: "\u2502",
horizontal: "\u2500"
};
bold = {
topLeft: "\u250F",
topRight: "\u2513",
bottomRight: "\u251B",
bottomLeft: "\u2517",
vertical: "\u2503",
horizontal: "\u2501"
};
singleDouble = {
topLeft: "\u2553",
topRight: "\u2556",
bottomRight: "\u255C",
bottomLeft: "\u2559",
vertical: "\u2551",
horizontal: "\u2500"
};
doubleSingle = {
topLeft: "\u2552",
topRight: "\u2555",
bottomRight: "\u255B",
bottomLeft: "\u2558",
vertical: "\u2502",
horizontal: "\u2550"
};
classic = {
topLeft: "+",
topRight: "+",
bottomRight: "+",
bottomLeft: "+",
vertical: "|",
horizontal: "-"
};
require$$0 = {
single,
double,
round,
bold,
singleDouble,
doubleSingle,
classic
};
camelcase = { exports: {} };
ansiStyles = { exports: {} };
ansiStyles.exports;
boxenExports = requireBoxen();
boxen = /* @__PURE__ */ getDefaultExportFromCjs(boxenExports);
compiledTemplatesCache = /* @__PURE__ */ new WeakMap();
MaybeMutable = class {
constructor(data, mutable) {
this.data = data;
this.mutable = mutable;
}
/**
* Gets the underlying data without any access control. Only used internally.
*
* @internal
*/
_internalGetData() {
return this.data;
}
/**
* If this instance is mutable, return as is.
*
* If this instance is immutable, return a mutable copy.
*
* Very easy to misuse, thus internal only for now.
*
* @internal
*/
_internalToMutable() {
if (this.mutable) {
return this;
}
return this.asMutableCopy();
}
asMutableCopy() {
return this.create(this.cloneData(this.data), true);
}
asImmutableCopy() {
if (this.mutable) {
return this.create(this.cloneData(this.data), false);
}
return this;
}
guardMutable() {
if (!this.mutable) {
throw new Error(text`
Cannot modify immutable ${this.getClassName()} instance. Use asMutableCopy() to get a
mutable copy.
`);
}
}
};
OWLSignal = class _OWLSignal extends Subscribable {
static {
this.NOT_AVAILABLE = LazySignal.NOT_AVAILABLE;
}
applyOptimisticUpdates(data) {
for (const update of this.queuedUpdates) {
[data] = update.updater(data);
}
return data;
}
updateOptimisticValue(tags) {
const innerValue = this.innerSignal.get();
if (!isAvailable(innerValue)) {
return;
}
this.setOuterSignal(this.applyOptimisticUpdates(innerValue), tags);
}
constructor(initialValue, subscribeUpstream, writeUpstream, equalsPredicate) {
super();
this.writeUpstream = writeUpstream;
this.isWriteLoopRunning = false;
this.isSubscriptionHandledByWriteLoop = false;
this.queuedUpdates = [];
this.currentEnsureAvailablePromise = null;
[this.writeErrorEvent, this.emitWriteErrorEvent] = Event2.create();
[this.outerSignal, this.setOuterSignal] = Signal.create(initialValue, equalsPredicate);
this.innerSignal = LazySignal.create(initialValue, subscribeUpstream, equalsPredicate);
this.innerSignal.passiveSubscribeFull((_data, _patches, tags) => {
if (this.isSubscriptionHandledByWriteLoop) {
return;
}
this.updateOptimisticValue(tags);
});
}
static create(initialValue, subscribeUpstream, writeUpstream, equalsPredicate = (a3, b4) => a3 === b4) {
const signal = new _OWLSignal(initialValue, subscribeUpstream, writeUpstream, equalsPredicate);
const setSignal = makeSetterWithPatches(signal.update.bind(signal));
const emitError = (tags, error) => signal.emitWriteErrorEvent({ tags, error });
return [signal, setSignal, emitError];
}
static createWithoutInitialValue(subscribeUpstream, writeUpstream, equalsPredicate = (a3, b4) => a3 === b4) {
const fullEqualsPredicate = (a3, b4) => {
if (a3 === _OWLSignal.NOT_AVAILABLE || b4 === _OWLSignal.NOT_AVAILABLE) {
return a3 === b4;
}
return equalsPredicate(a3, b4);
};
return _OWLSignal.create(_OWLSignal.NOT_AVAILABLE, subscribeUpstream, writeUpstream, fullEqualsPredicate);
}
async update(updater, tags) {
const { promise, reject, resolve: resolve2 } = makePromise();
this.queuedUpdates.push({
updater,
tags: tags ?? [],
resolve: resolve2,
reject
});
this.updateOptimisticValue();
this.ensureWriteLoop();
return promise;
}
/**
* Starts the write loop if it is not already running.
*/
ensureWriteLoop() {
if (!this.isWriteLoopRunning) {
this.writeLoop();
}
}
/**
* The main write loop, it will keep running until there are no more updates to process.
*/
async writeLoop() {
const unsubscribe = this.innerSignal.subscribe(() => {
});
this.isWriteLoopRunning = true;
if (this.isStale()) {
await this.innerSignal.pull();
}
while (this.queuedUpdates.length > 0) {
const numQueuedUpdatesToHandle = this.queuedUpdates.length;
const updater = (data) => {
const patches = [];
for (let i7 = 0; i7 < numQueuedUpdatesToHandle; i7++) {
const [newData, newPatches] = this.queuedUpdates[i7].updater(data);
data = newData;
patches.push(...newPatches);
}
return [data, patches];
};
const resolve2 = () => {
for (let i7 = 0; i7 < numQueuedUpdatesToHandle; i7++) {
this.queuedUpdates[i7].resolve();
}
};
const reject = (error) => {
for (let i7 = 0; i7 < numQueuedUpdatesToHandle; i7++) {
this.queuedUpdates[i7].reject(error);
}
};
const queuedUpdateTags = this.queuedUpdates.flatMap((update) => update.tags);
const tag = Date.now() + "-" + Math.random();
await new Promise((nextStep) => {
this.isSubscriptionHandledByWriteLoop = true;
const unsubscribeArray = [];
const settle = () => {
this.isSubscriptionHandledByWriteLoop = false;
unsubscribeArray.forEach((unsubscribe2) => unsubscribe2());
nextStep();
};
unsubscribeArray.push(this.innerSignal.subscribeFull((_data, _patches, tags) => {
if (!this.isSubscriptionHandledByWriteLoop) {
return;
}
if (tags?.includes(tag)) {
settle();
resolve2();
this.queuedUpdates.splice(0, numQueuedUpdatesToHandle);
this.updateOptimisticValue(tags.filter((t6) => t6 !== tag));
} else {
this.updateOptimisticValue(tags);
}
}));
unsubscribeArray.push(this.writeErrorEvent.subscribe(({ tags, error }) => {
if (!this.isSubscriptionHandledByWriteLoop) {
return;
}
if (tags.includes(tag)) {
settle();
reject(error);
this.queuedUpdates.splice(0, numQueuedUpdatesToHandle);
}
}));
const sent = this.writeUpstream(...updater(this.innerSignal.get()), [tag, ...queuedUpdateTags]);
if (!sent) {
settle();
resolve2();
this.queuedUpdates.splice(0, numQueuedUpdatesToHandle);
this.updateOptimisticValue(queuedUpdateTags.filter((t6) => t6 !== tag));
}
});
}
this.isWriteLoopRunning = false;
unsubscribe();
}
/**
* Returns whether the value is currently stale.
*
* A value is stale whenever the upstream subscription is not active. This can happen in three
* cases:
*
* 1. When no subscriber is attached to this signal, the signal will not subscribe to the
* upstream. In this case, the value is always stale.
* 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the
* value is also stale.
* 3. When the upstream has emitted an error. In this case, the subscription to the upstream is
* terminated and the value is stale.
*
* If you wish to get the current value and ensure that it is not stale, use the method
* {@link OWLSignal#pull}.
*/
isStale() {
return this.innerSignal.isStale();
}
/**
* Gets the current value of the signal. If the value is not available, it will return
* {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created
* without an initial value and the upstream has not emitted a value yet.)
*
* In addition, the value returned by this method may be stale. Use {@link OWLSignal#isStale} to
* check if the value is stale.
*
* If you wish to get the current value and ensure that it is not stale, use the method
* {@link OWLSignal#pull}.
*/
get() {
return this.outerSignal.get();
}
/**
* Gets the current value of the signal pessimistically. If the value is not available, it will
* return {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is
* created without an initial value and the upstream has not emitted a value yet.)
*/
getPessimistic() {
return this.innerSignal.get();
}
/**
* Pulls the current value of the signal. If the value is stale, it will subscribe and wait for
* the next value from the upstream and return it.
*
* You must also provide an `optimistic` flag. If `optimistic` is true, the pending optimistic
* updates will be applied to the value before returning it.
*/
async pull({ optimistic = true } = {}) {
if (optimistic) {
return this.applyOptimisticUpdates(await this.innerSignal.pull());
} else {
return this.innerSignal.pull();
}
}
async ensureAvailable() {
if (this.currentEnsureAvailablePromise === null) {
this.currentEnsureAvailablePromise = (async () => {
await this.innerSignal.pull();
return this;
})();
}
return this.currentEnsureAvailablePromise;
}
subscribe(subscriber) {
const unsubscribeOuter = this.outerSignal.subscribe(subscriber);
const unsubscribeInner = this.innerSignal.subscribe(() => {
});
return () => {
unsubscribeOuter();
unsubscribeInner();
};
}
subscribeFull(subscriber) {
const unsubscribeOuter = this.outerSignal.subscribeFull(subscriber);
const unsubscribeInner = this.innerSignal.subscribeFull(() => {
});
return () => {
unsubscribeOuter();
unsubscribeInner();
};
}
};
allowableEnvVarKeys = ["HSA_OVERRIDE_GFX_VERSION"];
allowableEnvVarKeysSchema = external_exports.enum(allowableEnvVarKeys);
allowableEnvVarsSchema = external_exports.record(allowableEnvVarKeysSchema, external_exports.string());
kebabCaseRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
kebabCaseSchema = external_exports.string().regex(kebabCaseRegex);
kebabCaseWithDotsRegex = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/;
kebabCaseWithDotsSchema = external_exports.string().regex(kebabCaseWithDotsRegex);
fileNameRegex = /^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(? {
try {
return JSON.parse(JSON.stringify(val2));
} catch (e9) {
ctx.addIssue({
code: external_exports.ZodIssueCode.custom,
message: "Not JSON serializable: " + e9.message
});
return val2;
}
});
chatMessagePartTextDataSchema = external_exports.object({
type: external_exports.literal("text"),
text: external_exports.string()
});
chatMessagePartFileDataSchema = external_exports.object({
type: external_exports.literal("file"),
name: external_exports.string(),
identifier: external_exports.string(),
sizeBytes: external_exports.number().int(),
fileType: fileTypeSchema
});
functionToolCallRequestSchema = external_exports.object({
id: external_exports.string().optional(),
type: external_exports.literal("function"),
arguments: external_exports.record(jsonSerializableSchema).optional(),
name: external_exports.string()
});
toolCallRequestSchema = external_exports.discriminatedUnion("type", [
functionToolCallRequestSchema
]);
chatMessagePartToolCallRequestDataSchema = external_exports.object({
type: external_exports.literal("toolCallRequest"),
toolCallRequest: toolCallRequestSchema
});
external_exports.object({
content: external_exports.string(),
toolCallId: external_exports.string().optional()
});
chatMessagePartToolCallResultDataSchema = external_exports.object({
type: external_exports.literal("toolCallResult"),
content: external_exports.string(),
toolCallId: external_exports.string().optional()
});
external_exports.discriminatedUnion("type", [
chatMessagePartTextDataSchema,
chatMessagePartFileDataSchema,
chatMessagePartToolCallRequestDataSchema,
chatMessagePartToolCallResultDataSchema
]);
external_exports.enum(["assistant", "user", "system", "tool"]);
chatMessageDataSchema = external_exports.discriminatedUnion("role", [
external_exports.object({
role: external_exports.literal("assistant"),
content: external_exports.array(external_exports.discriminatedUnion("type", [
chatMessagePartTextDataSchema,
chatMessagePartFileDataSchema,
chatMessagePartToolCallRequestDataSchema
]))
}),
external_exports.object({
role: external_exports.literal("user"),
content: external_exports.array(external_exports.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema]))
}),
external_exports.object({
role: external_exports.literal("system"),
content: external_exports.array(external_exports.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema]))
}),
external_exports.object({
role: external_exports.literal("tool"),
content: external_exports.array(chatMessagePartToolCallResultDataSchema)
})
]);
chatHistoryDataSchema = external_exports.object({
messages: external_exports.array(chatMessageDataSchema)
});
citationSourceSchema = external_exports.object({
fileName: external_exports.string(),
absoluteFilePath: external_exports.string().optional(),
pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(),
lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional()
});
colorPalette = external_exports.enum([
"red",
"green",
"blue",
"yellow",
"orange",
"purple",
"default"
]);
colorPaletteSchema = colorPalette;
diagnosticsLogEventDataSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("llm.prediction.input"),
modelPath: external_exports.string(),
modelIdentifier: external_exports.string(),
input: external_exports.string()
})
]);
diagnosticsLogEventSchema = external_exports.object({
timestamp: external_exports.number(),
data: diagnosticsLogEventDataSchema
});
llmLlamaAccelerationOffloadRatioSchema = external_exports.union([
external_exports.number().min(0).max(1),
external_exports.literal("max"),
external_exports.literal("off")
]);
llmSplitStrategySchema = external_exports.enum(["evenly", "favorMainGpu"]);
gpuSettingSchema = external_exports.object({
ratio: llmLlamaAccelerationOffloadRatioSchema.optional(),
mainGpu: external_exports.number().int().optional(),
splitStrategy: llmSplitStrategySchema.optional(),
disabledGpus: external_exports.array(external_exports.number().int()).optional()
});
llmLlamaCacheQuantizationTypes = [
"f32",
"f16",
"q8_0",
"q4_0",
"q4_1",
"iq4_nl",
"q5_0",
"q5_1"
];
llmLlamaCacheQuantizationTypeSchema = external_exports.enum(llmLlamaCacheQuantizationTypes);
llmMlxKvCacheBitsTypeSchema = external_exports.union([
external_exports.literal(8),
external_exports.literal(6),
external_exports.literal(4),
external_exports.literal(3),
external_exports.literal(2)
]);
llmMlxKvCacheGroupSizeTypesSchema = external_exports.union([
external_exports.literal(32),
external_exports.literal(64),
external_exports.literal(128)
]);
llmMlxKvCacheQuantizationSchema = external_exports.object({
enabled: external_exports.boolean(),
bits: llmMlxKvCacheBitsTypeSchema,
groupSize: llmMlxKvCacheGroupSizeTypesSchema,
quantizedStart: external_exports.number().int().nonnegative()
});
llmLoadModelConfigSchema = external_exports.object({
gpu: gpuSettingSchema.optional(),
gpuStrictVramCap: external_exports.boolean().optional(),
offloadKVCacheToGpu: external_exports.boolean().optional(),
contextLength: external_exports.number().int().min(1).optional(),
ropeFrequencyBase: external_exports.number().optional(),
ropeFrequencyScale: external_exports.number().optional(),
evalBatchSize: external_exports.number().int().min(1).optional(),
flashAttention: external_exports.boolean().optional(),
keepModelInMemory: external_exports.boolean().optional(),
seed: external_exports.number().int().optional(),
useFp16ForKVCache: external_exports.boolean().optional(),
tryMmap: external_exports.boolean().optional(),
numExperts: external_exports.number().int().optional(),
llamaKCacheQuantizationType: external_exports.enum(llmLlamaCacheQuantizationTypes).or(external_exports.literal(false)).optional(),
llamaVCacheQuantizationType: external_exports.enum(llmLlamaCacheQuantizationTypes).or(external_exports.literal(false)).optional()
});
embeddingLoadModelConfigSchema = external_exports.object({
gpu: gpuSettingSchema.optional(),
contextLength: external_exports.number().int().min(1).optional(),
ropeFrequencyBase: external_exports.number().optional(),
ropeFrequencyScale: external_exports.number().optional(),
keepModelInMemory: external_exports.boolean().optional(),
tryMmap: external_exports.boolean().optional()
});
modelCompatibilityTypeSchema = external_exports.enum([
"gguf",
"safetensors",
"onnx",
"ggml",
"mlx_placeholder",
"torch_safetensors"
]);
quantizationSchema = external_exports.object({
name: external_exports.string(),
bits: external_exports.number().int()
});
modelInfoBaseSchema = external_exports.object({
modelKey: external_exports.string(),
format: modelCompatibilityTypeSchema,
displayName: external_exports.string(),
path: external_exports.string(),
sizeBytes: external_exports.number().int(),
paramsString: external_exports.string().optional(),
architecture: external_exports.string().optional(),
quantization: quantizationSchema.optional()
});
modelInstanceInfoBaseSchema = modelInfoBaseSchema.extend({
identifier: external_exports.string(),
instanceReference: external_exports.string()
});
embeddingModelAdditionalInfoSchema = external_exports.object({
maxContextLength: external_exports.number().int()
});
embeddingModelInstanceAdditionalInfoSchema = external_exports.object({
contextLength: external_exports.number().int()
});
embeddingModelInfoSchema = external_exports.object({
type: external_exports.literal("embedding")
}).extend(modelInfoBaseSchema.shape).extend(embeddingModelAdditionalInfoSchema.shape);
embeddingModelInstanceInfoSchema = external_exports.object({ type: external_exports.literal("embedding") }).extend(modelInstanceInfoBaseSchema.shape).extend(embeddingModelAdditionalInfoSchema.shape).extend(embeddingModelInstanceAdditionalInfoSchema.shape);
modelDomainTypeSchema = external_exports.enum([
"llm",
"embedding",
"imageGen",
"transcription",
"tts"
]);
reasonableKeyStringSchema = external_exports.string().min(1).max(1024).refine((value) => value !== "__proto__", {
message: 'For security reasons, "__proto__" is not allowed'
}).refine((value) => new RegExp("\\p{C}", "u").test(value) === false, {
message: "Control characters are not allowed"
});
modelQuerySchema = external_exports.object({
domain: modelDomainTypeSchema.optional(),
identifier: reasonableKeyStringSchema.optional(),
path: reasonableKeyStringSchema.optional(),
vision: external_exports.boolean().optional()
});
modelSpecifierSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("query"),
query: modelQuerySchema
}),
external_exports.object({
type: external_exports.literal("instanceReference"),
instanceReference: external_exports.string()
})
]);
genericErrorDisplayDataSchema = [
external_exports.object({
code: external_exports.literal("generic.specificModelUnloaded")
}),
external_exports.object({
code: external_exports.literal("generic.noModelMatchingQuery"),
query: modelQuerySchema,
loadedModelsSample: external_exports.array(external_exports.string()),
totalLoadedModels: external_exports.number().int()
}),
external_exports.object({
code: external_exports.literal("generic.pathNotFound"),
path: external_exports.string(),
availablePathsSample: external_exports.array(external_exports.string()),
totalModels: external_exports.number().int()
}),
external_exports.object({
code: external_exports.literal("generic.identifierNotFound"),
identifier: external_exports.string(),
loadedModelsSample: external_exports.array(external_exports.string()),
totalLoadedModels: external_exports.number().int()
}),
external_exports.object({
code: external_exports.literal("generic.domainMismatch"),
path: external_exports.string(),
actualDomain: modelDomainTypeSchema,
expectedDomain: modelDomainTypeSchema
}),
external_exports.object({
code: external_exports.literal("generic.engineDoesNotSupportFeature"),
feature: external_exports.string(),
engineName: external_exports.string(),
engineType: external_exports.string(),
installedVersion: external_exports.string(),
supportedVersion: external_exports.string().nullable()
}),
external_exports.object({
code: external_exports.literal("generic.presetNotFound"),
specifiedFuzzyPresetIdentifier: external_exports.string(),
availablePresetsSample: external_exports.array(external_exports.object({
identifier: external_exports.string(),
name: external_exports.string()
})),
totalAvailablePresets: external_exports.number().int()
})
];
llmErrorDisplayDataSchema = [];
errorDisplayDataSchema = external_exports.discriminatedUnion("code", [
...llmErrorDisplayDataSchema,
...genericErrorDisplayDataSchema
]);
serializedLMSExtendedErrorSchema = external_exports.object({
title: failOk(external_exports.string()).default("Unknown error"),
cause: failOk(external_exports.string()).optional(),
suggestion: failOk(external_exports.string()).optional(),
errorData: failOk(external_exports.record(external_exports.string(), external_exports.unknown())).optional(),
displayData: failOk(errorDisplayDataSchema).optional(),
stack: failOk(external_exports.string()).optional(),
rootTitle: failOk(external_exports.string()).optional()
});
documentParsingLibraryIdentifierSchema = external_exports.object({
library: external_exports.string(),
version: external_exports.string()
});
documentParsingOptsSchema = external_exports.object({
parserId: documentParsingLibraryIdentifierSchema.optional()
});
external_exports.enum(["local", "base64"]);
external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("local"),
fileName: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("base64"),
base64Data: external_exports.string()
})
]);
gpuSplitStrategies = ["evenly", "priorityOrder", "custom"];
gpuSplitStrategySchema = external_exports.enum(gpuSplitStrategies);
defaultGPUSplitConfig = {
strategy: "evenly",
disabledGpus: [],
priority: [],
customRatio: []
};
gpuSplitConfigSchema = external_exports.object({
strategy: gpuSplitStrategySchema,
disabledGpus: external_exports.array(external_exports.number().int().min(0)),
priority: external_exports.array(external_exports.number().int().min(0)),
customRatio: external_exports.array(external_exports.number().min(0))
});
kvConfigFieldSchema = external_exports.object({
key: external_exports.string(),
value: external_exports.any()
});
kvConfigSchema = external_exports.object({
fields: external_exports.array(kvConfigFieldSchema)
});
kvConfigLayerNameSchema = external_exports.enum([
"currentlyEditing",
"currentlyLoaded",
"apiOverride",
"conversationSpecific",
"conversationGlobal",
"preset",
"serverSession",
"httpServerRequestOverride",
"completeModeFormatting",
"instance",
"userModelDefault",
"virtualModel",
"modelDefault",
"hardware"
]);
kvConfigStackLayerSchema = external_exports.object({
layerName: kvConfigLayerNameSchema,
config: kvConfigSchema
});
kvConfigStackSchema = external_exports.object({
layers: external_exports.array(kvConfigStackLayerSchema)
});
kvConfigFieldDependencySchema = external_exports.object({
key: external_exports.string(),
condition: external_exports.discriminatedUnion("type", [
external_exports.object({ type: external_exports.literal("equals"), value: external_exports.any() }),
external_exports.object({ type: external_exports.literal("notEquals"), value: external_exports.any() })
])
});
contentBlockStyleSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("default")
}),
external_exports.object({
type: external_exports.literal("customLabel"),
label: external_exports.string(),
color: external_exports.optional(colorPaletteSchema)
}),
external_exports.object({
type: external_exports.literal("thinking"),
ended: external_exports.boolean().optional(),
title: external_exports.string().optional()
})
]);
llmToolParametersSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("object"),
properties: external_exports.record(jsonSerializableSchema),
required: external_exports.array(external_exports.string()).optional(),
additionalProperties: external_exports.boolean().optional(),
$defs: external_exports.record(jsonSerializableSchema).optional()
})
// add more parameter types here
// ...
]);
llmToolSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("function"),
function: external_exports.object({
name: external_exports.string(),
description: external_exports.string().optional(),
parameters: llmToolParametersSchema.optional()
})
})
// add more tool types here
// ...
]);
external_exports.array(llmToolSchema);
llmToolUseSettingSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("none")
}),
external_exports.object({
type: external_exports.literal("toolArray"),
tools: external_exports.array(llmToolSchema).optional(),
force: external_exports.boolean().optional()
})
]);
llmApplyPromptTemplateOptsSchema = external_exports.object({
omitBosToken: external_exports.boolean().optional(),
omitEosToken: external_exports.boolean().optional(),
toolDefinitions: external_exports.array(llmToolSchema).optional()
});
llmContextReferenceSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("jsonFile"),
absPath: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("yamlFile"),
absPath: external_exports.string()
})
]);
external_exports.array(external_exports.object({
role: external_exports.enum(["user", "assistant", "system"]),
content: external_exports.string()
}));
external_exports.array(external_exports.union([
external_exports.object({
system: external_exports.string()
}),
external_exports.object({
user: external_exports.string()
}),
external_exports.object({
assistant: external_exports.string()
})
]));
llmAdditionalInfoSchema = external_exports.object({
vision: external_exports.boolean(),
trainedForToolUse: external_exports.boolean(),
maxContextLength: external_exports.number().int()
});
llmInstanceAdditionalInfoSchema = external_exports.object({
contextLength: external_exports.number().int()
});
llmInfoSchema = external_exports.object({
type: external_exports.literal("llm")
}).extend(modelInfoBaseSchema.shape).extend(llmAdditionalInfoSchema.shape);
llmInstanceInfoSchema = external_exports.object({
type: external_exports.literal("llm")
}).extend(modelInstanceInfoBaseSchema.shape).extend(llmAdditionalInfoSchema.shape).extend(llmInstanceAdditionalInfoSchema.shape);
toolNamingSchema = external_exports.enum(["passThrough", "removeSpecial", "snakeCase", "camelCase"]);
zodSchemaSchema = external_exports.custom((value) => {
if (typeof value?.parse !== "function") {
return false;
}
return true;
}, "Expected a zod schema");
llmManualPromptTemplateSchema = external_exports.object({
beforeSystem: external_exports.string(),
afterSystem: external_exports.string(),
beforeUser: external_exports.string(),
afterUser: external_exports.string(),
beforeAssistant: external_exports.string(),
afterAssistant: external_exports.string()
});
llmJinjaPromptTemplateSchema = external_exports.object({
template: external_exports.string()
});
llmPromptTemplateTypeSchema = external_exports.enum(["manual", "jinja"]);
llmPromptTemplateSchema = external_exports.object({
type: llmPromptTemplateTypeSchema,
manualPromptTemplate: llmManualPromptTemplateSchema.optional(),
jinjaPromptTemplate: llmJinjaPromptTemplateSchema.optional(),
stopStrings: external_exports.array(external_exports.string())
});
llmStructuredPredictionTypeSchema = external_exports.enum(["none", "json", "gbnf"]);
llmStructuredPredictionSettingSchema = external_exports.object({
type: llmStructuredPredictionTypeSchema,
jsonSchema: jsonSerializableSchema.optional(),
gbnfGrammar: external_exports.string().optional()
});
llmContextOverflowPolicySchema = external_exports.enum([
"stopAtLimit",
"truncateMiddle",
"rollingWindow"
]);
llmReasoningParsingSchema = external_exports.object({
enabled: external_exports.boolean(),
startString: external_exports.string(),
endString: external_exports.string()
});
llmPredictionConfigInputSchema = external_exports.object({
maxTokens: external_exports.number().int().min(-1).optional().or(external_exports.literal(false)),
temperature: external_exports.number().min(0).optional(),
stopStrings: external_exports.array(external_exports.string()).optional(),
toolCallStopStrings: external_exports.array(external_exports.string()).optional(),
contextOverflowPolicy: llmContextOverflowPolicySchema.optional(),
structured: external_exports.union([zodSchemaSchema, llmStructuredPredictionSettingSchema]).optional(),
rawTools: llmToolUseSettingSchema.optional(),
toolNaming: toolNamingSchema.optional(),
topKSampling: external_exports.number().optional(),
repeatPenalty: external_exports.number().optional().or(external_exports.literal(false)),
minPSampling: external_exports.number().optional().or(external_exports.literal(false)),
topPSampling: external_exports.number().optional().or(external_exports.literal(false)),
cpuThreads: external_exports.number().int().optional(),
promptTemplate: llmPromptTemplateSchema.optional(),
draftModel: external_exports.string().optional(),
speculativeDecodingNumDraftTokensExact: external_exports.number().int().min(1).optional(),
speculativeDecodingMinDraftLengthToConsider: external_exports.number().int().min(0).optional(),
speculativeDecodingMinContinueDraftingProbability: external_exports.number().optional(),
reasoningParsing: llmReasoningParsingSchema.optional(),
raw: kvConfigSchema.optional()
});
external_exports.object({
...llmPredictionConfigInputSchema.shape,
structured: llmStructuredPredictionSettingSchema.optional()
});
llmLlamaMirostatSamplingConfigSchema = external_exports.object({
version: external_exports.union([external_exports.literal(0), external_exports.literal(1), external_exports.literal(2)]),
learningRate: external_exports.number(),
targetEntropy: external_exports.number()
});
llmLlamaSingleLogitBiasModificationSchema = external_exports.union([external_exports.number(), external_exports.literal("-inf")]);
llmLlamaLogitBiasConfigSchema = external_exports.array(external_exports.tuple([external_exports.number(), llmLlamaSingleLogitBiasModificationSchema]));
llmPredictionFragmentReasoningTypeSchema = external_exports.enum([
"none",
"reasoning",
"reasoningStartTag",
"reasoningEndTag"
]);
llmPredictionFragmentSchema = external_exports.object({
content: external_exports.string(),
tokensCount: external_exports.number().int(),
containsDrafted: external_exports.boolean(),
reasoningType: llmPredictionFragmentReasoningTypeSchema,
isStructural: external_exports.boolean()
});
llmPredictionFragmentInputOptsSchema = external_exports.object({
tokenCount: external_exports.number().int().optional(),
containsDrafted: external_exports.boolean().optional(),
reasoningType: llmPredictionFragmentReasoningTypeSchema.optional(),
isStructural: external_exports.boolean().optional()
});
llmPredictionStopReasonSchema = external_exports.enum([
"userStopped",
"modelUnloaded",
"failed",
"eosFound",
"stopStringFound",
"toolCalls",
"maxPredictedTokensReached",
"contextLengthReached"
]);
llmPredictionStatsSchema = external_exports.object({
stopReason: llmPredictionStopReasonSchema,
tokensPerSecond: external_exports.number().optional(),
numGpuLayers: external_exports.number().optional(),
timeToFirstTokenSec: external_exports.number().optional(),
totalTimeSec: external_exports.number().optional(),
promptTokensCount: external_exports.number().int().optional(),
predictedTokensCount: external_exports.number().int().optional(),
totalTokensCount: external_exports.number().int().optional(),
usedDraftModelKey: external_exports.string().optional(),
totalDraftTokensCount: external_exports.number().int().optional(),
acceptedDraftTokensCount: external_exports.number().int().optional(),
rejectedDraftTokensCount: external_exports.number().int().optional(),
ignoredDraftTokensCount: external_exports.number().int().optional()
});
llmGenInfoSchema = external_exports.object({
indexedModelIdentifier: external_exports.string(),
identifier: external_exports.string(),
loadModelConfig: kvConfigSchema,
predictionConfig: kvConfigSchema,
stats: llmPredictionStatsSchema
});
blockLocationSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("beforeId"),
id: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("afterId"),
id: external_exports.string()
})
]);
statusStepStatusSchema = external_exports.enum([
"waiting",
"loading",
"done",
"error",
"canceled"
]);
statusStepStateSchema = external_exports.object({
status: statusStepStatusSchema,
text: external_exports.string()
});
processingUpdateStatusCreateSchema = external_exports.object({
type: external_exports.literal("status.create"),
id: external_exports.string(),
state: statusStepStateSchema,
location: blockLocationSchema.optional(),
indentation: external_exports.number().int().optional()
});
processingUpdateStatusUpdateSchema = external_exports.object({
type: external_exports.literal("status.update"),
id: external_exports.string(),
state: statusStepStateSchema
});
processingUpdateStatusRemoveSchema = external_exports.object({
type: external_exports.literal("status.remove"),
id: external_exports.string()
});
processingUpdateCitationBlockCreateSchema = external_exports.object({
type: external_exports.literal("citationBlock.create"),
id: external_exports.string(),
citedText: external_exports.string(),
fileName: external_exports.string(),
fileIdentifier: external_exports.string(),
pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(),
lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional()
});
processingUpdateDebugInfoBlockCreateSchema = external_exports.object({
type: external_exports.literal("debugInfoBlock.create"),
id: external_exports.string(),
debugInfo: external_exports.string()
});
processingUpdateContentBlockCreateSchema = external_exports.object({
type: external_exports.literal("contentBlock.create"),
id: external_exports.string(),
includeInContext: external_exports.boolean(),
roleOverride: external_exports.enum(["user", "assistant", "system", "tool"]).optional(),
style: contentBlockStyleSchema.optional(),
prefix: external_exports.string().optional(),
suffix: external_exports.string().optional()
});
processingUpdateContentBlockAppendTextSchema = external_exports.object({
type: external_exports.literal("contentBlock.appendText"),
id: external_exports.string(),
text: external_exports.string(),
tokensCount: external_exports.number().int().optional(),
fromDraftModel: external_exports.boolean().optional(),
isStructural: external_exports.boolean().optional()
});
processingUpdateContentBlockAppendToolResultSchema = external_exports.object({
type: external_exports.literal("contentBlock.appendToolResult"),
id: external_exports.string(),
callId: external_exports.number().int(),
toolCallRequestId: external_exports.string().optional(),
content: external_exports.string()
});
processingUpdateContentBlockAppendToolRequestSchema = external_exports.object({
type: external_exports.literal("contentBlock.appendToolRequest"),
id: external_exports.string(),
callId: external_exports.number().int(),
toolCallRequestId: external_exports.string().optional(),
name: external_exports.string(),
parameters: external_exports.record(external_exports.unknown()),
pluginIdentifier: external_exports.string().optional()
});
processingUpdateContentBlockReplaceToolRequestSchema = external_exports.object({
type: external_exports.literal("contentBlock.replaceToolRequest"),
id: external_exports.string(),
callId: external_exports.number().int(),
toolCallRequestId: external_exports.string().optional(),
name: external_exports.string(),
parameters: external_exports.record(external_exports.unknown()),
pluginIdentifier: external_exports.string().optional()
});
processingUpdateContentBlockReplaceTextSchema = external_exports.object({
type: external_exports.literal("contentBlock.replaceText"),
id: external_exports.string(),
text: external_exports.string()
});
processingUpdateContentBlockSetPrefixSchema = external_exports.object({
type: external_exports.literal("contentBlock.setPrefix"),
id: external_exports.string(),
prefix: external_exports.string()
});
processingUpdateContentBlockSetSuffixSchema = external_exports.object({
type: external_exports.literal("contentBlock.setSuffix"),
id: external_exports.string(),
suffix: external_exports.string()
});
processingUpdateContentBlockAttachGenInfoSchema = external_exports.object({
type: external_exports.literal("contentBlock.attachGenInfo"),
id: external_exports.string(),
genInfo: llmGenInfoSchema
});
processingUpdateContentBlockSetStyleSchema = external_exports.object({
type: external_exports.literal("contentBlock.setStyle"),
id: external_exports.string(),
style: contentBlockStyleSchema
});
toolStatusStepStateStatusSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("generatingToolCall"),
name: external_exports.string().optional(),
pluginIdentifier: external_exports.string().optional(),
argumentsString: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationFailed"),
error: external_exports.string(),
rawContent: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("toolCallQueued")
}),
external_exports.object({
type: external_exports.literal("confirmingToolCall")
}),
external_exports.object({
type: external_exports.literal("toolCallDenied"),
denyReason: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("callingTool")
}),
external_exports.object({
type: external_exports.literal("toolCallFailed"),
error: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("toolCallSucceeded"),
timeMs: external_exports.number().int()
})
]);
toolStatusStepStateSchema = external_exports.object({
status: toolStatusStepStateStatusSchema,
customStatus: external_exports.string(),
customWarnings: external_exports.array(external_exports.string())
});
processingUpdateToolStatusCreateSchema = external_exports.object({
type: external_exports.literal("toolStatus.create"),
id: external_exports.string(),
callId: external_exports.number().int(),
state: toolStatusStepStateSchema
});
processingUpdateToolStatusUpdateSchema = external_exports.object({
type: external_exports.literal("toolStatus.update"),
id: external_exports.string(),
state: toolStatusStepStateSchema
});
processingUpdateToolStatusArgumentFragmentSchema = external_exports.object({
type: external_exports.literal("toolStatus.argumentFragment"),
id: external_exports.string(),
content: external_exports.string()
});
processingUpdateSetSenderNameSchema = external_exports.object({
type: external_exports.literal("setSenderName"),
name: external_exports.string()
});
processingUpdateSchema = external_exports.discriminatedUnion("type", [
processingUpdateStatusCreateSchema,
processingUpdateStatusUpdateSchema,
processingUpdateStatusRemoveSchema,
processingUpdateCitationBlockCreateSchema,
processingUpdateDebugInfoBlockCreateSchema,
processingUpdateContentBlockCreateSchema,
processingUpdateContentBlockAppendTextSchema,
processingUpdateContentBlockAppendToolRequestSchema,
processingUpdateContentBlockReplaceToolRequestSchema,
processingUpdateContentBlockAppendToolResultSchema,
processingUpdateContentBlockReplaceTextSchema,
processingUpdateContentBlockSetPrefixSchema,
processingUpdateContentBlockSetSuffixSchema,
processingUpdateContentBlockAttachGenInfoSchema,
processingUpdateContentBlockSetStyleSchema,
processingUpdateToolStatusCreateSchema,
processingUpdateToolStatusUpdateSchema,
processingUpdateToolStatusArgumentFragmentSchema,
processingUpdateSetSenderNameSchema
]);
external_exports.discriminatedUnion("type", [
processingUpdateStatusCreateSchema,
processingUpdateStatusUpdateSchema,
processingUpdateStatusRemoveSchema,
processingUpdateCitationBlockCreateSchema,
processingUpdateDebugInfoBlockCreateSchema,
processingUpdateContentBlockCreateSchema,
processingUpdateContentBlockAppendTextSchema,
processingUpdateContentBlockReplaceTextSchema,
processingUpdateContentBlockAppendToolRequestSchema,
processingUpdateContentBlockReplaceToolRequestSchema,
processingUpdateContentBlockAppendToolResultSchema,
processingUpdateContentBlockAttachGenInfoSchema,
processingUpdateContentBlockSetStyleSchema,
processingUpdateToolStatusCreateSchema,
processingUpdateToolStatusUpdateSchema,
processingUpdateToolStatusArgumentFragmentSchema,
processingUpdateSetSenderNameSchema
]);
processingRequestConfirmToolCallSchema = external_exports.object({
type: external_exports.literal("confirmToolCall"),
callId: external_exports.number().int(),
pluginIdentifier: external_exports.string().optional(),
name: external_exports.string(),
parameters: external_exports.record(external_exports.any())
});
processingRequestTextInputSchema = external_exports.object({
type: external_exports.literal("textInput"),
prompt: external_exports.string()
});
processingRequestSchema = external_exports.discriminatedUnion("type", [
processingRequestConfirmToolCallSchema,
processingRequestTextInputSchema
]);
processingRequestResponseConfirmToolCallSchema = external_exports.object({
type: external_exports.literal("confirmToolCall"),
result: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("allow"),
toolArgsOverride: external_exports.record(external_exports.any()).optional()
}),
external_exports.object({
type: external_exports.literal("deny"),
denyReason: external_exports.string().optional()
})
])
});
processingRequestResponseTextInputSchema = external_exports.object({
type: external_exports.literal("textInput"),
result: external_exports.string()
});
processingRequestResponseSchema = external_exports.discriminatedUnion("type", [
processingRequestResponseConfirmToolCallSchema,
processingRequestResponseTextInputSchema
]);
external_exports.object({
modelTag: external_exports.string().optional(),
ignoreUserConfig: external_exports.boolean().optional()
});
external_exports.discriminatedUnion("type", [
processingUpdateStatusCreateSchema,
processingUpdateStatusUpdateSchema,
processingUpdateStatusRemoveSchema,
processingUpdateCitationBlockCreateSchema,
processingUpdateDebugInfoBlockCreateSchema
]);
tokenSourceIdentifierSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("model"),
identifier: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("generator"),
pluginIdentifier: external_exports.string()
})
]);
modelInfoSchema = external_exports.discriminatedUnion("type", [
llmInfoSchema,
embeddingModelInfoSchema
]);
modelInstanceInfoSchema = external_exports.discriminatedUnion("type", [
llmInstanceInfoSchema,
embeddingModelInstanceInfoSchema
]);
pluginConfigSpecifierSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("direct"),
config: kvConfigSchema,
workingDirectoryPath: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("predictionProcess"),
pci: external_exports.string(),
token: external_exports.string()
})
]);
remotePluginInfoSchema = external_exports.object({
identifier: external_exports.string(),
isDev: external_exports.boolean(),
isTrusted: external_exports.boolean(),
hasPromptPreprocessor: external_exports.boolean(),
hasPredictionLoopHandler: external_exports.boolean(),
hasToolsProvider: external_exports.boolean(),
hasGenerator: external_exports.boolean()
});
artifactDownloadPlanModelInfoSchema = external_exports.object({
displayName: external_exports.string(),
sizeBytes: external_exports.number(),
quantName: external_exports.string().optional(),
compatibilityType: modelCompatibilityTypeSchema
});
artifactDownloadPlanNodeStateSchema = external_exports.enum(["pending", "fetching", "satisfied", "completed"]);
artifactDownloadPlanNodeSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("artifact"),
owner: kebabCaseSchema,
name: kebabCaseWithDotsSchema,
state: artifactDownloadPlanNodeStateSchema,
artifactType: artifactTypeSchema.optional(),
sizeBytes: external_exports.number().int().optional(),
dependencyNodes: external_exports.array(external_exports.number().int())
}),
external_exports.object({
type: external_exports.literal("model"),
state: artifactDownloadPlanNodeStateSchema,
resolvedSources: external_exports.number().int().optional(),
totalSources: external_exports.number().int().optional(),
alreadyOwned: artifactDownloadPlanModelInfoSchema.optional(),
selected: artifactDownloadPlanModelInfoSchema.optional()
})
]);
artifactDownloadPlanSchema = external_exports.object({
nodes: external_exports.array(artifactDownloadPlanNodeSchema),
downloadSizeBytes: external_exports.number().int()
});
localArtifactFileEntrySchema = external_exports.object({
relativePath: external_exports.string(),
sizeBytes: external_exports.number().int()
});
localArtifactFileListSchema = external_exports.object({
files: external_exports.array(localArtifactFileEntrySchema),
usedIgnoreFile: external_exports.string().nullable()
});
downloadProgressUpdateSchema = external_exports.object({
downloadedBytes: external_exports.number().int(),
totalBytes: external_exports.number().int(),
speedBytesPerSecond: external_exports.number()
});
modelSearchResultDownloadOptionFitEstimationSchema = external_exports.enum([
"fullGPUOffload",
"partialGPUOffload",
"fitWithoutGPU",
"willNotFit"
]);
modelSearchResultDownloadOptionDataSchema = external_exports.object({
quantization: external_exports.string().optional(),
name: external_exports.string(),
sizeBytes: external_exports.number().int(),
fitEstimation: modelSearchResultDownloadOptionFitEstimationSchema,
recommended: external_exports.boolean().optional(),
downloadIdentifier: external_exports.string(),
indexedModelIdentifier: external_exports.string()
});
modelSearchResultIdentifierSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("catalog"),
identifier: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("hf"),
identifier: external_exports.string()
})
]);
modelSearchResultEntryDataSchema = external_exports.object({
name: external_exports.string(),
identifier: modelSearchResultIdentifierSchema,
exact: external_exports.boolean().optional(),
staffPick: external_exports.boolean().optional()
});
modelSearchOptsSchema = external_exports.object({
searchTerm: external_exports.string().optional(),
limit: external_exports.number().int().positive().max(25).optional(),
compatibilityTypes: external_exports.array(modelCompatibilityTypeSchema).optional()
});
internalRetrievalResultEntrySchema = external_exports.object({
content: external_exports.string(),
score: external_exports.number(),
sourceIndex: external_exports.number().int(),
pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(),
lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional()
});
internalRetrievalResultSchema = external_exports.object({
entries: external_exports.array(internalRetrievalResultEntrySchema)
});
external_exports.object({
content: external_exports.string(),
score: external_exports.number(),
citation: citationSourceSchema
});
retrievalChunkingMethodSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("recursive-v1"),
chunkSize: external_exports.number().int(),
chunkOverlap: external_exports.number().int()
})
]);
retrievalFileProcessingStepSchema = external_exports.enum(["loading", "chunking", "embedding"]);
acceleratorTypeSchema = external_exports.enum(["unknown", "integratedGpu", "dedicatedGpu"]);
acceleratorSchema = external_exports.object({
name: external_exports.string(),
deviceId: external_exports.number().int(),
totalMemoryBytes: external_exports.number().int(),
type: acceleratorTypeSchema
});
external_exports.object({
key: external_exports.string(),
name: external_exports.string(),
accelerators: external_exports.array(acceleratorSchema)
});
serializedKVConfigSchematicsFieldSchema = external_exports.object({
shortKey: external_exports.string(),
fullKey: external_exports.string(),
typeKey: external_exports.string(),
typeParams: jsonSerializableSchema,
defaultValue: jsonSerializableSchema
});
serializedKVConfigSchematicsSchema = external_exports.object({
fields: external_exports.array(serializedKVConfigSchematicsFieldSchema),
extensionPrefixes: external_exports.array(external_exports.string()).optional()
});
external_exports.object({
fullKey: external_exports.string(),
error: jsonSerializableSchema
});
booleanOrMixedSchema = external_exports.union([
external_exports.literal(true),
external_exports.literal(false),
external_exports.literal("mixed")
]);
virtualModelDefinitionMetadataOverridesSchema = external_exports.object({
domain: modelDomainTypeSchema.optional(),
architectures: external_exports.array(external_exports.string()).optional(),
compatibilityTypes: external_exports.array(modelCompatibilityTypeSchema).optional(),
paramsStrings: external_exports.array(external_exports.string()).optional(),
minMemoryUsageBytes: external_exports.number().optional(),
contextLengths: external_exports.array(external_exports.number()).optional(),
trainedForToolUse: booleanOrMixedSchema.optional(),
vision: booleanOrMixedSchema.optional(),
reasoning: booleanOrMixedSchema.optional(),
fim: booleanOrMixedSchema.optional()
});
virtualModelDefinitionConcreteModelBaseSchema = external_exports.object({
key: external_exports.string(),
sources: external_exports.array(modelDownloadSourceSchema)
});
virtualModelCustomFieldSetJinjaVariableEffectSchema = external_exports.object({
type: external_exports.literal("setJinjaVariable"),
variable: external_exports.string()
});
virtualModelCustomFieldPrependSystemPromptEffectSchema = external_exports.object({
type: external_exports.literal("prependSystemPrompt"),
content: external_exports.string()
});
virtualModelCustomFieldAppendSystemPromptEffectSchema = external_exports.object({
type: external_exports.literal("appendSystemPrompt"),
content: external_exports.string()
});
virtualModelCustomFieldDefinitionBaseSchema = external_exports.object({
key: external_exports.string(),
displayName: external_exports.string(),
description: external_exports.string()
});
virtualModelBooleanCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({
type: external_exports.literal("boolean"),
defaultValue: external_exports.boolean(),
effects: external_exports.array(external_exports.discriminatedUnion("type", [
virtualModelCustomFieldSetJinjaVariableEffectSchema,
virtualModelCustomFieldPrependSystemPromptEffectSchema,
virtualModelCustomFieldAppendSystemPromptEffectSchema
]))
});
virtualModelStringCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({
type: external_exports.literal("string"),
defaultValue: external_exports.string(),
effects: external_exports.array(external_exports.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema]))
});
virtualModelSelectCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({
type: external_exports.literal("select"),
options: external_exports.array(external_exports.object({
label: external_exports.string(),
value: external_exports.string()
})),
defaultValue: external_exports.string(),
effects: external_exports.array(external_exports.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema]))
});
virtualModelCustomFieldDefinitionSchema = external_exports.discriminatedUnion("type", [
virtualModelBooleanCustomFieldDefinitionSchema,
virtualModelStringCustomFieldDefinitionSchema,
virtualModelSelectCustomFieldDefinitionSchema
]);
virtualModelConditionEqualsSchema = external_exports.object({
type: external_exports.literal("equals"),
key: external_exports.string(),
value: jsonSerializableSchema
});
virtualModelConditionSchema = external_exports.discriminatedUnion("type", [
virtualModelConditionEqualsSchema
]);
virtualModelSuggestionSchema = external_exports.object({
message: external_exports.string(),
conditions: external_exports.array(virtualModelConditionSchema),
fields: external_exports.array(kvConfigFieldSchema).optional()
});
external_exports.object({
model: external_exports.string().regex(/^[^/]+\/[^/]+$/),
base: external_exports.union([external_exports.string(), external_exports.array(virtualModelDefinitionConcreteModelBaseSchema)]),
tags: external_exports.array(external_exports.string().max(100)).optional(),
config: external_exports.object({
load: kvConfigSchema.optional(),
operation: kvConfigSchema.optional()
}).optional(),
metadataOverrides: virtualModelDefinitionMetadataOverridesSchema.optional(),
customFields: external_exports.array(virtualModelCustomFieldDefinitionSchema).optional(),
suggestions: external_exports.array(virtualModelSuggestionSchema).optional()
});
logLevelSchema = external_exports.enum(["debug", "info", "warn", "error"]);
defaultInfoPrefix = import_chalk.default.greenBright("I");
defaultWarnPrefix = import_chalk.default.yellowBright("W");
defaultErrorPrefix = import_chalk.default.redBright("E");
defaultDebugPrefix = import_chalk.default.blueBright("D");
SimpleLogger = class _SimpleLogger {
constructor(prefixText = "", parentLogger = console, { useLogLevelPrefixes, infoPrefix, warnPrefix, errorPrefix, debugPrefix } = {}) {
this.isSimpleLogger = true;
this.infoPrefix = [];
this.warnPrefix = [];
this.errorPrefix = [];
this.debugPrefix = [];
if (isSimpleLogger(parentLogger)) {
useLogLevelPrefixes = useLogLevelPrefixes ?? parentLogger.opts.useLogLevelPrefixes;
infoPrefix = infoPrefix === void 0 ? parentLogger.opts.infoPrefix : infoPrefix;
warnPrefix = warnPrefix === void 0 ? parentLogger.opts.warnPrefix : warnPrefix;
errorPrefix = errorPrefix === void 0 ? parentLogger.opts.errorPrefix : errorPrefix;
debugPrefix = debugPrefix === void 0 ? parentLogger.opts.debugPrefix : debugPrefix;
if (prefixText === "") {
this.innerPrefix = parentLogger.innerPrefix;
this.fullPrefix = parentLogger.fullPrefix;
} else {
if (parentLogger.fullPrefix === "") {
this.innerPrefix = prefixText;
} else {
this.innerPrefix = `${parentLogger.innerPrefix}][${prefixText}`;
}
this.fullPrefix = import_chalk.default.whiteBright(`[${this.innerPrefix}]`);
}
this.parentLogger = parentLogger.parentLogger;
} else {
useLogLevelPrefixes = useLogLevelPrefixes ?? false;
infoPrefix = infoPrefix === void 0 ? defaultInfoPrefix : infoPrefix;
warnPrefix = warnPrefix === void 0 ? defaultWarnPrefix : warnPrefix;
errorPrefix = errorPrefix === void 0 ? defaultErrorPrefix : errorPrefix;
debugPrefix = debugPrefix === void 0 ? defaultDebugPrefix : debugPrefix;
if (prefixText === "") {
this.innerPrefix = "";
this.fullPrefix = "";
} else {
this.innerPrefix = prefixText;
this.fullPrefix = import_chalk.default.whiteBright(`[${this.innerPrefix}]`);
}
this.parentLogger = parentLogger;
}
if (useLogLevelPrefixes) {
if (infoPrefix !== null) {
this.infoPrefix.push(infoPrefix);
}
if (warnPrefix !== null) {
this.warnPrefix.push(warnPrefix);
}
if (errorPrefix !== null) {
this.errorPrefix.push(errorPrefix);
}
if (debugPrefix !== null) {
this.debugPrefix.push(debugPrefix);
}
}
if (this.fullPrefix !== "") {
this.infoPrefix.push(this.fullPrefix);
this.warnPrefix.push(this.fullPrefix);
this.errorPrefix.push(this.fullPrefix);
this.debugPrefix.push(this.fullPrefix);
}
this.opts = {
useLogLevelPrefixes,
infoPrefix,
warnPrefix,
errorPrefix,
debugPrefix
};
}
subclass(prefixText) {
return new _SimpleLogger(`${this.innerPrefix}:${prefixText}`, this.parentLogger);
}
info(...messages) {
this.parentLogger.info(...this.infoPrefix, ...messages);
}
infoText(strings, ...values2) {
this.info(text(strings, ...values2));
}
infoWithoutPrefix(...messages) {
this.parentLogger.info(...messages);
}
error(...messages) {
this.parentLogger.error(...this.errorPrefix, ...messages);
}
errorText(strings, ...values2) {
this.error(text(strings, ...values2));
}
errorWithoutPrefix(...messages) {
this.parentLogger.error(...messages);
}
warn(...messages) {
this.parentLogger.warn(...this.warnPrefix, ...messages);
}
warnText(strings, ...values2) {
this.warn(text(strings, ...values2));
}
warnWithoutPrefix(...messages) {
this.parentLogger.warn(...messages);
}
debug(...messages) {
this.parentLogger.debug(...this.debugPrefix, ...messages);
}
debugText(strings, ...values2) {
this.debug(text(strings, ...values2));
}
debugWithoutPrefix(...messages) {
this.parentLogger.debug(...messages);
}
throw(message) {
throw new Error(`${this.fullPrefix} ${message}`);
}
logAtLevel(level, ...messages) {
switch (level) {
case "debug":
this.debug(...messages);
break;
case "info":
this.info(...messages);
break;
case "warn":
this.warn(...messages);
break;
case "error":
this.error(...messages);
break;
}
}
static fromMultiple(loggers, opts) {
return new _SimpleLogger("", {
debug: (...messages) => {
for (const logger2 of loggers) {
logger2.debug(...messages);
}
},
info: (...messages) => {
for (const logger2 of loggers) {
logger2.info(...messages);
}
},
warn: (...messages) => {
for (const logger2 of loggers) {
logger2.warn(...messages);
}
},
error: (...messages) => {
for (const logger2 of loggers) {
logger2.error(...messages);
}
}
}, {
...opts,
useLogLevelPrefixes: false
});
}
};
finished = Symbol("finished");
StreamablePromise = class {
/**
* Called by the producer when it has finished producing values. If an error is provided, the
* promise will be rejected with that error. If no error is provided, the promise will be resolved
* with the final value.
*
* This method should be exposed in the static constructor of the subclass.
*
* @param error - The error to reject the promise with, if any.
*/
finished(error) {
if (this.status !== "pending") {
throw new Error("`finished` called while not pending");
}
if (error === void 0) {
this.status = "resolved";
this.nextFragmentPromiseBundle?.resolve(finished);
this.resolveFinal(this.collect(this.buffer));
} else {
this.status = "rejected";
this.nextFragmentPromiseBundle?.reject(error);
this.rejectFinal(error);
}
}
/**
* Called by the producer to push a new fragment into the buffer. This method should be exposed in
* the static constructor of the subclass.
*
* This method should be exposed in the static constructor of the subclass.
*
* @param fragment - The fragment to push into the buffer.
*/
push(fragment2) {
if (this.status !== "pending") {
throw new Error("`push` called while not pending");
}
this.buffer.push(fragment2);
this.nextFragmentPromiseBundle?.resolve(fragment2);
this.nextFragmentPromiseBundle = null;
}
constructor() {
this.status = "pending";
this.buffer = [];
this.nextFragmentPromiseBundle = null;
this.hasIterator = false;
this[_a5] = "StreamablePromise";
const { promise, resolve: resolve2, reject } = makePromise();
this.promiseFinal = promise;
this.resolveFinal = resolve2;
this.rejectFinal = reject;
}
then(onfulfilled, onrejected) {
return this.promiseFinal.then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.promiseFinal.catch(onrejected);
}
finally(onfinally) {
return this.promiseFinal.finally(onfinally);
}
/**
* If nextFragmentPromiseBundle exists, it is returned. Otherwise, a new one is created and
* returned.
*/
obtainNextFragmentPromiseBundle() {
if (this.nextFragmentPromiseBundle === null) {
this.nextFragmentPromiseBundle = makePromise();
}
return this.nextFragmentPromiseBundle;
}
async *[(_a5 = Symbol.toStringTag, Symbol.asyncIterator)]() {
if (!this.hasIterator) {
this.promiseFinal.catch(() => {
});
this.hasIterator = true;
}
let i7 = 0;
while (i7 < this.buffer.length || this.status === "pending") {
if (i7 < this.buffer.length) {
yield this.buffer[i7];
i7++;
} else {
const nextFragmentPromiseBundle = this.obtainNextFragmentPromiseBundle();
const nextFragment = await nextFragmentPromiseBundle.promise;
if (nextFragment === finished) {
break;
}
yield nextFragment;
i7++;
}
}
await this.promiseFinal;
await Promise.resolve();
}
};
Validator = class _Validator {
constructor({ attachStack } = {}) {
this.attachStack = attachStack ?? true;
}
/**
* Pretty-prints a Zod error.
*
* @param rootObjectName - The name of the object being validated (used for error messages)
* @param error - The Zod error to pretty-print
*
* @returns The pretty-printed error in a string
*/
static prettyPrintZod(rootObjectName, error) {
return error.errors.map((e9) => {
if (e9.path.length === 0) {
return `- ${import_chalk.default.redBright(rootObjectName)}: ${e9.message}`;
}
const path6 = import_chalk.default.red(`.${e9.path.join(".")}`);
return `- ${import_chalk.default.redBright(rootObjectName)}${path6}: ${e9.message}`;
}).join("\n");
}
/**
* Validates a value against a schema and throws an error if it's invalid.
*
* @param lead - The start of the error message (used for error messages)
* @param rootObjectName - The name of the object being validated (used for error messages)
* @param schema - The schema to validate against
* @param value - The value to validate
*
* @returns The validated value
* @throws An error if the value is invalid
*/
validateOrThrow(lead, rootObjectName, schema, value, stack) {
const result = schema.safeParse(value);
if (result.success) {
return result.data;
} else {
throw makePrettyError(`${lead}
${_Validator.prettyPrintZod(rootObjectName, result.error)}`, this.attachStack ? stack : void 0);
}
}
/**
* Validates multiple values against multiple schemas and throws an error if any of them are
* invalid. All values are validated before any errors are thrown. This is useful when you want to
* validate multiple values at once and want to see all the errors at once.
*
* @param leadProducer - The function to produce the start of the error message (used for error).
* It is called with a set of indices of the invalid values.
* @param rootObjectNames - The names of the objects being validated (used for error messages)
* @param schemas - The schemas to validate against
* @param values - The values to validate
*
* @returns The validated values
* @throws An error if any of the values are invalid
*/
validateMultipleOrThrow(leadProducer, rootObjectNames, schemas, values2, stack) {
const results = schemas.map((schema, index2) => schema.safeParse(values2[index2]));
const errors = results.map((result, index2) => ({ result, index: index2, rootObjectName: rootObjectNames[index2] })).filter(({ result }) => !result.success).map(({ result, rootObjectName, index: index2 }) => ({
error: result.error,
rootObjectName,
index: index2
}));
if (errors.length === 0) {
return results.map((result) => result.data);
} else {
const erroredValues = new Set(errors.map(({ index: index2 }) => index2));
const lead = leadProducer(erroredValues);
throw makePrettyError(`${lead}
${errors.map(({ error, rootObjectName }) => _Validator.prettyPrintZod(rootObjectName, error)).join("\n")}`, this.attachStack ? stack : void 0);
}
}
/**
* Validates a value against a schema and throws an error if it's invalid. This is a convenience
* function for validating one single method parameter.
*
* @param className - The name of the class containing the method (used for error messages)
* @param methodName - The name of the method (used for error messages)
* @param paramName - The name of the parameter being validated (used for error messages)
* @param schema - The schema to validate against
* @param value - The value to validate
*
* @returns The validated value
* @throws An error if the value is invalid
*/
validateMethodParamOrThrow(className, methodName, paramName, schema, value, stack) {
const functionCall = import_chalk.default.yellowBright(text`
${className}.${methodName}(${import_chalk.default.redBright(paramName)})
`);
return this.validateOrThrow(`Invalid parameter(s) for ${functionCall}:`, paramName, schema, value, stack);
}
/**
* Validates multiple values against multiple schemas and throws an error if any of them are
* invalid. This is a convenience function for validating multiple method parameters.
*
* @param className - The name of the class containing the method (used for error messages)
* @param methodName - The name of the method (used for error messages)
* @param paramNames - The names of the parameters being validated (used for error messages)
* @param schemas - The schemas to validate against
* @param values - The values to validate
*
* @returns The validated values
* @throws An error if any of the values are invalid
*/
validateMethodParamsOrThrow(className, methodName, paramNames, schemas, values2, stack) {
return this.validateMultipleOrThrow((erroredValues) => {
const coloredParamNames = paramNames.map((name, index2) => erroredValues.has(index2) ? import_chalk.default.redBright(name) : name);
const functionCall = import_chalk.default.yellowBright(text`
${className}.${methodName}(${coloredParamNames.join(", ")})
`);
return `Invalid parameter(s) for ${functionCall}:`;
}, paramNames, schemas, values2, stack);
}
/**
* Validates a value against a schema and throws an error if it's invalid. This is a convenience
* function for validating one single constructor parameter.
*
* @param className - The name of the class (used for error messages)
* @param paramName - The name of the parameter being validated (used for error messages)
* @param schema - The schema to validate against
* @param value - The value to validate
*
* @returns The validated value
* @throws An error if the value is invalid
*/
validateConstructorParamOrThrow(className, paramName, schema, value, stack) {
const functionCall = import_chalk.default.yellowBright(text`
${className}(${import_chalk.default.redBright(paramName)})
`);
return this.validateOrThrow(`Invalid parameter(s) when constructing ${functionCall}`, paramName, schema, value, stack);
}
/**
* Validates multiple values against multiple schemas and throws an error if any of them are
* invalid. This is a convenience function for validating multiple constructor parameters.
*
* @param className - The name of the class (used for error messages)
* @param paramNames - The names of the parameters being validated (used for error messages)
*
* @param schemas - The schemas to validate against
* @param values - The values to validate
*/
validateConstructorParamsOrThrow(className, paramNames, schemas, values2, stack) {
return this.validateMultipleOrThrow((erroredValues) => {
const coloredParamNames = paramNames.map((name, index2) => erroredValues.has(index2) ? import_chalk.default.redBright(name) : name);
const functionCall = import_chalk.default.yellowBright(text`
${className}(${coloredParamNames.join(", ")})
`);
return `Invalid parameter(s) when constructing ${functionCall}:`;
}, paramNames, schemas, values2, stack);
}
};
sharedValidator = new Validator();
FileHandle = class {
/**
* @deprecated Direct construction is not recommended. Please use the `prepareFile` API instead
*/
constructor(filesNamespace, identifier, type, sizeBytes, name) {
this.filesNamespace = filesNamespace;
this.identifier = identifier;
this.type = type;
this.sizeBytes = sizeBytes;
this.name = name;
this.parsedIdentifier = parseFileIdentifier(identifier);
}
/**
* Gets the absolute file path of this file.
*/
async getFilePath() {
switch (this.parsedIdentifier.type) {
case "local": {
return (await this.filesNamespace.getLocalFileAbsolutePath(this.parsedIdentifier.fileName)).path;
}
case "base64": {
throw new Error("Not implemented. Please open an issue on GitHub if you encountered this error.");
}
default: {
const _exhaustiveCheck = this.parsedIdentifier;
throw new Error(`Unexpected file identifier type: ${JSON.stringify(_exhaustiveCheck)}`);
}
}
}
isImage() {
return this.type === "image";
}
};
chatMessageInputSchema = external_exports.object({
role: external_exports.enum(["user", "assistant", "system"]).optional(),
content: external_exports.string().optional(),
images: external_exports.array(external_exports.instanceof(FileHandle)).optional()
});
chatHistoryInputSchema = external_exports.array(chatMessageInputSchema);
Chat3 = class _Chat extends MaybeMutable {
getClassName() {
return "Chat";
}
create(data, mutable) {
return new _Chat(data, mutable);
}
cloneData(data) {
return chatHistoryDataSchema.parse(data);
}
/**
* Don't use this constructor directly.
*
* - To create an empty chat history, use `Chat.empty()`.
* - To create a chat history with existing data, use `Chat.from()`.
*/
constructor(data, mutable) {
super(data, mutable);
}
/**
* Creates an empty mutable chat history.
*/
static empty() {
return new _Chat({ messages: [] }, true);
}
/**
* Quickly create a mutable chat history with something that can be converted to a chat history.
*
* The created chat history will be a mutable copy of the input.
*
* @example
* ```ts
* const history = Chat.from([
* { role: "user", content: "Hello" },
* { role: "assistant", content: "Hi!" },
* { role: "user", content: "What is your name?" },
* ]);
* ```
*/
static from(initializer) {
const stack = getCurrentStack(1);
sharedValidator.validateMethodParamOrThrow("Chat", "from", "initializer", chatHistoryLikeSchema, initializer, stack);
if (initializer instanceof _Chat) {
return initializer.asMutableCopy();
}
if (typeof initializer === "string") {
const chatHistory = _Chat.empty();
chatHistory.append("user", initializer);
return chatHistory;
}
if (Array.isArray(initializer)) {
return new _Chat({ messages: initializer.map(chatMessageInputToChatMessageData) }, true);
}
if (isChatMessageInputAsOpposeToChatHistoryData(initializer)) {
return new _Chat({ messages: [chatMessageInputToChatMessageData(initializer)] }, true);
} else {
return new _Chat(initializer, false).asMutableCopy();
}
}
/**
* Creates a chat history with raw data. This method is intended for internal use only.
*
* If mutable is set to false, you MUST ensure that the data is not mutated.
*
* @internal
*/
static createRaw(data, mutable) {
return new _Chat(data, mutable);
}
/**
* Gets the raw data of this message. This method is intended for internal use only.
*
* If mutable is set to false, you MUST ensure that the data is not mutated.
*
* @internal
*/
getRaw() {
return this.data;
}
append(...args) {
this.guardMutable();
if (args.length === 1) {
const [chatMessageLike] = args;
const chatMessage = ChatMessage.from(chatMessageLike);
const messageMutable = accessMaybeMutableInternals(chatMessage)._internalToMutable();
this.data.messages.push(accessMaybeMutableInternals(messageMutable)._internalGetData());
} else {
const [role, content, opts = {}] = args;
if (role === "user" || role === "system" || role === "assistant") {
const parts = [
{ type: "text", text: content }
];
if (opts.images !== void 0) {
for (const image of opts.images) {
parts.push({
type: "file",
name: image.name,
identifier: image.identifier,
sizeBytes: image.sizeBytes,
fileType: image.type
});
}
}
this.data.messages.push({ role, content: parts });
} else {
throw new Error(text`
Unsupported role for append() API with [role, content] parameters: ${role}.
Supported roles are 'user', 'system', and 'assistant'.
`);
}
}
}
withAppended(...args) {
const copy2 = this.asMutableCopy();
copy2.append(...args);
return copy2;
}
/**
* Get the number of messages in the history.
*/
getLength() {
return this.data.messages.length;
}
/**
* Get the number of messages in the history.
*/
get length() {
return this.getLength();
}
/**
* Remove the last message from the history. If the history is empty, this method will throw.
*/
pop() {
this.guardMutable();
if (this.data.messages.length === 0) {
throw new Error("Tried to pop from an empty history.");
}
const popped = this.data.messages.pop();
return ChatMessage.createRaw(popped, true);
}
/**
* Gets all files contained in this history.
*
* @param client - LMStudio client
*/
getAllFiles(client) {
return this.data.messages.flatMap((message) => message.content.filter((part) => part.type === "file")).map((part) => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name));
}
/**
* Allows iterating over the files in the history.
*/
*files(client) {
for (const message of this.data.messages) {
for (const part of message.content) {
if (part.type === "file") {
yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
}
}
}
}
/**
* Returns true if this history contains any files.
*/
hasFiles() {
return this.data.messages.some((message) => message.content.some((part) => part.type === "file"));
}
/**
* Gets the message at the given index. If the index is negative, it will be counted from the end.
*
* If the index is out of bounds, this method will throw as oppose to returning undefined. This is
* to help catch bugs early.
*/
at(index2) {
let actualIndex = index2;
if (index2 < 0) {
actualIndex = this.data.messages.length + index2;
}
if (actualIndex < 0 || actualIndex >= this.data.messages.length) {
throw new Error(text`
Tried to access the message at index ${index2}, but the history only has
${this.data.messages.length} messages.
`);
}
return ChatMessage.createRaw(this.data.messages[actualIndex], this.mutable);
}
/**
* Get all the messages in the history as an array of ChatMessage objects.
*/
getMessagesArray() {
return this.data.messages.map((message) => ChatMessage.createRaw(message, this.mutable));
}
/**
* Maps over the messages in the history and returns an array of the results.
*/
map(mapper) {
return this.getMessagesArray().map(mapper);
}
/**
* Maps over the messages in the history and returns a flattened array of the results.
*
* This is similar to `Array.prototype.flatMap`, but it works with ChatMessage objects.
*/
flatMap(mapper) {
return this.getMessagesArray().flatMap(mapper);
}
/**
* Allows iterating over the messages in the history.
*/
*[Symbol.iterator]() {
for (const message of this.data.messages) {
yield ChatMessage.createRaw(message, this.mutable);
}
}
/**
* Given a predicate, the predicate is called for each file in the history.
*
* - If the predicate returns true, the file is removed from the history and is collected into the
* returned array.
* - If the predicate returns false, the file is kept in the history.
*
* This method is useful if you are implementing a promptPreprocessor that needs to convert certain
* types of files.
*
* If the predicate needs to be async, use the {@link Chat#consumeFilesAsync} method.
*
* @param client - LMStudio client
* @param predicate - The predicate to call for each file.
* @returns The files that were consumed.
*/
consumeFiles(client, predicate) {
this.guardMutable();
const consumedFiles = [];
for (const message of this.data.messages) {
consumedFiles.push(...ChatMessage.createRaw(message, true).consumeFiles(client, predicate));
}
return consumedFiles;
}
/**
* Given an async predicate, the predicate is called for each file in the history.
*
* - If the predicate returns true, the file is removed from the history and is collected into the
* returned array.
* - If the predicate returns false, the file is kept in the history.
*
* This method is useful if you are implementing a promptPreprocessor that needs to convert certain
* types of files.
*
* If you need a synchronous version, use the {@link Chat#consumeFiles} method.
*
* @param client - LMStudio client
* @param predicate - The predicate to call for each file.
* @returns The files that were consumed.
*/
async consumeFilesAsync(client, predicate) {
this.guardMutable();
const consumedFiles = [];
for (const message of this.data.messages) {
consumedFiles.push(...await ChatMessage.createRaw(message, true).consumeFilesAsync(client, predicate));
}
return consumedFiles;
}
getSystemPrompt() {
return this.data.messages.filter((message) => message.role === "system").map((message) => message.content.filter((part) => part.type === "text").map((part) => part.text).join(" ")).join("\n\n");
}
replaceSystemPrompt(content) {
this.guardMutable();
this.data.messages = this.data.messages.filter((message) => message.role !== "system");
this.data.messages.unshift({ role: "system", content: [{ type: "text", text: content }] });
}
filterInPlace(predicate) {
this.guardMutable();
this.data.messages = this.data.messages.filter((message) => predicate(ChatMessage.createRaw(message, true)));
}
toString() {
return "Chat {\n" + this.data.messages.map((message) => {
const messageString = ChatMessage.createRaw(message, false).toString();
return messageString.split("\n").map((line) => " " + line).join("\n");
}).join("\n") + "\n}";
}
};
chatHistoryLikeSchema = external_exports.union([
external_exports.instanceof(Chat3),
chatHistoryDataSchema,
external_exports.string(),
chatHistoryInputSchema,
chatMessageInputSchema
]);
ChatMessage = class _ChatMessage extends MaybeMutable {
getClassName() {
return "ChatMessage";
}
create(data, mutable) {
return new _ChatMessage(data, mutable);
}
cloneData(data) {
return chatMessageDataSchema.parse(data);
}
constructor(data, mutable) {
super(data, mutable);
}
/**
* Create a mutable text only message.
*/
static create(role, content) {
return new _ChatMessage(chatMessageDataSchema.parse({
role,
content: [{ type: "text", text: content }]
}), true);
}
/**
* Quickly create a mutable message with something that can be converted to a message.
*/
static from(initializer) {
const stack = getCurrentStack(1);
sharedValidator.validateMethodParamOrThrow("ChatMessage", "from", "initializer", chatMessageLikeSchema, initializer, stack);
if (initializer instanceof _ChatMessage) {
return initializer.asMutableCopy();
}
if (typeof initializer === "string") {
return new _ChatMessage(chatMessageDataSchema.parse({
role: "user",
content: [{ type: "text", text: initializer }]
}), true);
}
if (isChatMessageInputAsOpposeToChatMessageData(initializer)) {
return new _ChatMessage(chatMessageInputToChatMessageData(initializer), true);
} else {
return new _ChatMessage(initializer, true);
}
}
/**
* Creates a chat history with raw data. This method is intended for internal use only.
*
* If mutable is set to false, you MUST ensure that the data is not mutated.
*
* @internal
*/
static createRaw(data, mutable) {
return new _ChatMessage(data, mutable);
}
/**
* Gets the raw data of this message. This method is intended for internal use only.
*
* If mutable is set to false, you MUST ensure that the data is not mutated.
*
* @internal
*/
getRaw() {
return this.data;
}
getRole() {
return this.data.role;
}
setRole(role) {
this.guardMutable();
this.data.role = role;
}
getFileParts() {
return this.data.content.filter((part) => part.type === "file");
}
/**
* Gets all text contained in this message.
*/
getText() {
return this.data.content.filter((part) => part.type === "text").map((part) => part.text).join(" ");
}
/**
* Get all tool call results within this message.
*/
getToolCallResults() {
return this.data.content.filter((part) => part.type === "toolCallResult").map((part) => ({
content: part.content,
toolCallId: part.toolCallId
}));
}
/**
* Gets all file parts contained in this message.
*/
getToolCallRequests() {
return this.data.content.filter((part) => part.type === "toolCallRequest").map((part) => part.toolCallRequest);
}
/**
* Gets all files contained in this message.
*
* @param client - LMStudio client
*/
getFiles(client) {
return this.getFileParts().map((part) => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name));
}
/**
* Allows iterating over the files in the message.
*/
*files(client) {
for (const part of this.getFileParts()) {
yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
}
}
/**
* Given a predicate, the predicate is called for each file in the message.
*
* - If the predicate returns true, the file is removed from the message and is collected into the
* returned array.
* - If the predicate returns false, the file is kept in the message.
*
* This method is useful if you are implementing a promptPreprocessor that needs to convert certain
* types of files.
*
* If the predicate needs to be async, use the {@link ChatMessage#consumeFilesAsync} method.
*
* @param client - LMStudio client
* @param predicate - The predicate to call for each file.
* @returns The files that were consumed.
*/
consumeFiles(client, predicate) {
this.guardMutable();
const consumedFiles = [];
const partIndexesToRemove = /* @__PURE__ */ new Set();
for (const [index2, part] of this.data.content.entries()) {
if (part.type !== "file") {
continue;
}
const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
if (predicate(file)) {
consumedFiles.push(file);
partIndexesToRemove.add(index2);
}
}
this.data.content = this.data.content.filter((_3, index2) => !partIndexesToRemove.has(index2));
return consumedFiles;
}
/**
* Given an async predicate, the predicate is called for each file in the message.
*
* - If the predicate returns true, the file is removed from the message and is collected into the
* returned array.
* - If the predicate returns false, the file is kept in the message.
*
* This method is useful if you are implementing a promptPreprocessor that needs to convert certain
* types of files.
*
* If you need a synchronous version, use the {@link ChatMessage#consumeFiles} method.
*
* @param client - LMStudio client
* @param predicate - The predicate to call for each file.
* @returns The files that were consumed.
*/
async consumeFilesAsync(client, predicate) {
this.guardMutable();
const consumedFiles = [];
const partIndexesToRemove = /* @__PURE__ */ new Set();
for (const [index2, part] of this.data.content.entries()) {
if (part.type !== "file") {
continue;
}
const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
if (await predicate(file)) {
consumedFiles.push(file);
partIndexesToRemove.add(index2);
}
}
this.data.content = this.data.content.filter((_3, index2) => !partIndexesToRemove.has(index2));
return consumedFiles;
}
/**
* Returns true if this message contains any files.
*/
hasFiles() {
return this.data.content.some((part) => part.type === "file");
}
/**
* Append text to the message.
*/
appendText(text3) {
this.guardMutable();
switch (this.data.role) {
case "assistant":
case "user":
case "system":
this.data.content.push({
type: "text",
text: text3
});
break;
case "tool":
throw new Error(`Cannot append text to a message with role "${this.data.role}"`);
default: {
const exhaustiveCheck = this.data;
throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`);
}
}
}
/**
* Append a file to the message. Takes in a FileHandle. You can obtain a FileHandle from
* `client.files.prepareImage`.
*/
appendFile(file) {
this.guardMutable();
switch (this.data.role) {
case "assistant":
case "user":
case "system":
this.data.content.push({
type: "file",
name: file.name,
identifier: file.identifier,
sizeBytes: file.sizeBytes,
fileType: file.type
});
break;
case "tool":
throw new Error(`Cannot append text to a message with role "${this.data.role}"`);
default: {
const exhaustiveCheck = this.data;
throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`);
}
}
}
/**
* Replaces all text in the messages.
*
* If the message contains other components (such as files), they will kept. The replaced text
* will be inserted to the beginning of the message.
*/
replaceText(text3) {
this.guardMutable();
switch (this.data.role) {
case "assistant":
case "user":
case "system":
this.data.content = [
{ type: "text", text: text3 },
...this.data.content.filter((part) => part.type !== "text")
];
break;
case "tool":
throw new Error(`Cannot replace text in a message with role "${this.data.role}"`);
default: {
const exhaustiveCheck = this.data;
throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`);
}
}
}
isSystemPrompt() {
return this.data.role === "system";
}
isUserMessage() {
return this.data.role === "user";
}
isAssistantMessage() {
return this.data.role === "assistant";
}
toString() {
const text3 = this.data.content.map((part) => {
switch (part.type) {
case "text":
return part.text;
case "file":
return ``;
case "toolCallRequest":
return part.toolCallRequest.name + `(${JSON.stringify(part.toolCallRequest.arguments)})`;
case "toolCallResult":
return part.content;
default: {
const exhaustiveCheck = part;
throw new Error(`Unknown part type: ${exhaustiveCheck.type}`);
}
}
}).join(" ");
if (text3.includes("\n")) {
return this.data.role + ":\n" + text3.split("\n").map((line) => " " + line).join("\n");
} else {
return this.data.role + ": " + text3;
}
}
};
chatMessageLikeSchema = external_exports.union([
external_exports.instanceof(ChatMessage),
chatMessageInputSchema,
external_exports.string(),
chatMessageDataSchema
]);
KVFieldValueTypesLibraryBuilder = class {
constructor(baseSchema) {
this.baseSchema = baseSchema;
this.valueTypes = /* @__PURE__ */ new Map();
}
/**
* Define a new field value type.
*/
valueType(key, param) {
if (this.valueTypes.has(key)) {
throw new Error(`ValueType with key ${key} already exists`);
}
this.valueTypes.set(key, {
paramType: external_exports.object({
...this.baseSchema,
...param.paramType
}),
schemaMaker: param.schemaMaker,
effectiveEquals: param.effectiveEquals,
stringify: param.stringify
});
return this;
}
build() {
return new KVFieldValueTypeLibrary(new Map(this.valueTypes));
}
};
KVFieldValueTypeLibrary = class {
constructor(valueTypes) {
this.valueTypes = valueTypes;
}
/**
* Gets the schema for a specific field value type with the given key and parameters.
*/
getSchema(key, param) {
const valueType = this.valueTypes.get(key);
if (valueType === void 0) {
throw new Error(`Cannot find value type ${key}`);
}
return valueType.schemaMaker(valueType.paramType.parse(param));
}
parseParamTypes(key, param) {
return this.valueTypes.get(key).paramType.parse(param);
}
effectiveEquals(key, typeParam, a3, b4) {
return this.valueTypes.get(key).effectiveEquals(a3, b4, typeParam);
}
stringify(key, typeParam, opts, value) {
return this.valueTypes.get(key).stringify(value, typeParam, opts);
}
};
KVConfigSchematicsBuilder = class _KVConfigSchematicsBuilder {
constructor(valueTypeLibrary) {
this.valueTypeLibrary = valueTypeLibrary;
this.fields = /* @__PURE__ */ new Map();
this.extensionPrefixes = [];
}
/**
* Adds a field
*/
field(key, valueTypeKey, valueTypeParams, defaultValue) {
const schema = this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams);
const defaultValueParseResult = schema.safeParse(defaultValue);
if (!defaultValueParseResult.success) {
throw new Error(`Invalid default value for field ${key}: ${defaultValueParseResult.error.message}`);
}
defaultValue = defaultValueParseResult.data;
if (this.fields.has(key)) {
throw new Error(`Cannot add field with key ${key}. Key already exists in the schematics.`);
}
this.fields.set(key, {
valueTypeKey,
valueTypeParams,
schema: this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams),
fullKey: key,
defaultValue
});
return this;
}
/**
* Adds an extension point. For example, if called with .extension("hello.world"), then any keys
* that match "hello.world.*" will be allowed when going through lenient zod schema. However,
* any extension fields will still not be accessible via this schematics.
*/
extension(prefix) {
this.extensionPrefixes.push(`${prefix}.`);
return this;
}
/**
* Convenience method for grouping a set of fields under a shared namespace.
*
* For example, if we want to create two fields: `some:namespace:a` and `some:namespace:b`.
* Instead of doing:
*
* ```ts
* builder
* .field("some:namespace:a", ...)
* .field("some:namespace:b", ...)
* ```
*
* We can do:
*
* ```ts
* builder.scope("some:namespace", builder =>
* builder
* .field("a", ...)
* .field("b", ...)
* )
* ```
*
* This method does support nesting. Whether to nest or not is up to the user.
*/
scope(scopeKey, fn) {
const innerBuilder = fn(new _KVConfigSchematicsBuilder(this.valueTypeLibrary));
for (const [key, { valueTypeKey, valueTypeParams, schema, defaultValue }] of innerBuilder.fields.entries()) {
const fullKey = `${scopeKey}.${key}`;
if (this.fields.has(fullKey)) {
throw new Error(`Cannot add field with key ${fullKey}. Key already exists in the schematics.`);
}
this.fields.set(fullKey, {
valueTypeKey,
valueTypeParams,
schema,
fullKey,
defaultValue
});
}
this.extensionPrefixes.push(...innerBuilder.extensionPrefixes.map((prefix) => `${scopeKey}.${prefix}`));
return this;
}
build() {
return new KVConfigSchematics(this.valueTypeLibrary, this.fields, this.extensionPrefixes);
}
};
createParsedKVConfig = Symbol("createParsedKVConfig");
KVConfigSchematics = class _KVConfigSchematics {
constructor(valueTypeLibrary, fields, extensionPrefixes) {
this.valueTypeLibrary = valueTypeLibrary;
this.fields = fields;
this.extensionPrefixes = extensionPrefixes;
this.fullKepMap = void 0;
this.lenientZodSchema = void 0;
}
getFieldsMap() {
return new Map([...this.fields.values()].map((field) => [field.fullKey, field]));
}
obtainField(key) {
const field = this.fields.get(key);
if (field === void 0) {
const fieldKeys = [...this.fields.keys()];
let availableList = fieldKeys.slice(0, 10).map((key2) => `- ${key2}`).join("\n");
if (fieldKeys.length > 10) {
availableList += `
... and ${fieldKeys.length - 10} more`;
}
throw new Error(`Cannot access key ${key}. Key does not exist in the schematics. Available keys:
` + availableList);
}
return field;
}
obtainFieldByFullKey(fullKey) {
const field = this.getFullKeyMap().get(fullKey);
if (field === void 0) {
const fieldKeys = [...this.getFullKeyMap().keys()];
let availableList = fieldKeys.slice(0, 10).map((key) => `- ${key}`).join("\n");
if (fieldKeys.length > 10) {
availableList += `
... and ${fieldKeys.length - 10} more`;
}
throw new Error(`Cannot access full key ${fullKey}. Full key does not exist in the schematics. Availablekeys:
` + availableList);
}
return field;
}
getSchemaForKey(key) {
const field = this.obtainField(key);
return field.schema;
}
parseField(fieldSchema, value) {
if (value === void 0) {
if (fieldSchema.defaultValue === void 0) {
throw new Error(`Field with key ${fieldSchema.fullKey} is missing and has no default value`);
}
return fieldSchema.defaultValue;
}
const parseResult = fieldSchema.schema.safeParse(value);
if (!parseResult.success) {
throw new Error(`Field with key ${fieldSchema.fullKey} does not satisfy the schema:` + parseResult.error.message);
}
return parseResult.data;
}
parseFieldWithoutDefault(field, value) {
if (value === void 0) {
return void 0;
}
const parseResult = field.schema.safeParse(value);
if (!parseResult.success) {
throw new Error(`Field with key ${field.fullKey} does not satisfy the schema:` + parseResult.error.message);
}
return parseResult.data;
}
/**
* Parse and access a field in the config.
*/
access(config, key) {
const field = this.obtainField(key);
return this.parseField(field, config.fields.find((f4) => f4.key === field.fullKey)?.value);
}
accessByFullKey(config, fullKey) {
const field = this.obtainFieldByFullKey(fullKey);
return this.parseField(field, config.fields.find((f4) => f4.key === field.fullKey)?.value);
}
/**
* Parse and access a field in the config. Returns undefined if the field is missing.
*/
accessPartial(config, key) {
const field = this.obtainField(key);
return this.parseFieldWithoutDefault(field, config.fields.find((f4) => f4.key === field.fullKey)?.value);
}
/**
* Gets a slice of the config schema with the given key patterns. Support syntax:
*
* - `some.namespace.key`: Matches exactly `some.namespace.key`
* - `some.namespace.*`: Matches anything that starts with `some.namespace.`
*/
sliced(...patterns) {
const parsedPatterns = patterns.map((p4) => {
if (p4.endsWith("*")) {
return { type: "prefix", value: p4.substring(0, p4.length - 1) };
}
return { type: "exact", value: p4 };
});
const newFields = /* @__PURE__ */ new Map();
for (const [key, field] of this.fields.entries()) {
for (const pattern of parsedPatterns) {
if (pattern.type === "exact" && key === pattern.value || pattern.type === "prefix" && key.startsWith(pattern.value)) {
newFields.set(key, field);
}
}
}
return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes);
}
/**
* Get a subset of the config schema with a specific scope.
*/
scoped(scopeKey) {
const newFields = /* @__PURE__ */ new Map();
for (const [key, field] of this.fields.entries()) {
if (key.startsWith(`${scopeKey}.`)) {
newFields.set(key.substring(scopeKey.length + 1), field);
}
}
return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes);
}
union(other) {
const newFields = /* @__PURE__ */ new Map();
for (const [key, field] of this.fields.entries()) {
newFields.set(key, field);
}
for (const [key, field] of other.fields.entries()) {
if (newFields.has(key)) {
throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: " + key);
}
newFields.set(key, field);
}
return new _KVConfigSchematics(this.valueTypeLibrary, newFields, [
...this.extensionPrefixes,
...other.extensionPrefixes
]);
}
/**
* Combine baseKey into the fields. Effectively removes the baseKey.
*/
flattenBaseKey() {
const newFields = /* @__PURE__ */ new Map();
for (const field of this.fields.values()) {
newFields.set(field.fullKey, field);
}
return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes);
}
parseToMap(config) {
const rawConfigMap = kvConfigToMap(config);
const parsedConfigMap = /* @__PURE__ */ new Map();
for (const [key, field] of this.fields.entries()) {
const value = rawConfigMap.get(field.fullKey);
const parsedValue = this.parseField(field, value);
parsedConfigMap.set(key, parsedValue);
}
return parsedConfigMap;
}
parseToMapWithFullKey(config) {
const rawConfigMap = kvConfigToMap(config);
const parsedConfigMap = /* @__PURE__ */ new Map();
for (const field of this.fields.values()) {
const value = rawConfigMap.get(field.fullKey);
const parsedValue = this.parseField(field, value);
parsedConfigMap.set(field.fullKey, parsedValue);
}
return parsedConfigMap;
}
parseToMapPartial(config) {
const rawConfigMap = kvConfigToMap(config);
const parsedConfigMap = /* @__PURE__ */ new Map();
for (const [key, field] of this.fields.entries()) {
const value = rawConfigMap.get(field.fullKey);
const parsedValue = this.parseFieldWithoutDefault(field, value);
if (parsedValue !== void 0) {
parsedConfigMap.set(key, parsedValue);
}
}
return parsedConfigMap;
}
/**
* Parse the given config to a ParsedKVConfig. **Will throw** if the config does not satisfy the
* schema.
*/
parse(config) {
return ParsedKVConfig[createParsedKVConfig](this.parseToMap(config));
}
parsePartial(config) {
return PartialParsedKVConfig[createParsedKVConfig](this.parseToMapPartial(config));
}
/**
* Builds a full KV config from the given values record. **Will throw** if any of the values are
* missing or do not satisfy the schema.
*/
buildFullConfig(valuesRecord) {
return {
fields: Array.from(this.fields.entries()).map(([key, field]) => {
const value = this.parseField(field, valuesRecord[key]);
return { key: field.fullKey, value };
})
};
}
/**
* Builds a partial KV config from the given values record. Will leave holes in the config if the
* values are missing. **Will throw** if any of the values do not satisfy the schema.
*/
buildPartialConfig(valuesRecord) {
return {
fields: Object.entries(valuesRecord).filter(([_key, value]) => value !== void 0).map(([key, value]) => {
const field = this.obtainField(key);
return { key: field.fullKey, value: this.parseField(field, value) };
})
};
}
createBuildPartialConfigInput() {
return {};
}
configBuilder() {
return new KVConfigBuilder(this.fields);
}
clone() {
return new _KVConfigSchematics(this.valueTypeLibrary, new Map(this.fields), this.extensionPrefixes);
}
withTypeParamOverride(key, paramMapper) {
const field = this.obtainField(key);
const clone3 = this.clone();
clone3.fields.set(key, {
...field,
valueTypeParams: paramMapper(field.valueTypeParams),
schema: this.valueTypeLibrary.getSchema(field.valueTypeKey, paramMapper(field.valueTypeParams))
});
return clone3;
}
getFullKeyMap() {
if (this.fullKepMap !== void 0) {
return this.fullKepMap;
}
this.fullKepMap = new Map([...this.fields.values()].map((field) => [field.fullKey, field]));
return this.fullKepMap;
}
makeLenientZodSchema() {
const fullKeyMap = this.getFullKeyMap();
return kvConfigSchema.transform((value) => {
const seenKeys = /* @__PURE__ */ new Set();
return {
fields: value.fields.filter((field) => {
if (this.extensionPrefixes.some((prefix) => field.key.startsWith(prefix))) {
return true;
}
if (seenKeys.has(field.key)) {
return false;
}
const fieldDef = fullKeyMap.get(field.key);
if (fieldDef === void 0) {
return false;
}
const parsed = fieldDef.schema.safeParse(field.value);
if (!parsed.success) {
return false;
}
seenKeys.add(field.key);
return true;
})
};
});
}
/**
* Makes a zod schema that parses a KVConfig which only allows fields with correct keys and types
* through.
*
* Will filter out any fields that are not in the schema.
*/
getLenientZodSchema() {
if (this.lenientZodSchema !== void 0) {
return this.lenientZodSchema;
}
this.lenientZodSchema = this.makeLenientZodSchema();
return this.lenientZodSchema;
}
getValueType(key) {
const field = this.fields.get(key);
if (field === void 0) {
return null;
}
return field.valueTypeKey;
}
getValueTypeParam(key) {
const field = this.fields.get(key);
if (field === void 0) {
return null;
}
return field.valueTypeParams;
}
getValueTypeParamByFullKey(key) {
const field = this.getFullKeyMap().get(key);
if (field === void 0) {
throw new Error(`Field with key ${key} does not exist in the schematics`);
}
return field.valueTypeParams;
}
hasFullKey(key) {
const field = this.getFullKeyMap().get(key);
return field !== void 0;
}
/**
* Given a KVConfig, filter it to only include fields that are in the schematics.
*/
filterConfig(config, additionalFilter) {
const fullKeyMap = this.getFullKeyMap();
return {
fields: config.fields.filter((configField) => {
const field = fullKeyMap.get(configField.key);
if (field === void 0) {
return false;
}
if (additionalFilter !== void 0) {
return additionalFilter(field.fullKey, {
type: field.valueTypeKey,
param: field.valueTypeParams
});
}
return true;
})
};
}
/**
* Given a KVConfigStack, filter it to only include fields that are in the schematics.
*/
filterStack(stack) {
return {
layers: stack.layers.map((layer) => ({
layerName: layer.layerName,
config: this.filterConfig(layer.config)
}))
};
}
twoWayFilterConfig(config, additionalFilter) {
const includedFields = [];
const excludedFields = [];
const fullKeyMap = this.getFullKeyMap();
for (const configField of config.fields) {
const field = fullKeyMap.get(configField.key);
let include = field !== void 0;
if (field !== void 0 && additionalFilter !== void 0) {
include = additionalFilter(field.fullKey, {
type: field.valueTypeKey,
param: field.valueTypeParams
});
}
if (include) {
includedFields.push(configField);
} else {
excludedFields.push(configField);
}
}
return [{ fields: includedFields }, { fields: excludedFields }];
}
/**
* Given a list of keys, filter it to only include keys that are in the schematics.
*/
filterFullKeys(keys2) {
const fullKeyMap = this.getFullKeyMap();
return keys2.filter((key) => fullKeyMap.has(key));
}
/**
* Compares two KV config. Compare with "effective equals". Only compare fields in the schematics.
* Does not apply defaults.
*/
configEffectiveEquals(a3, b4) {
const aMap = kvConfigToMap(a3);
const bMap = kvConfigToMap(b4);
for (const field of this.fields.values()) {
const aValue = aMap.get(field.fullKey);
const bValue = bMap.get(field.fullKey);
if (aValue === void 0) {
if (bValue === void 0) {
continue;
} else {
return false;
}
}
this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue);
}
return true;
}
/**
* Compares two KV config field. Compare with "effective equals". Can only compare fields in the
* schematics.
*/
fieldEffectiveEquals(key, a3, b4) {
const field = this.obtainField(key);
return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a3), field.schema.parse(b4));
}
fieldEffectiveEqualsWithFullKey(fullKey, a3, b4) {
const fullKeyMap = this.getFullKeyMap();
const field = fullKeyMap.get(fullKey);
if (field === void 0) {
throw new Error(`Field with key ${fullKey} does not exist in the schematics`);
}
return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a3), field.schema.parse(b4));
}
makeInternalFieldStringifyOpts(opts) {
return {
t: opts.t ?? ((_key, fallback) => fallback),
desiredLength: opts.desiredLength
};
}
stringifyField(key, value, opts = {}) {
const field = this.obtainField(key);
return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value);
}
tryStringifyFieldWithFullKey(key, value, opts) {
const fullKeyMap = this.getFullKeyMap();
const field = fullKeyMap.get(key);
if (field === void 0) {
return null;
}
return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value);
}
/**
* Apply config in patch to target. Only apply fields that are in the schematics.
*/
apply(target, patch) {
const filteredPatch = this.filterConfig(patch);
return collapseKVStackRaw([target, filteredPatch]);
}
/**
* Tries to un-apply the patch from the target. Will only un-apply fields that are in the
* schematics.
*
* If the value in the target is not effective equal to the value in the patch, it will not be
* removed.
*/
unApply(target, patch) {
const filteredPatch = this.filterConfig(patch);
const patchMap = kvConfigToMap(filteredPatch);
const newMap = new Map(kvConfigToMap(target));
const fullKeyMap = this.getFullKeyMap();
for (const [key, value] of patchMap.entries()) {
const field = fullKeyMap.get(key);
if (field === void 0) {
continue;
}
const targetValue = newMap.get(key);
if (targetValue !== void 0) {
if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, value, targetValue)) {
continue;
}
newMap.delete(key);
}
}
return mapToKVConfig(newMap);
}
/**
* Given a KVConfig, iterate through all the fields that are in the schematics. Keys will be full
* keys.
*/
*iterateFieldsOfConfig(config) {
const fullKeyMap = this.getFullKeyMap();
for (const { key, value } of config.fields) {
const field = fullKeyMap.get(key);
if (field !== void 0) {
yield [key, value];
}
}
}
/**
* Given a KVConfig, iterate through all the fields that are in the schematics.
*/
*fullKeys() {
const fullKeyMap = this.getFullKeyMap();
for (const key of fullKeyMap.keys()) {
yield key;
}
}
/**
* Effectively compare two KV config, and return full keys of fields that are different.
*/
effectiveCompareConfig(a3, b4, opts = {}) {
const { fieldFilter } = opts;
const aMap = kvConfigToMap(a3);
const bMap = kvConfigToMap(b4);
const onlyInA = [];
const onlyInB = [];
const inBothButDifferent = [];
for (const field of this.fields.values()) {
if (fieldFilter !== void 0) {
if (!fieldFilter(field.fullKey, {
type: field.valueTypeKey,
param: field.valueTypeParams
})) {
continue;
}
}
const aValue = aMap.get(field.fullKey);
const bValue = bMap.get(field.fullKey);
if (aValue === void 0) {
if (bValue === void 0) {
continue;
} else {
onlyInB.push(field.fullKey);
}
} else {
if (bValue === void 0) {
onlyInA.push(field.fullKey);
} else {
if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue)) {
inBothButDifferent.push(field.fullKey);
}
}
}
}
return { onlyInA, onlyInB, inBothButDifferent };
}
serialize() {
return {
fields: [...this.fields.entries()].map(([key, field]) => ({
shortKey: key,
fullKey: field.fullKey,
typeKey: field.valueTypeKey,
typeParams: field.valueTypeParams,
defaultValue: field.defaultValue
})),
extensionPrefixes: this.extensionPrefixes
};
}
/**
* Check if any of the fields in the schematics has a full key that starts with the given prefix.
*/
hasFieldsWithPrefix(prefix) {
for (const field of this.fields.values()) {
if (field.fullKey.startsWith(prefix)) {
return true;
}
}
return false;
}
static deserialize(valueTypeLibrary, serialized) {
const fields = new Map(serialized.fields.map((field) => {
const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams);
const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams);
return [
field.shortKey,
{
valueTypeKey: field.typeKey,
valueTypeParams: typeParams,
schema: valueSchema,
fullKey: field.fullKey,
defaultValue: valueSchema.parse(field.defaultValue)
}
];
}));
return new _KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []);
}
static tryDeserialize(valueTypeLibrary, serialized) {
const fields = /* @__PURE__ */ new Map();
const errors = [];
for (const field of serialized.fields) {
try {
const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams);
const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams);
fields.set(field.shortKey, {
valueTypeKey: field.typeKey,
valueTypeParams: typeParams,
schema: valueSchema,
fullKey: field.fullKey,
defaultValue: valueSchema.parse(field.defaultValue)
});
} catch (error) {
errors.push({
fullKey: field.fullKey,
error: serializeError(error)
});
}
}
return {
schematics: new _KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []),
errors
};
}
};
KVConfigBuilder = class {
constructor(fieldDefs) {
this.fieldDefs = fieldDefs;
this.fields = /* @__PURE__ */ new Map();
}
with(key, value) {
const field = this.fieldDefs.get(key);
if (field === void 0) {
throw new Error(`Field with key ${key} does not exist in the schematics.`);
}
this.fields.set(field.fullKey, value);
return this;
}
build() {
return mapToKVConfig(this.fields);
}
};
ParsedKVConfig = class _ParsedKVConfig {
constructor(configMap) {
this.configMap = configMap;
}
/**
* @internal
*/
static [createParsedKVConfig](configMap) {
return new _ParsedKVConfig(configMap);
}
get(key) {
return this.configMap.get(key);
}
};
PartialParsedKVConfig = class _PartialParsedKVConfig {
constructor(configMap) {
this.configMap = configMap;
}
static [createParsedKVConfig](configMap) {
return new _PartialParsedKVConfig(configMap);
}
get(key) {
return this.configMap.get(key);
}
has(key) {
return this.configMap.has(key);
}
};
emptyKVConfig = {
fields: []
};
baseKVValueTypesLibraryBuilder = new KVFieldValueTypesLibraryBuilder({
/**
* Display name of the field.
*/
displayName: external_exports.string().optional(),
/**
* Hint about the field. Shown when hovering over the field.
*/
hint: external_exports.string().optional(),
/**
* A field can be marked as model centric when it loses its meaning when there is no model to
* reference.
*
* An example would be prompt template. There is no point to configure prompt template when there
* isn't a specific model.
*
* @experimental This field is experimental and may change in the future.
*/
modelCentric: external_exports.boolean().optional(),
/**
* A field can be marked as non-configurable when it is only used as a means to carry information.
* As a result, it will not be shown in the UI.
*
* An example would be context length for MLX, as you cannot change it.
*
* @experimental This field is experimental and may change in the future.
*/
nonConfigurable: external_exports.boolean().optional(),
/**
* A field can be marked as engineDoesNotSupport when when the engine running the model does not
* support the field.
*
* @experimental This field is experimental and may change in the future.
*/
engineDoesNotSupport: external_exports.boolean().optional(),
/**
* A field can be marked as machine dependent when its value is highly dependent on the machine
* that is being used. When exporting the config, one may decide to not include machine dependent
* fields by default.
*
* An example would be GPU offload settings.
*
* @experimental This field is experimental and may change in the future.
*/
machineDependent: external_exports.boolean().optional(),
warning: external_exports.string().optional(),
subtitle: external_exports.string().optional(),
isExperimental: external_exports.boolean().optional(),
dependencies: external_exports.array(kvConfigFieldDependencySchema).optional()
}).valueType("numeric", {
paramType: {
min: external_exports.number().optional(),
max: external_exports.number().optional(),
step: external_exports.number().optional(),
int: external_exports.boolean().optional(),
precision: external_exports.number().int().nonnegative().optional(),
slider: external_exports.object({
min: external_exports.number(),
max: external_exports.number(),
step: external_exports.number()
}).optional(),
shortHand: external_exports.string().optional()
},
schemaMaker: ({ min, max, int, precision }) => {
let schema = external_exports.number();
if (min !== void 0) {
schema = schema.min(min);
}
if (max !== void 0) {
schema = schema.max(max);
}
if (int) {
if (precision !== void 0) {
throw new Error("Cannot specify both int and precision.");
}
schema = schema.int();
}
return schema;
},
effectiveEquals: (a3, b4) => {
return a3 === b4;
},
stringify: (value, { int, precision }) => {
if (int) {
return String(Math.round(value));
}
return value.toFixed(precision ?? 2);
}
}).valueType("string", {
paramType: {
minLength: external_exports.number().optional(),
maxLength: external_exports.number().optional(),
isParagraph: external_exports.boolean().optional(),
isProtected: external_exports.boolean().optional(),
/**
* If true, the string should match to a single token.
*/
isToken: external_exports.boolean().optional(),
placeholder: external_exports.string().optional()
},
schemaMaker: ({ minLength, maxLength }) => {
let schema = external_exports.string();
if (minLength !== void 0) {
schema = schema.min(minLength);
}
if (maxLength !== void 0) {
schema = schema.max(maxLength);
}
return schema;
},
effectiveEquals: (a3, b4) => {
return a3 === b4;
},
stringify: (value, { isParagraph, isProtected }, { t: t6, desiredLength }) => {
if (isProtected) {
return "********";
}
if (isParagraph) {
if (value === "") {
return t6("config:customInputs.string.emptyParagraph", "");
} else {
if (desiredLength === void 0 || value.length <= desiredLength) {
return value;
} else {
return value.slice(0, Math.floor(desiredLength / 2)) + " ... " + value.slice(-Math.ceil(desiredLength / 2));
}
}
} else {
const quoted = quoteString(value);
if (desiredLength === void 0 || quoted.length <= desiredLength) {
return quoted;
} else {
return quoted.slice(0, Math.floor(desiredLength / 2)) + "..." + quoted.slice(-Math.ceil(desiredLength / 2));
}
}
}
}).valueType("select", {
paramType: {
options: external_exports.array(external_exports.object({ value: external_exports.string().nonempty(), displayName: external_exports.string() }).or(external_exports.string())).refine((options) => {
const values2 = /* @__PURE__ */ new Set();
for (const option of options) {
const value = typeof option === "string" ? option : option.value;
if (values2.has(value)) {
return false;
}
values2.add(value);
}
return true;
}, {
message: "Duplicate values in options."
})
},
schemaMaker: ({ options }) => {
const allowedValues = new Set(options.map((option) => typeof option === "string" ? option : option.value));
return external_exports.string().refine((value) => allowedValues.has(value));
},
effectiveEquals: (a3, b4) => {
return a3 === b4;
},
stringify: (value) => {
return value;
}
}).valueType("boolean", {
paramType: {},
schemaMaker: () => {
return external_exports.boolean();
},
effectiveEquals: (a3, b4) => {
return a3 === b4;
},
stringify: (value) => {
return value ? "ON" : "OFF";
}
}).valueType("stringArray", {
paramType: {
maxNumItems: external_exports.number().optional(),
/**
* Whether to allow empty strings in the array. Default is false.
*/
allowEmptyStrings: external_exports.boolean().optional()
},
schemaMaker: ({ maxNumItems, allowEmptyStrings }) => {
let stringSchema = external_exports.string();
if (!allowEmptyStrings) {
stringSchema = stringSchema.min(1);
}
let schema = external_exports.array(stringSchema);
if (maxNumItems !== void 0) {
schema = schema.max(maxNumItems);
}
return schema;
},
effectiveEquals: (a3, b4) => {
return a3.length === b4.length && a3.every((v4, i7) => v4 === b4[i7]);
},
stringify: (value, _typeParam, { t: t6, desiredLength }) => {
const quoted = value.map((v4) => quoteString(v4));
if (quoted.length === 0) {
return t6("config:customInputs.stringArray.empty", "");
}
if (quoted.length <= 2 || desiredLength === void 0) {
return quoted.join(", ");
}
let currentLength = quoted[0].length + quoted[1].length + 6;
for (let i7 = 1; i7 < quoted.length - 1; i7++) {
currentLength += quoted[i7].length + 2;
if (currentLength >= desiredLength) {
return quoted.slice(0, i7).join(", ") + ", ..." + quoted[quoted.length - 1];
}
}
return quoted.join(", ");
}
});
baseKVValueTypesLibraryBuilder.build();
kvValueTypesLibrary = baseKVValueTypesLibraryBuilder.valueType("checkboxNumeric", {
paramType: {
min: external_exports.number().optional(),
max: external_exports.number().optional(),
step: external_exports.number().optional(),
int: external_exports.boolean().optional(),
uncheckedHint: external_exports.string().optional(),
precision: external_exports.number().int().nonnegative().optional(),
slider: external_exports.object({
min: external_exports.number(),
max: external_exports.number(),
step: external_exports.number()
}).optional()
},
schemaMaker: ({ min, max, int, precision }) => {
let numberSchema = external_exports.number();
if (min !== void 0) {
numberSchema = numberSchema.min(min);
}
if (max !== void 0) {
numberSchema = numberSchema.max(max);
}
if (int) {
if (precision !== void 0) {
throw new Error("Cannot specify both int and precision.");
}
numberSchema = numberSchema.int();
}
return external_exports.object({
checked: external_exports.boolean(),
value: numberSchema
});
},
effectiveEquals: (a3, b4) => {
if (a3.checked !== b4.checked) {
return false;
}
if (!a3.checked) {
return true;
}
return a3.value === b4.value;
},
stringify: (value, { int, precision }, { t: t6 }) => {
if (!value.checked) {
return t6("config:customInputs.checkboxNumeric.off", "OFF");
}
if (int) {
return String(Math.round(value.value));
}
return value.value.toFixed(precision ?? 2);
}
}).valueType("numericArray", {
paramType: {
min: external_exports.number().optional(),
max: external_exports.number().optional(),
int: external_exports.boolean().optional()
},
schemaMaker: ({ min, max, int }) => {
let numberSchema = external_exports.number();
if (min !== void 0) {
numberSchema = numberSchema.min(min);
}
if (max !== void 0) {
numberSchema = numberSchema.max(max);
}
if (int) {
numberSchema = numberSchema.int();
}
return external_exports.array(numberSchema);
},
effectiveEquals: (a3, b4) => {
return a3.length === b4.length && a3.every((v4, i7) => v4 === b4[i7]);
},
stringify: (value, { int }) => {
return value.map((v4) => int ? String(Math.round(v4)) : String(v4)).join(", ");
}
}).valueType("contextOverflowPolicy", {
paramType: {},
schemaMaker: () => {
return llmContextOverflowPolicySchema;
},
effectiveEquals: (a3, b4) => {
return a3 === b4;
},
stringify: (value, _typeParam, { t: t6 }) => {
switch (value) {
case "stopAtLimit":
return t6("config:customInputs.contextOverflowPolicy.stopAtLimit", "Stop At Limit");
case "truncateMiddle":
return t6("config:customInputs.contextOverflowPolicy.truncateMiddle", "Truncate Middle");
case "rollingWindow":
return t6("config:customInputs.contextOverflowPolicy.rollingWindow", "Rolling Window");
}
}
}).valueType("context", {
paramType: {},
schemaMaker: () => {
return external_exports.array(llmContextReferenceSchema);
},
effectiveEquals: (a3, b4) => {
return deepEquals(a3, b4);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("contextLength", {
paramType: {
max: external_exports.number().optional()
},
schemaMaker: () => {
return external_exports.number().int().positive();
},
effectiveEquals: (a3, b4) => {
return a3 === b4;
},
stringify: (value, { max }) => {
if (max === void 0) {
return String(value);
}
return `${value}/${max}`;
}
}).valueType("modelIdentifier", {
paramType: {
domain: external_exports.array(modelDomainTypeSchema).optional()
},
schemaMaker: () => {
return external_exports.string();
},
effectiveEquals: (a3, b4) => {
return a3 === b4;
},
stringify: (value) => {
return value;
}
}).valueType("llmPromptTemplate", {
paramType: {},
schemaMaker: () => {
return llmPromptTemplateSchema;
},
effectiveEquals: (a3, b4) => {
if (a3.type !== b4.type) {
return false;
}
if (a3.stopStrings.length !== b4.stopStrings.length) {
return false;
}
if (!a3.stopStrings.every((v4, i7) => v4 === b4.stopStrings[i7])) {
return false;
}
switch (a3.type) {
case "jinja":
return a3.jinjaPromptTemplate?.template === b4.jinjaPromptTemplate?.template;
case "manual":
return a3.manualPromptTemplate?.beforeSystem === b4.manualPromptTemplate?.beforeSystem && a3.manualPromptTemplate?.afterSystem === b4.manualPromptTemplate?.afterSystem && a3.manualPromptTemplate?.beforeUser === b4.manualPromptTemplate?.beforeUser && a3.manualPromptTemplate?.afterUser === b4.manualPromptTemplate?.afterUser && a3.manualPromptTemplate?.beforeAssistant === b4.manualPromptTemplate?.beforeAssistant && a3.manualPromptTemplate?.afterAssistant === b4.manualPromptTemplate?.afterAssistant;
default: {
const exhaustiveCheck = a3.type;
throw new Error("Unknown template type: " + exhaustiveCheck);
}
}
},
stringify: (value, _typeParam, { t: t6, desiredLength }) => {
switch (value.type) {
case "jinja": {
const lead = `${t6("config:customInputs.llmPromptTemplate.type", "Type")}: ${t6("config:customInputs.llmPromptTemplate.types.jinja/label", "Jinja")}
${t6("config:customInputs.llmPromptTemplate.jinja.template/label", "Template")}: `;
if (desiredLength === void 0) {
return lead + value.jinjaPromptTemplate?.template;
}
const currentLength = lead.length;
const remainingLength = Math.min(100, desiredLength - currentLength);
const template = value.jinjaPromptTemplate?.template ?? "";
if (template.length <= remainingLength) {
return lead + template;
}
return lead + template.slice(0, Math.floor(remainingLength / 2)) + "..." + template.slice(-Math.ceil(remainingLength / 2));
}
case "manual": {
return `${t6("config:customInputs.llmPromptTemplate.type", "Type")}: ${t6("config:customInputs.llmPromptTemplate.types.manual/label", "Manual")}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.beforeSystem/label", "Before System")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeSystem)}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.afterSystem/label", "After System")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterSystem)}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.beforeUser/label", "Before User")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeUser)}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.afterUser/label", "After User")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterUser)}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.beforeAssistant/label", "Before Assistant")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeAssistant)}
${t6("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label", "After Assistant")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterAssistant)}`;
}
default: {
const exhaustiveCheck = value.type;
throw new Error("Unknown template type: " + exhaustiveCheck);
}
}
}
}).valueType("llmReasoningParsing", {
paramType: {},
schemaMaker: () => {
return llmReasoningParsingSchema;
},
effectiveEquals: (a3, b4) => {
return a3.startString === b4.startString && a3.endString === b4.endString;
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("llamaStructuredOutput", {
paramType: {},
schemaMaker: () => {
return llmStructuredPredictionSettingSchema;
},
effectiveEquals: (a3, b4) => {
if (a3.type === "json" && b4.type === "json") {
return deepEquals(a3, b4);
} else if (a3.type === "none" && b4.type === "none") {
return true;
} else {
return false;
}
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("speculativeDecodingDraftModel", {
paramType: {},
schemaMaker: () => {
return external_exports.string();
},
effectiveEquals: (a3, b4) => {
return a3 === b4;
},
stringify: (value, _typeParam, { t: t6 }) => {
if (value === "") {
return t6("config:customInputs.speculativeDecodingDraftModel.off", "OFF");
}
return value;
}
}).valueType("toolUse", {
paramType: {},
schemaMaker: () => {
return llmToolUseSettingSchema;
},
effectiveEquals: (a3, b4) => {
return deepEquals(a3, b4);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("toolNaming", {
paramType: {},
schemaMaker: () => {
return toolNamingSchema;
},
effectiveEquals: (a3, b4) => {
return a3 === b4;
},
stringify: (value) => {
return value;
}
}).valueType("llamaAccelerationOffloadRatio", {
paramType: {
numLayers: external_exports.number().optional()
},
schemaMaker: () => {
return llmLlamaAccelerationOffloadRatioSchema;
},
effectiveEquals: (a3, b4) => {
const ratioA = a3 === "max" ? 1 : a3 === "off" ? 0 : a3;
const ratioB = b4 === "max" ? 1 : b4 === "off" ? 0 : b4;
return ratioA === ratioB;
},
stringify: (value, { numLayers }, { t: t6 }) => {
if (value === "max" || value === 1) {
const label = t6("config:customInputs.llamaAccelerationOffloadRatio.max", "MAX");
if (numLayers !== 0) {
return `${label} (${numLayers})`;
}
return label;
}
if (value === "off" || value === 0) {
return t6("config:customInputs.llamaAccelerationOffloadRatio.off", "OFF");
}
if (numLayers !== void 0) {
return String(Math.round(numLayers * value));
}
return (value * 100).toFixed(0) + "%";
}
}).valueType("llamaMirostatSampling", {
paramType: {},
schemaMaker: () => {
return llmLlamaMirostatSamplingConfigSchema;
},
effectiveEquals: (a3, b4) => {
return deepEquals(a3, b4);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("llamaLogitBias", {
paramType: {},
schemaMaker: () => {
return llmLlamaLogitBiasConfigSchema;
},
effectiveEquals: (a3, b4) => {
return deepEquals(a3, b4);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("llamaCacheQuantizationType", {
paramType: {},
schemaMaker: () => {
return external_exports.object({
checked: external_exports.boolean(),
value: llmLlamaCacheQuantizationTypeSchema
});
},
effectiveEquals: (a3, b4) => {
if (a3.checked !== b4.checked) {
return false;
}
if (!a3.checked) {
return true;
}
return a3.value === b4.value;
},
stringify: (value, _typeParam, { t: t6 }) => {
if (!value.checked) {
return t6("config:customInputs.llamaCacheQuantizationType.off", "OFF");
}
return value.value;
}
}).valueType("mlxKvCacheQuantizationType", {
paramType: {},
schemaMaker: () => {
return llmMlxKvCacheQuantizationSchema;
},
effectiveEquals: (a3, b4) => {
if (a3.enabled !== b4.enabled) {
return false;
}
if (!a3.enabled) {
return true;
}
return a3.bits === b4.bits && a3.groupSize === b4.groupSize && a3.quantizedStart === b4.quantizedStart;
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("retrievalChunkingMethod", {
paramType: {},
schemaMaker: () => {
return retrievalChunkingMethodSchema;
},
effectiveEquals: (a3, b4) => {
return deepEquals(a3, b4);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("envVars", {
paramType: {},
schemaMaker: () => {
return allowableEnvVarsSchema;
},
effectiveEquals: (a3, b4) => {
return deepEquals(a3, b4);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("gpuSplitConfig", {
paramType: {},
schemaMaker: () => {
return gpuSplitConfigSchema;
},
effectiveEquals: (a3, b4) => {
return deepEquals(a3, b4);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).build();
globalConfigSchematics = new KVConfigSchematicsBuilder(kvValueTypesLibrary).extension("ext.virtualModel.customField").field("envVars", "envVars", {}, {}).scope("llm.prediction", (builder) => builder.field("temperature", "numeric", {
min: 0,
step: 0.01,
slider: { min: 0, max: 1, step: 0.01 },
precision: 2,
shortHand: "temp"
}, 0.8).field("contextOverflowPolicy", "contextOverflowPolicy", {}, "truncateMiddle").field("maxPredictedTokens", "checkboxNumeric", { min: 1, int: true }, { checked: false, value: 1e3 }).field("stopStrings", "stringArray", {}, []).field("toolCallStopStrings", "stringArray", {}, []).field("structured", "llamaStructuredOutput", {}, { type: "none" }).scope("speculativeDecoding", (builder2) => builder2.field("draftModel", "speculativeDecodingDraftModel", {
modelCentric: true
}, "").field("minDraftLengthToConsider", "numeric", {
modelCentric: true,
min: 0,
int: true,
slider: { min: 0, max: 10, step: 1 }
}, 0).field("numReuseTokens", "numeric", { modelCentric: true, min: 1, int: true }, 256).field("minContinueDraftingProbability", "numeric", {
modelCentric: true,
min: 0,
max: 1,
step: 0.01,
precision: 2,
slider: { min: 0, max: 1, step: 0.01 }
}, 0.75).field("maxTokensToDraft", "numeric", { modelCentric: true, min: 1, int: true, slider: { min: 10, max: 30, step: 1 } }, 16).field("numDraftTokensExact", "numeric", {
modelCentric: true,
min: 1,
int: true,
slider: { min: 1, max: 10, step: 1 }
}, 2)).field("tools", "toolUse", {}, { type: "none" }).field("toolNaming", "toolNaming", {}, "removeSpecial").field("promptTemplate", "llmPromptTemplate", { modelCentric: true }, {
type: "manual",
manualPromptTemplate: {
beforeSystem: "Instruct: ",
afterSystem: "\n",
beforeAssistant: "AI: ",
afterAssistant: "\n",
beforeUser: "Human: ",
afterUser: "\n"
},
stopStrings: []
}).field("systemPrompt", "string", { isParagraph: true }, "").field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).field("contextPrefill", "context", {}, []).field("topKSampling", "numeric", { min: -1, max: 500, int: true }, 40).field("repeatPenalty", "checkboxNumeric", { min: -1, step: 0.01 }, { checked: true, value: 1.1 }).field("minPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.05 }).field("topPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.95 }).field("logProbs", "checkboxNumeric", { min: 0, max: 100, int: true }, { checked: false, value: 0 }).scope("reasoning", (builder2) => builder2.field("parsing", "llmReasoningParsing", {}, {
enabled: true,
startString: "",
endString: " "
})).scope("llama", (builder2) => builder2.field("cpuThreads", "numeric", { min: 1, int: true }, 4).field("frequencyPenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0 }).field("xtcProbability", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.5 }).field("xtcThreshold", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 0.5, step: 0.01 } }, { checked: false, value: 0.1 }).field("presencePenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0 }).field("mirostatSampling", "llamaMirostatSampling", {}, {
// Disabled by default
version: 0,
learningRate: 0.1,
targetEntropy: 5
}).field("tailFreeSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.95 }).field("locallyTypicalSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.9 }).field("logitBias", "llamaLogitBias", {}, []))).scope("llm.load", (builder) => builder.field("contextLength", "contextLength", {
machineDependent: true
}, 2048).field("numExperts", "numeric", { min: 0, int: true }, 0).field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).field("offloadKVCacheToGpu", "boolean", {}, true).field("numCpuExpertLayersRatio", "llamaAccelerationOffloadRatio", { machineDependent: true, isExperimental: true }, "off").scope("llama", (builder2) => builder2.scope("acceleration", (builder3) => builder3.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")).field("cpuThreadPoolSize", "numeric", { min: 1, machineDependent: true }, 4).field("evalBatchSize", "numeric", { min: 1, int: true }, 512).field("flashAttention", "boolean", { isExperimental: true, warning: "config:flashAttentionWarning" }, false).field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }).field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }).field("keepModelInMemory", "boolean", {}, true).field("useFp16ForKVCache", "boolean", {}, true).field("tryMmap", "boolean", {}, true).field("kCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true }, { checked: false, value: "f16" }).field("vCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true, warning: "config:llamaKvCacheQuantizationWarning" }, { checked: false, value: "f16" })).scope("mlx", (builder2) => builder2.field("kvCacheQuantization", "mlxKvCacheQuantizationType", { isExperimental: true }, { enabled: false, bits: 8, groupSize: 64, quantizedStart: 5e3 }))).scope("load", (builder) => builder.field("gpuSplitConfig", "gpuSplitConfig", {}, defaultGPUSplitConfig).field("gpuStrictVramCap", "boolean", {}, false)).scope("embedding.load", (builder) => builder.field("contextLength", "contextLength", { machineDependent: true }, 2048).field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).scope("llama", (builder2) => builder2.scope("acceleration", (builder3) => builder3.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")).field("evalBatchSize", "numeric", { min: 1, int: true }, 512).field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }).field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }).field("keepModelInMemory", "boolean", {}, true).field("tryMmap", "boolean", {}, true))).scope("retrieval", (builder) => builder.field("databaseFile", "string", { machineDependent: true }, "").field("chunkingMethod", "retrievalChunkingMethod", {}, {
type: "recursive-v1",
chunkSize: 512,
chunkOverlap: 100
}).field("limit", "numeric", { min: 1, int: true }, 5).field("embeddingModel", "modelIdentifier", { domain: ["embedding"] }, "")).build();
llmPredictionConfigSchematics = globalConfigSchematics.scoped("llm.prediction");
llmSharedPredictionConfigSchematics = llmPredictionConfigSchematics.sliced("temperature", "maxPredictedTokens", "promptTemplate", "systemPrompt", "seed", "contextPrefill", "tools", "toolNaming", "reasoning.*");
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("llama.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "topKSampling", "repeatPenalty", "minPSampling", "topPSampling", "logProbs", "speculativeDecoding.draftModel", "speculativeDecoding.minContinueDraftingProbability", "speculativeDecoding.minDraftLengthToConsider", "speculativeDecoding.maxTokensToDraft", "speculativeDecoding.numReuseTokens"));
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("mlx.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "repeatPenalty", "minPSampling", "topPSampling", "topKSampling", "speculativeDecoding.draftModel", "speculativeDecoding.numDraftTokensExact"));
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("transformers.*"));
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("onnx.*", "repeatPenalty", "topPSampling", "topKSampling"));
llmLoadSchematics = globalConfigSchematics.scoped("llm.load").union(globalConfigSchematics.sliced("envVars"));
llmSharedLoadConfigSchematics = llmLoadSchematics.sliced("contextLength", "seed", "envVars");
llamaLoadConfigSchematics = globalConfigSchematics.sliced("llama.load.*", "load.*");
llmLlamaLoadConfigSchematics = llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("llama.*", "load.*", "offloadKVCacheToGpu")).union(llamaLoadConfigSchematics);
llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("mlx.*"));
llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("transformers.*"));
llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("onnx.*"));
llmLlamaMoeAdditionalLoadConfigSchematics = llmLoadSchematics.sliced("numExperts", "numCpuExpertLayersRatio");
llmLlamaMoeLoadConfigSchematics = llmLlamaLoadConfigSchematics.union(llmLlamaMoeAdditionalLoadConfigSchematics);
embeddingLoadSchematics = globalConfigSchematics.scoped("embedding.load").union(globalConfigSchematics.sliced("load.*"));
embeddingSharedLoadConfigSchematics = embeddingLoadSchematics.sliced("contextLength", "seed");
retrievalSchematics = globalConfigSchematics.scoped("retrieval");
embeddingLlamaLoadConfigSchematics = embeddingSharedLoadConfigSchematics.union(embeddingLoadSchematics.sliced("llama.*")).union(llamaLoadConfigSchematics);
new KVConfigSchematicsBuilder(kvValueTypesLibrary).build();
lib = {};
helpers = {};
scan = {};
libExports = requireLib();
toolBaseSchema = external_exports.object({
name: external_exports.string(),
description: external_exports.string()
});
SimpleToolCallContext = class {
constructor(logger2, signal, callId) {
this.logger = logger2;
this.signal = signal;
this.callId = callId;
}
status(text3) {
this.logger.info(text3);
}
warn(text3) {
this.logger.warn(text3);
}
};
functionToolSchema = toolBaseSchema.extend({
type: external_exports.literal("function"),
parametersSchema: zodSchemaSchema,
checkParameters: external_exports.function(),
implementation: external_exports.function()
});
rawFunctionToolSchema = toolBaseSchema.extend({
type: external_exports.literal("rawFunction"),
parametersSchema: zodSchemaSchema,
checkParameters: external_exports.function(),
implementation: external_exports.function()
});
unimplementedRawFunctionToolSchema = toolBaseSchema.extend({
type: external_exports.literal("unimplementedRawFunction"),
parametersJsonSchema: zodSchemaSchema,
checkParameters: external_exports.function(),
implementation: external_exports.function()
});
remoteToolSchema = toolBaseSchema.extend({
type: external_exports.literal("remoteTool"),
pluginIdentifier: external_exports.string(),
parametersJsonSchema: zodSchemaSchema,
checkParameters: external_exports.function(),
implementation: external_exports.function()
});
external_exports.discriminatedUnion("type", [
functionToolSchema,
rawFunctionToolSchema,
unimplementedRawFunctionToolSchema,
remoteToolSchema
]);
UnimplementedToolError = class extends Error {
constructor(toolName) {
super(`Tool "${toolName}" is not implemented.`);
}
};
ToolCallRequestError = class extends Error {
constructor(message, rawContent) {
super(message);
this.rawContent = rawContent;
}
};
BackendInterface = class {
constructor() {
this.unhandledEndpoints = /* @__PURE__ */ new Set();
this.existingEndpointNames = /* @__PURE__ */ new Set();
this.rpcEndpoints = /* @__PURE__ */ new Map();
this.channelEndpoints = /* @__PURE__ */ new Map();
this.signalEndpoints = /* @__PURE__ */ new Map();
this.writableSignalEndpoints = /* @__PURE__ */ new Map();
}
withContextType() {
return this;
}
assertEndpointNameNotExists(endpointName) {
if (this.existingEndpointNames.has(endpointName)) {
throw new Error(`Endpoint with name ${endpointName} already exists`);
}
}
/**
* Register an Rpc endpoint.
*/
addRpcEndpoint(endpointName, { parameter, returns, serialization = "raw" }) {
this.assertEndpointNameNotExists(endpointName);
this.existingEndpointNames.add(endpointName);
this.rpcEndpoints.set(endpointName, {
name: endpointName,
parameter,
returns,
serialization,
handler: null
});
return this;
}
addChannelEndpoint(endpointName, { creationParameter, toServerPacket, toClientPacket, serialization = "raw" }) {
this.assertEndpointNameNotExists(endpointName);
this.existingEndpointNames.add(endpointName);
this.channelEndpoints.set(endpointName, {
name: endpointName,
creationParameter,
toServerPacket,
toClientPacket,
serialization,
handler: null
});
return this;
}
addSignalEndpoint(endpointName, { creationParameter, signalData, serialization = "raw" }) {
this.assertEndpointNameNotExists(endpointName);
this.existingEndpointNames.add(endpointName);
this.signalEndpoints.set(endpointName, {
name: endpointName,
creationParameter,
signalData,
serialization,
handler: null
});
return this;
}
addWritableSignalEndpoint(endpointName, { creationParameter, signalData, serialization = "raw" }) {
this.assertEndpointNameNotExists(endpointName);
this.existingEndpointNames.add(endpointName);
this.writableSignalEndpoints.set(endpointName, {
name: endpointName,
creationParameter,
signalData,
serialization,
handler: null
});
return this;
}
/**
* Adds a handler for an Rpc endpoint.
*
* @param endpointName - The name of the endpoint.
* @param handler - The handler function. Will be called when the endpoint is invoked. When
* called, the first parameter is the context, and the second parameter is the "parameter" for the
* RPC call. Can return a value or a promise that resolves to the result.
*/
handleRpcEndpoint(endpointName, handler) {
const endpoint = this.rpcEndpoints.get(endpointName);
if (endpoint === void 0) {
throw new Error(`No Rpc endpoint with name ${endpointName}`);
}
if (endpoint.handler !== null) {
throw new Error(`Rpc endpoint with name ${endpointName} already has a handler`);
}
endpoint.handler = handler;
this.unhandledEndpoints.delete(endpointName);
}
/**
* Adds a handler for a channel endpoint.
*
* @param endpointName - The name of the endpoint.
* @param handler - The handler function. Will be called when the client creates a channel for
* this endpoint. When called, the first parameter is the context, the second parameter is the
* "creationParameter" for the channel, and the third parameter is a channel object that can be
* used to send and receive messages from the client.
*
* Must return a promise. Once that promise is settled, the channel will be closed.
*/
handleChannelEndpoint(endpointName, handler) {
const endpoint = this.channelEndpoints.get(endpointName);
if (endpoint === void 0) {
throw new Error(`No channel endpoint with name ${endpointName}`);
}
if (endpoint.handler !== null) {
throw new Error(`Channel endpoint with name ${endpointName} already has a handler`);
}
endpoint.handler = handler;
this.unhandledEndpoints.delete(endpointName);
}
/**
* Adds a handler for a signal endpoint.
*
* @param endpointName - The name of the endpoint.
* @param handler - The handler function. Will be called when the client creates a signal, and at
* least one subscriber is attached to that signal. When called, the first parameter is the
* context, and the second parameter is the "creationParameter" for the signal. This method should
* return a SignalLike, or a promise that resolves to a SignalLike.
*
* Note: There is no 1-to-1 correlation between the signal on the client side and the number of
* times this handler is called. Every time the number of client subscribers changes from 0 to 1,
* this handler will be called. Every time the number of client subscribers changes from 1 to 0,
* the signal returned from this handler will be unsubscribed.
*
* Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will
* cause memory leaks. That is, either:
*
* - Return a signal that already exists
* - Create and return a LazySignal
*/
handleSignalEndpoint(endpointName, handler) {
const endpoint = this.signalEndpoints.get(endpointName);
if (endpoint === void 0) {
throw new Error(`No signal endpoint with name ${endpointName}`);
}
if (endpoint.handler !== null) {
throw new Error(`Signal endpoint with name ${endpointName} already has a handler`);
}
endpoint.handler = handler;
this.unhandledEndpoints.delete(endpointName);
}
/**
* Adds a handler for a writable signal endpoint.
*
* @param endpointName - The name of the endpoint.
* @param handler - The handler function. Will be called when the client creates a writable
* signal, and at least one subscriber is attached to that signal. When called, the first
* parameter is the context, and the second parameter is the "creationParameter" for the signal.
* This method should return a tuple of the signal and an update function. The update function
* should be called with the new data, patches, and tags to update the signal.
*
* Note: There is no 1-to-1 correlation between the signal on the client side and the number of
* times this handler is called. Every time the number of client subscribers changes from 0 to 1,
* this handler will be called. Every time the number of client subscribers changes from 1 to 0
* the signal returned from this handler will be unsubscribed.
*
* Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will
* cause memory leaks. That is, either:
*
* - Return a signal that already exists
* - Create and return a LazySignal
*/
handleWritableSignalEndpoint(endpointName, handler) {
const endpoint = this.writableSignalEndpoints.get(endpointName);
if (endpoint === void 0) {
throw new Error(`No writable signal endpoint with name ${endpointName}`);
}
if (endpoint.handler !== null) {
throw new Error(`Writable signal endpoint with name ${endpointName} already has a handler`);
}
endpoint.handler = handler;
this.unhandledEndpoints.delete(endpointName);
}
assertAllEndpointsHandled() {
if (this.unhandledEndpoints.size > 0) {
throw new Error(`The following endpoints were not handled: ${Array.from(this.unhandledEndpoints).join(", ")}`);
}
}
getRpcEndpoint(endpointName) {
return this.rpcEndpoints.get(endpointName);
}
getAllRpcEndpoints() {
return [...this.rpcEndpoints.values()];
}
getChannelEndpoint(endpointName) {
return this.channelEndpoints.get(endpointName);
}
getAllChannelEndpoints() {
return [...this.channelEndpoints.values()];
}
getSignalEndpoint(endpointName) {
return this.signalEndpoints.get(endpointName);
}
getAllSignalEndpoints() {
return [...this.signalEndpoints.values()];
}
getWritableSignalEndpoint(endpointName) {
return this.writableSignalEndpoints.get(endpointName);
}
getAllWritableSignalEndpoints() {
return [...this.writableSignalEndpoints.values()];
}
};
(function(ConnectionStatus2) {
ConnectionStatus2["Connected"] = "CONNECTED";
ConnectionStatus2["Errored"] = "ERRORED";
ConnectionStatus2["Closed"] = "CLOSED";
})(ConnectionStatus || (ConnectionStatus = {}));
logger = new SimpleLogger("Channel");
Channel = class _Channel {
constructor(innerSend) {
this.innerSend = innerSend;
this.nextAckId = 0;
this.waitingForAck = /* @__PURE__ */ new Map();
this.receivedACK = (ackId) => {
if (this.connectionStatus.get() !== ConnectionStatus.Connected) {
logger.warn("Received ACK while in status", this.connectionStatus.get());
return;
}
const waiting = this.waitingForAck.get(ackId);
if (waiting === void 0) {
logger.warn("Received ACK for a message that is no longer waiting for ACK, ackId =", ackId);
return;
}
waiting.resolve();
this.waitingForAck.delete(ackId);
};
this.receivedMessage = (packet) => {
if (this.connectionStatus.get() !== ConnectionStatus.Connected) {
logger.warn("Received message while in status", this.connectionStatus.get());
return;
}
this.emitOnMessage(packet);
};
this.errored = (error) => {
if (this.connectionStatus.get() !== ConnectionStatus.Connected) {
logger.warn("Received error while in status", this.connectionStatus.get());
return;
}
this.rejectAllWaitingForAck(error);
this.setConnectionStatus(ConnectionStatus.Errored);
this.emitOnError(error);
};
this.closed = () => {
this.rejectAllWaitingForAck(new Error("Channel closed"));
this.setConnectionStatus(ConnectionStatus.Closed);
this.emitOnClose();
};
[this.onMessage, this.emitOnMessage] = BufferedEvent.create();
[this.onError, this.emitOnError] = BufferedEvent.create();
[this.onClose, this.emitOnClose] = BufferedEvent.create();
[this.connectionStatus, this.setConnectionStatus] = Signal.create(ConnectionStatus.Connected);
}
rejectAllWaitingForAck(error) {
const rejects = Array.from(this.waitingForAck.values()).map(({ reject }) => reject);
this.waitingForAck.clear();
for (const reject of rejects) {
reject(error);
}
}
static create(innerSend) {
const channel = new _Channel(innerSend);
return {
channel,
receivedAck: channel.receivedACK,
receivedMessage: channel.receivedMessage,
errored: channel.errored,
closed: channel.closed
};
}
send(packet) {
this.innerSend(packet);
}
sendAndWaitForACK(packet) {
const { promise, resolve: resolve2, reject } = makePromise();
const ackId = this.nextAckId;
this.nextAckId++;
this.waitingForAck.set(ackId, { resolve: resolve2, reject });
this.innerSend(packet, ackId);
return promise;
}
};
DoubleIndexedKV = /** @class */
(function() {
function DoubleIndexedKV2() {
this.keyToValue = /* @__PURE__ */ new Map();
this.valueToKey = /* @__PURE__ */ new Map();
}
DoubleIndexedKV2.prototype.set = function(key, value) {
this.keyToValue.set(key, value);
this.valueToKey.set(value, key);
};
DoubleIndexedKV2.prototype.getByKey = function(key) {
return this.keyToValue.get(key);
};
DoubleIndexedKV2.prototype.getByValue = function(value) {
return this.valueToKey.get(value);
};
DoubleIndexedKV2.prototype.clear = function() {
this.keyToValue.clear();
this.valueToKey.clear();
};
return DoubleIndexedKV2;
})();
Registry = /** @class */
(function() {
function Registry3(generateIdentifier) {
this.generateIdentifier = generateIdentifier;
this.kv = new DoubleIndexedKV();
}
Registry3.prototype.register = function(value, identifier) {
if (this.kv.getByValue(value)) {
return;
}
if (!identifier) {
identifier = this.generateIdentifier(value);
}
this.kv.set(identifier, value);
};
Registry3.prototype.clear = function() {
this.kv.clear();
};
Registry3.prototype.getIdentifier = function(value) {
return this.kv.getByValue(value);
};
Registry3.prototype.getValue = function(identifier) {
return this.kv.getByKey(identifier);
};
return Registry3;
})();
__extends = globalThis && globalThis.__extends || /* @__PURE__ */ (function() {
var extendStatics = function(d4, b4) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d5, b5) {
d5.__proto__ = b5;
} || function(d5, b5) {
for (var p4 in b5) if (Object.prototype.hasOwnProperty.call(b5, p4)) d5[p4] = b5[p4];
};
return extendStatics(d4, b4);
};
return function(d4, b4) {
if (typeof b4 !== "function" && b4 !== null)
throw new TypeError("Class extends value " + String(b4) + " is not a constructor or null");
extendStatics(d4, b4);
function __() {
this.constructor = d4;
}
d4.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __());
};
})();
ClassRegistry = /** @class */
(function(_super) {
__extends(ClassRegistry2, _super);
function ClassRegistry2() {
var _this = _super.call(this, function(c6) {
return c6.name;
}) || this;
_this.classToAllowedProps = /* @__PURE__ */ new Map();
return _this;
}
ClassRegistry2.prototype.register = function(value, options) {
if (typeof options === "object") {
if (options.allowProps) {
this.classToAllowedProps.set(value, options.allowProps);
}
_super.prototype.register.call(this, value, options.identifier);
} else {
_super.prototype.register.call(this, value, options);
}
};
ClassRegistry2.prototype.getAllowedProps = function(value) {
return this.classToAllowedProps.get(value);
};
return ClassRegistry2;
})(Registry);
__read$3 = globalThis && globalThis.__read || function(o9, n7) {
var m4 = typeof Symbol === "function" && o9[Symbol.iterator];
if (!m4) return o9;
var i7 = m4.call(o9), r8, ar = [], e9;
try {
while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value);
} catch (error) {
e9 = { error };
} finally {
try {
if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7);
} finally {
if (e9) throw e9.error;
}
}
return ar;
};
CustomTransformerRegistry = /** @class */
(function() {
function CustomTransformerRegistry2() {
this.transfomers = {};
}
CustomTransformerRegistry2.prototype.register = function(transformer) {
this.transfomers[transformer.name] = transformer;
};
CustomTransformerRegistry2.prototype.findApplicable = function(v4) {
return find(this.transfomers, function(transformer) {
return transformer.isApplicable(v4);
});
};
CustomTransformerRegistry2.prototype.findByName = function(name) {
return this.transfomers[name];
};
return CustomTransformerRegistry2;
})();
getType$1 = function(payload) {
return Object.prototype.toString.call(payload).slice(8, -1);
};
isUndefined = function(payload) {
return typeof payload === "undefined";
};
isNull = function(payload) {
return payload === null;
};
isPlainObject$1 = function(payload) {
if (typeof payload !== "object" || payload === null)
return false;
if (payload === Object.prototype)
return false;
if (Object.getPrototypeOf(payload) === null)
return true;
return Object.getPrototypeOf(payload) === Object.prototype;
};
isEmptyObject = function(payload) {
return isPlainObject$1(payload) && Object.keys(payload).length === 0;
};
isArray$1 = function(payload) {
return Array.isArray(payload);
};
isString = function(payload) {
return typeof payload === "string";
};
isNumber = function(payload) {
return typeof payload === "number" && !isNaN(payload);
};
isBoolean = function(payload) {
return typeof payload === "boolean";
};
isRegExp = function(payload) {
return payload instanceof RegExp;
};
isMap = function(payload) {
return payload instanceof Map;
};
isSet = function(payload) {
return payload instanceof Set;
};
isSymbol = function(payload) {
return getType$1(payload) === "Symbol";
};
isDate = function(payload) {
return payload instanceof Date && !isNaN(payload.valueOf());
};
isError = function(payload) {
return payload instanceof Error;
};
isNaNValue = function(payload) {
return typeof payload === "number" && isNaN(payload);
};
isPrimitive = function(payload) {
return isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
};
isBigint = function(payload) {
return typeof payload === "bigint";
};
isInfinite = function(payload) {
return payload === Infinity || payload === -Infinity;
};
isTypedArray = function(payload) {
return ArrayBuffer.isView(payload) && !(payload instanceof DataView);
};
isURL = function(payload) {
return payload instanceof URL;
};
escapeKey = function(key) {
return key.replace(/\./g, "\\.");
};
stringifyPath = function(path6) {
return path6.map(String).map(escapeKey).join(".");
};
parsePath = function(string) {
var result = [];
var segment = "";
for (var i7 = 0; i7 < string.length; i7++) {
var char = string.charAt(i7);
var isEscapedDot = char === "\\" && string.charAt(i7 + 1) === ".";
if (isEscapedDot) {
segment += ".";
i7++;
continue;
}
var isEndOfSegment = char === ".";
if (isEndOfSegment) {
result.push(segment);
segment = "";
continue;
}
segment += char;
}
var lastSegment = segment;
result.push(lastSegment);
return result;
};
__assign$1 = globalThis && globalThis.__assign || function() {
__assign$1 = Object.assign || function(t6) {
for (var s6, i7 = 1, n7 = arguments.length; i7 < n7; i7++) {
s6 = arguments[i7];
for (var p4 in s6) if (Object.prototype.hasOwnProperty.call(s6, p4))
t6[p4] = s6[p4];
}
return t6;
};
return __assign$1.apply(this, arguments);
};
__read$2 = globalThis && globalThis.__read || function(o9, n7) {
var m4 = typeof Symbol === "function" && o9[Symbol.iterator];
if (!m4) return o9;
var i7 = m4.call(o9), r8, ar = [], e9;
try {
while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value);
} catch (error) {
e9 = { error };
} finally {
try {
if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7);
} finally {
if (e9) throw e9.error;
}
}
return ar;
};
__spreadArray$2 = globalThis && globalThis.__spreadArray || function(to2, from2) {
for (var i7 = 0, il = from2.length, j3 = to2.length; i7 < il; i7++, j3++)
to2[j3] = from2[i7];
return to2;
};
simpleRules = [
simpleTransformation(isUndefined, "undefined", function() {
return null;
}, function() {
return void 0;
}),
simpleTransformation(isBigint, "bigint", function(v4) {
return v4.toString();
}, function(v4) {
if (typeof BigInt !== "undefined") {
return BigInt(v4);
}
console.error("Please add a BigInt polyfill.");
return v4;
}),
simpleTransformation(isDate, "Date", function(v4) {
return v4.toISOString();
}, function(v4) {
return new Date(v4);
}),
simpleTransformation(isError, "Error", function(v4, superJson) {
var baseError = {
name: v4.name,
message: v4.message
};
superJson.allowedErrorProps.forEach(function(prop) {
baseError[prop] = v4[prop];
});
return baseError;
}, function(v4, superJson) {
var e9 = new Error(v4.message);
e9.name = v4.name;
e9.stack = v4.stack;
superJson.allowedErrorProps.forEach(function(prop) {
e9[prop] = v4[prop];
});
return e9;
}),
simpleTransformation(isRegExp, "regexp", function(v4) {
return "" + v4;
}, function(regex) {
var body = regex.slice(1, regex.lastIndexOf("/"));
var flags = regex.slice(regex.lastIndexOf("/") + 1);
return new RegExp(body, flags);
}),
simpleTransformation(
isSet,
"set",
// (sets only exist in es6+)
// eslint-disable-next-line es5/no-es6-methods
function(v4) {
return __spreadArray$2([], __read$2(v4.values()));
},
function(v4) {
return new Set(v4);
}
),
simpleTransformation(isMap, "map", function(v4) {
return __spreadArray$2([], __read$2(v4.entries()));
}, function(v4) {
return new Map(v4);
}),
simpleTransformation(function(v4) {
return isNaNValue(v4) || isInfinite(v4);
}, "number", function(v4) {
if (isNaNValue(v4)) {
return "NaN";
}
if (v4 > 0) {
return "Infinity";
} else {
return "-Infinity";
}
}, Number),
simpleTransformation(function(v4) {
return v4 === 0 && 1 / v4 === -Infinity;
}, "number", function() {
return "-0";
}, Number),
simpleTransformation(isURL, "URL", function(v4) {
return v4.toString();
}, function(v4) {
return new URL(v4);
})
];
symbolRule = compositeTransformation(function(s6, superJson) {
if (isSymbol(s6)) {
var isRegistered = !!superJson.symbolRegistry.getIdentifier(s6);
return isRegistered;
}
return false;
}, function(s6, superJson) {
var identifier = superJson.symbolRegistry.getIdentifier(s6);
return ["symbol", identifier];
}, function(v4) {
return v4.description;
}, function(_3, a3, superJson) {
var value = superJson.symbolRegistry.getValue(a3[1]);
if (!value) {
throw new Error("Trying to deserialize unknown symbol");
}
return value;
});
constructorToName = [
Int8Array,
Uint8Array,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array,
Uint8ClampedArray
].reduce(function(obj, ctor) {
obj[ctor.name] = ctor;
return obj;
}, {});
typedArrayRule = compositeTransformation(isTypedArray, function(v4) {
return ["typed-array", v4.constructor.name];
}, function(v4) {
return __spreadArray$2([], __read$2(v4));
}, function(v4, a3) {
var ctor = constructorToName[a3[1]];
if (!ctor) {
throw new Error("Trying to deserialize unknown typed array");
}
return new ctor(v4);
});
classRule = compositeTransformation(isInstanceOfRegisteredClass, function(clazz, superJson) {
var identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
return ["class", identifier];
}, function(clazz, superJson) {
var allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
if (!allowedProps) {
return __assign$1({}, clazz);
}
var result = {};
allowedProps.forEach(function(prop) {
result[prop] = clazz[prop];
});
return result;
}, function(v4, a3, superJson) {
var clazz = superJson.classRegistry.getValue(a3[1]);
if (!clazz) {
throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");
}
return Object.assign(Object.create(clazz.prototype), v4);
});
customRule = compositeTransformation(function(value, superJson) {
return !!superJson.customTransformerRegistry.findApplicable(value);
}, function(value, superJson) {
var transformer = superJson.customTransformerRegistry.findApplicable(value);
return ["custom", transformer.name];
}, function(value, superJson) {
var transformer = superJson.customTransformerRegistry.findApplicable(value);
return transformer.serialize(value);
}, function(v4, a3, superJson) {
var transformer = superJson.customTransformerRegistry.findByName(a3[1]);
if (!transformer) {
throw new Error("Trying to deserialize unknown custom value");
}
return transformer.deserialize(v4);
});
compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
transformValue = function(value, superJson) {
var applicableCompositeRule = findArr(compositeRules, function(rule) {
return rule.isApplicable(value, superJson);
});
if (applicableCompositeRule) {
return {
value: applicableCompositeRule.transform(value, superJson),
type: applicableCompositeRule.annotation(value, superJson)
};
}
var applicableSimpleRule = findArr(simpleRules, function(rule) {
return rule.isApplicable(value, superJson);
});
if (applicableSimpleRule) {
return {
value: applicableSimpleRule.transform(value, superJson),
type: applicableSimpleRule.annotation
};
}
return void 0;
};
simpleRulesByAnnotation = {};
simpleRules.forEach(function(rule) {
simpleRulesByAnnotation[rule.annotation] = rule;
});
untransformValue = function(json2, type, superJson) {
if (isArray$1(type)) {
switch (type[0]) {
case "symbol":
return symbolRule.untransform(json2, type, superJson);
case "class":
return classRule.untransform(json2, type, superJson);
case "custom":
return customRule.untransform(json2, type, superJson);
case "typed-array":
return typedArrayRule.untransform(json2, type, superJson);
default:
throw new Error("Unknown transformation: " + type);
}
} else {
var transformation = simpleRulesByAnnotation[type];
if (!transformation) {
throw new Error("Unknown transformation: " + type);
}
return transformation.untransform(json2, superJson);
}
};
getNthKey = function(value, n7) {
var keys2 = value.keys();
while (n7 > 0) {
keys2.next();
n7--;
}
return keys2.next().value;
};
getDeep = function(object, path6) {
validatePath(path6);
for (var i7 = 0; i7 < path6.length; i7++) {
var key = path6[i7];
if (isSet(object)) {
object = getNthKey(object, +key);
} else if (isMap(object)) {
var row = +key;
var type = +path6[++i7] === 0 ? "key" : "value";
var keyOfRow = getNthKey(object, row);
switch (type) {
case "key":
object = keyOfRow;
break;
case "value":
object = object.get(keyOfRow);
break;
}
} else {
object = object[key];
}
}
return object;
};
setDeep = function(object, path6, mapper) {
validatePath(path6);
if (path6.length === 0) {
return mapper(object);
}
var parent = object;
for (var i7 = 0; i7 < path6.length - 1; i7++) {
var key = path6[i7];
if (isArray$1(parent)) {
var index2 = +key;
parent = parent[index2];
} else if (isPlainObject$1(parent)) {
parent = parent[key];
} else if (isSet(parent)) {
var row = +key;
parent = getNthKey(parent, row);
} else if (isMap(parent)) {
var isEnd = i7 === path6.length - 2;
if (isEnd) {
break;
}
var row = +key;
var type = +path6[++i7] === 0 ? "key" : "value";
var keyOfRow = getNthKey(parent, row);
switch (type) {
case "key":
parent = keyOfRow;
break;
case "value":
parent = parent.get(keyOfRow);
break;
}
}
}
var lastKey = path6[path6.length - 1];
if (isArray$1(parent)) {
parent[+lastKey] = mapper(parent[+lastKey]);
} else if (isPlainObject$1(parent)) {
parent[lastKey] = mapper(parent[lastKey]);
}
if (isSet(parent)) {
var oldValue = getNthKey(parent, +lastKey);
var newValue = mapper(oldValue);
if (oldValue !== newValue) {
parent["delete"](oldValue);
parent.add(newValue);
}
}
if (isMap(parent)) {
var row = +path6[path6.length - 2];
var keyToRow = getNthKey(parent, row);
var type = +lastKey === 0 ? "key" : "value";
switch (type) {
case "key": {
var newKey = mapper(keyToRow);
parent.set(newKey, parent.get(keyToRow));
if (newKey !== keyToRow) {
parent["delete"](keyToRow);
}
break;
}
case "value": {
parent.set(keyToRow, mapper(parent.get(keyToRow)));
break;
}
}
}
return object;
};
__read$1 = globalThis && globalThis.__read || function(o9, n7) {
var m4 = typeof Symbol === "function" && o9[Symbol.iterator];
if (!m4) return o9;
var i7 = m4.call(o9), r8, ar = [], e9;
try {
while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value);
} catch (error) {
e9 = { error };
} finally {
try {
if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7);
} finally {
if (e9) throw e9.error;
}
}
return ar;
};
__spreadArray$1 = globalThis && globalThis.__spreadArray || function(to2, from2) {
for (var i7 = 0, il = from2.length, j3 = to2.length; i7 < il; i7++, j3++)
to2[j3] = from2[i7];
return to2;
};
isDeep = function(object, superJson) {
return isPlainObject$1(object) || isArray$1(object) || isMap(object) || isSet(object) || isInstanceOfRegisteredClass(object, superJson);
};
walker = function(object, identities, superJson, dedupe, path6, objectsInThisPath, seenObjects) {
var _a7;
if (path6 === void 0) {
path6 = [];
}
if (objectsInThisPath === void 0) {
objectsInThisPath = [];
}
if (seenObjects === void 0) {
seenObjects = /* @__PURE__ */ new Map();
}
var primitive = isPrimitive(object);
if (!primitive) {
addIdentity(object, path6, identities);
var seen = seenObjects.get(object);
if (seen) {
return dedupe ? {
transformedValue: null
} : seen;
}
}
if (!isDeep(object, superJson)) {
var transformed_1 = transformValue(object, superJson);
var result_1 = transformed_1 ? {
transformedValue: transformed_1.value,
annotations: [transformed_1.type]
} : {
transformedValue: object
};
if (!primitive) {
seenObjects.set(object, result_1);
}
return result_1;
}
if (includes(objectsInThisPath, object)) {
return {
transformedValue: null
};
}
var transformationResult = transformValue(object, superJson);
var transformed = (_a7 = transformationResult === null || transformationResult === void 0 ? void 0 : transformationResult.value) !== null && _a7 !== void 0 ? _a7 : object;
var transformedValue = isArray$1(transformed) ? [] : {};
var innerAnnotations = {};
forEach(transformed, function(value, index2) {
var recursiveResult = walker(value, identities, superJson, dedupe, __spreadArray$1(__spreadArray$1([], __read$1(path6)), [index2]), __spreadArray$1(__spreadArray$1([], __read$1(objectsInThisPath)), [object]), seenObjects);
transformedValue[index2] = recursiveResult.transformedValue;
if (isArray$1(recursiveResult.annotations)) {
innerAnnotations[index2] = recursiveResult.annotations;
} else if (isPlainObject$1(recursiveResult.annotations)) {
forEach(recursiveResult.annotations, function(tree, key) {
innerAnnotations[escapeKey(index2) + "." + key] = tree;
});
}
});
var result = isEmptyObject(innerAnnotations) ? {
transformedValue,
annotations: !!transformationResult ? [transformationResult.type] : void 0
} : {
transformedValue,
annotations: !!transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
};
if (!primitive) {
seenObjects.set(object, result);
}
return result;
};
__assign = globalThis && globalThis.__assign || function() {
__assign = Object.assign || function(t6) {
for (var s6, i7 = 1, n7 = arguments.length; i7 < n7; i7++) {
s6 = arguments[i7];
for (var p4 in s6) if (Object.prototype.hasOwnProperty.call(s6, p4))
t6[p4] = s6[p4];
}
return t6;
};
return __assign.apply(this, arguments);
};
__read = globalThis && globalThis.__read || function(o9, n7) {
var m4 = typeof Symbol === "function" && o9[Symbol.iterator];
if (!m4) return o9;
var i7 = m4.call(o9), r8, ar = [], e9;
try {
while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value);
} catch (error) {
e9 = { error };
} finally {
try {
if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7);
} finally {
if (e9) throw e9.error;
}
}
return ar;
};
__spreadArray = globalThis && globalThis.__spreadArray || function(to2, from2) {
for (var i7 = 0, il = from2.length, j3 = to2.length; i7 < il; i7++, j3++)
to2[j3] = from2[i7];
return to2;
};
SuperJSON = /** @class */
(function() {
function SuperJSON2(_a7) {
var _b = _a7 === void 0 ? {} : _a7, _c = _b.dedupe, dedupe = _c === void 0 ? false : _c;
this.classRegistry = new ClassRegistry();
this.symbolRegistry = new Registry(function(s6) {
var _a8;
return (_a8 = s6.description) !== null && _a8 !== void 0 ? _a8 : "";
});
this.customTransformerRegistry = new CustomTransformerRegistry();
this.allowedErrorProps = [];
this.dedupe = dedupe;
}
SuperJSON2.prototype.serialize = function(object) {
var identities = /* @__PURE__ */ new Map();
var output = walker(object, identities, this, this.dedupe);
var res = {
json: output.transformedValue
};
if (output.annotations) {
res.meta = __assign(__assign({}, res.meta), { values: output.annotations });
}
var equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
if (equalityAnnotations) {
res.meta = __assign(__assign({}, res.meta), { referentialEqualities: equalityAnnotations });
}
return res;
};
SuperJSON2.prototype.deserialize = function(payload) {
var json2 = payload.json, meta = payload.meta;
var result = copy(json2);
if (meta === null || meta === void 0 ? void 0 : meta.values) {
result = applyValueAnnotations(result, meta.values, this);
}
if (meta === null || meta === void 0 ? void 0 : meta.referentialEqualities) {
result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities);
}
return result;
};
SuperJSON2.prototype.stringify = function(object) {
return JSON.stringify(this.serialize(object));
};
SuperJSON2.prototype.parse = function(string) {
return this.deserialize(JSON.parse(string));
};
SuperJSON2.prototype.registerClass = function(v4, options) {
this.classRegistry.register(v4, options);
};
SuperJSON2.prototype.registerSymbol = function(v4, identifier) {
this.symbolRegistry.register(v4, identifier);
};
SuperJSON2.prototype.registerCustom = function(transformer, name) {
this.customTransformerRegistry.register(__assign({ name }, transformer));
};
SuperJSON2.prototype.allowErrorProps = function() {
var _a7;
var props = [];
for (var _i = 0; _i < arguments.length; _i++) {
props[_i] = arguments[_i];
}
(_a7 = this.allowedErrorProps).push.apply(_a7, __spreadArray([], __read(props)));
};
SuperJSON2.defaultInstance = new SuperJSON2();
SuperJSON2.serialize = SuperJSON2.defaultInstance.serialize.bind(SuperJSON2.defaultInstance);
SuperJSON2.deserialize = SuperJSON2.defaultInstance.deserialize.bind(SuperJSON2.defaultInstance);
SuperJSON2.stringify = SuperJSON2.defaultInstance.stringify.bind(SuperJSON2.defaultInstance);
SuperJSON2.parse = SuperJSON2.defaultInstance.parse.bind(SuperJSON2.defaultInstance);
SuperJSON2.registerClass = SuperJSON2.defaultInstance.registerClass.bind(SuperJSON2.defaultInstance);
SuperJSON2.registerSymbol = SuperJSON2.defaultInstance.registerSymbol.bind(SuperJSON2.defaultInstance);
SuperJSON2.registerCustom = SuperJSON2.defaultInstance.registerCustom.bind(SuperJSON2.defaultInstance);
SuperJSON2.allowErrorProps = SuperJSON2.defaultInstance.allowErrorProps.bind(SuperJSON2.defaultInstance);
return SuperJSON2;
})();
serialize$1 = SuperJSON.serialize;
deserialize$1 = SuperJSON.deserialize;
serializedOpaqueSchema = external_exports.any();
clientToServerMessageSchema = external_exports.discriminatedUnion("type", [
// Communication
external_exports.object({
type: external_exports.literal("communicationWarning"),
warning: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("keepAlive")
}),
// Channel
external_exports.object({
type: external_exports.literal("channelCreate"),
endpoint: external_exports.string(),
channelId: external_exports.number().int(),
creationParameter: serializedOpaqueSchema
}),
external_exports.object({
type: external_exports.literal("channelSend"),
channelId: external_exports.number().int(),
message: serializedOpaqueSchema,
ackId: external_exports.number().int().optional()
}),
external_exports.object({
type: external_exports.literal("channelAck"),
channelId: external_exports.number().int(),
ackId: external_exports.number().int()
}),
// RPC
external_exports.object({
type: external_exports.literal("rpcCall"),
endpoint: external_exports.string(),
callId: external_exports.number().int(),
parameter: serializedOpaqueSchema
}),
// Readonly signal
external_exports.object({
type: external_exports.literal("signalSubscribe"),
creationParameter: serializedOpaqueSchema,
endpoint: external_exports.string(),
subscribeId: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("signalUnsubscribe"),
subscribeId: external_exports.number().int()
}),
// Writable signal
external_exports.object({
type: external_exports.literal("writableSignalSubscribe"),
creationParameter: serializedOpaqueSchema,
endpoint: external_exports.string(),
subscribeId: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("writableSignalUnsubscribe"),
subscribeId: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("writableSignalUpdate"),
subscribeId: external_exports.number().int(),
patches: external_exports.array(serializedOpaqueSchema),
tags: external_exports.array(external_exports.string())
})
]);
serverToClientMessageSchema = external_exports.discriminatedUnion("type", [
// Communication
external_exports.object({
type: external_exports.literal("communicationWarning"),
warning: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("keepAliveAck")
}),
// Channel
external_exports.object({
type: external_exports.literal("channelSend"),
channelId: external_exports.number().int(),
message: serializedOpaqueSchema,
ackId: external_exports.number().int().optional()
}),
external_exports.object({
type: external_exports.literal("channelAck"),
channelId: external_exports.number().int(),
ackId: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("channelClose"),
channelId: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("channelError"),
channelId: external_exports.number().int(),
error: serializedLMSExtendedErrorSchema
}),
// RPC
external_exports.object({
type: external_exports.literal("rpcResult"),
callId: external_exports.number().int(),
result: serializedOpaqueSchema
}),
external_exports.object({
type: external_exports.literal("rpcError"),
callId: external_exports.number().int(),
error: serializedLMSExtendedErrorSchema
}),
// Readonly signal
external_exports.object({
type: external_exports.literal("signalUpdate"),
subscribeId: external_exports.number().int(),
patches: external_exports.array(serializedOpaqueSchema),
tags: external_exports.array(external_exports.string())
}),
external_exports.object({
type: external_exports.literal("signalError"),
subscribeId: external_exports.number().int(),
error: serializedLMSExtendedErrorSchema
}),
// Writable signal
external_exports.object({
type: external_exports.literal("writableSignalUpdate"),
subscribeId: external_exports.number().int(),
patches: external_exports.array(serializedOpaqueSchema),
tags: external_exports.array(external_exports.string())
}),
external_exports.object({
type: external_exports.literal("writableSignalError"),
subscribeId: external_exports.number().int(),
error: serializedLMSExtendedErrorSchema
})
]);
Transport = class {
constructor() {
this.disposed = false;
}
async [Symbol.asyncDispose]() {
if (this.disposed) {
throw new Error("Cannot dispose twice");
}
this.disposed = true;
}
};
ClientTransport = class extends Transport {
parseIncomingMessage(message) {
return serverToClientMessageSchema.parse(message);
}
send(message) {
const result = clientToServerMessageSchema.parse(message);
this.sendViaTransport(result);
}
/**
* Called by the client port when the number of open communications changes from 0 to 1. This
* usually indicates the `socket.ref()` should be called to prevent the process from exiting.
*/
onHavingOneOrMoreOpenCommunication() {
}
// The following snippet is intentionally not a tsdoc (only 1 star as oppose to 2). There is
// likely a bug in TypeScript that when we change it to tsdoc, on darwin and linux, it causes the
// generated .d.ts file to be invalid. We have considered reporting this to TypeScript, but it is
// way too difficult to narrow down, thus we just hope this is the only case that this error
// occurs.
/*
* Called by the client port when the number of open communications changes from 1 or more to 0.
* This usually indicates the `socket.unref()` should be called to allow the process to exit.
*/
onHavingNoOpenCommunication() {
}
};
wsAuthenticationResultSchema = external_exports.discriminatedUnion("success", [
external_exports.object({
success: external_exports.literal(true)
}),
external_exports.object({
success: external_exports.literal(false),
error: external_exports.string()
})
]);
(function(WsClientTransportStatus2) {
WsClientTransportStatus2["Disconnected"] = "DISCONNECTED";
WsClientTransportStatus2["Connecting"] = "CONNECTING";
WsClientTransportStatus2["Connected"] = "CONNECTED";
})(WsClientTransportStatus || (WsClientTransportStatus = {}));
WsClientTransport = class _WsClientTransport extends ClientTransport {
constructor(url, receivedMessage, errored, { abortSignal, parentLogger } = {}) {
super();
this.url = url;
this.receivedMessage = receivedMessage;
this.errored = errored;
this.ws = null;
this.queuedMessages = [];
this.status = WsClientTransportStatus.Disconnected;
this.resolvedUrl = null;
this.shouldRef = false;
this.resolveDisposed = null;
this.abortSignal = abortSignal;
this.logger = new SimpleLogger("WsClientTransport", parentLogger);
}
static createWsClientTransportFactory(url, { abortSignal } = {}) {
return (receivedMessage, errored, parentLogger) => new _WsClientTransport(url, receivedMessage, errored, {
abortSignal,
parentLogger
});
}
connect() {
if (this.status !== WsClientTransportStatus.Disconnected) {
this.logger.warn("connect() called while not disconnected");
return;
}
if (this.disposed) {
throw new Error(text`
Cannot establish WebSocket connection because the transport has been disposed.
`);
}
if (this.abortSignal !== void 0 && this.abortSignal.aborted) {
throw new Error(this.abortSignal.reason);
}
this.status = WsClientTransportStatus.Connecting;
Promise.resolve(this.url).then((url) => {
this.resolvedUrl = url;
this.ws = new import_lms_isomorphic.WebSocket(url);
this.ws.addEventListener("open", this.onWsOpen.bind(this));
this.ws.addEventListener("error", (event) => this.onWsError(event.error));
this.ws.addEventListener("close", () => {
this.onWsError(new Error("WebSocket connection closed"));
});
const abortSignal = this.abortSignal;
if (abortSignal !== void 0) {
if (abortSignal.aborted) {
this.onWsError(abortSignal.reason);
} else {
const abortListener = () => {
this.onWsError(abortSignal.reason);
};
abortSignal.addEventListener("abort", abortListener, { once: true });
this.ws.addEventListener("close", () => {
abortSignal.removeEventListener("abort", abortListener);
});
}
}
});
}
onWsOpen() {
this.ws.addEventListener("message", this.onWsMessage.bind(this));
this.status = WsClientTransportStatus.Connected;
this.queuedMessages.forEach((message) => this.sendViaTransport(message));
this.queuedMessages = [];
this.updateShouldRef(this.shouldRef);
}
onWsMessage(event) {
if (this.status !== WsClientTransportStatus.Connected) {
this.logger.warn("Received message while not connected. Message ignored:", event.data);
return;
}
let message;
try {
message = JSON.parse(String(event.data));
} catch (error) {
this.logger.warn("Received invalid JSON message from server:", event.data);
return;
}
let parsed;
try {
parsed = this.parseIncomingMessage(message);
} catch (error) {
this.logger.warn("Received invalid message from server:", message);
return;
}
this.receivedMessage(parsed);
}
onWsError(error) {
if (this.status === WsClientTransportStatus.Disconnected) {
return;
}
this.logger.warn("WebSocket error:", error);
if (error.code === "ECONNREFUSED") {
this.logger.warnText`
WebSocket connection refused. This can happen if the server is not running or the client
is trying to connect to the wrong path. The server path that this client is
attempting to connect to is:
${this.resolvedUrl ?? "Unknown"}.
Please make sure the following:
1. LM Studio is running
2. The API server in LM Studio has started
3. The client is attempting to connect to the correct path
`;
}
try {
this.ws?.close();
} catch (error2) {
}
this.status = WsClientTransportStatus.Disconnected;
this.errored(error);
}
onWsTimeout() {
if (this.status === WsClientTransportStatus.Disconnected) {
return;
}
this.logger.warn("Websocket timed out");
try {
this.ws?.close();
} catch (error) {
}
this.status = WsClientTransportStatus.Disconnected;
this.errored(new Error("WebSocket timed out"));
}
onHavingNoOpenCommunication() {
this.updateShouldRef(false);
if (this.disposed && this.resolveDisposed !== null) {
this.resolveDisposed();
this.resolveDisposed = null;
}
}
onHavingOneOrMoreOpenCommunication() {
this.updateShouldRef(true);
}
updateShouldRef(shouldRef) {
this.shouldRef = shouldRef;
if (this.ws === null) {
return;
}
if (!this.ws._socket) {
return;
}
if (shouldRef) {
this.ws._socket.ref();
} else {
this.ws._socket.unref();
}
}
sendViaTransport(message) {
if (this.status === WsClientTransportStatus.Connected) {
this.ws.send(JSON.stringify(message));
} else {
this.queuedMessages.push(message);
if (this.status === WsClientTransportStatus.Disconnected) {
this.connect();
}
}
}
async [Symbol.asyncDispose]() {
await super[Symbol.asyncDispose]();
if (this.shouldRef) {
const { promise: disposedPromise, resolve: resolveDisposed } = makePromise();
this.resolveDisposed = resolveDisposed;
await disposedPromise;
}
if (this.ws !== null) {
try {
this.ws.close();
} catch (error) {
}
this.ws = null;
}
this.errored(new Error("WebSocket client transport disposed"));
this.status = WsClientTransportStatus.Disconnected;
}
};
AuthenticatedWsClientTransport = class _AuthenticatedWsClientTransport extends WsClientTransport {
constructor(url, clientIdentifier, clientPasskey, receivedMessage, errored, { parentLogger, abortSignal } = {}) {
super(url, receivedMessage, errored, { parentLogger, abortSignal });
this.clientIdentifier = clientIdentifier;
this.clientPasskey = clientPasskey;
this.logger = this.logger.subclass("AuthenticatedWsClientTransport");
}
static createAuthenticatedWsClientTransportFactory({ url, clientIdentifier, clientPasskey, abortSignal }) {
return (receivedMessage, errored, parentLogger) => new _AuthenticatedWsClientTransport(url, clientIdentifier, clientPasskey, receivedMessage, errored, { parentLogger, abortSignal });
}
onWsOpen() {
this.ws.send(JSON.stringify({
authVersion: 1,
clientIdentifier: this.clientIdentifier,
clientPasskey: this.clientPasskey
}));
this.ws.addEventListener("message", (event) => {
try {
const data = JSON.parse(event.data.toString("utf-8"));
const result = wsAuthenticationResultSchema.parse(data);
if (result.success) {
super.onWsOpen();
} else {
this.onWsError(new Error("Failed to authenticate: " + result.error));
}
} catch (error) {
this.onWsError(new Error("Failed to parse authentication result: " + error?.message));
}
}, {
once: true
});
}
};
ClientPort = class {
constructor(backendInterface, factory, { parentLogger, errorDeserializer, verboseErrorMessage } = {}) {
this.backendInterface = backendInterface;
this.openChannels = /* @__PURE__ */ new Map();
this.ongoingRpcs = /* @__PURE__ */ new Map();
this.openSignalSubscriptions = /* @__PURE__ */ new Map();
this.openWritableSignalSubscriptions = /* @__PURE__ */ new Map();
this.openCommunicationsCount = 0;
this.nextChannelId = 0;
this.nextSubscribeId = 0;
this.nextWritableSubscribeId = 0;
this.producedCommunicationWarningsCount = 0;
this.receivedMessage = (message) => {
switch (message.type) {
case "channelSend": {
this.receivedChannelSend(message);
break;
}
case "channelAck": {
this.receivedChannelAck(message);
break;
}
case "channelClose": {
this.receivedChannelClose(message);
break;
}
case "channelError": {
this.receivedChannelError(message);
break;
}
case "rpcResult": {
this.receivedRpcResult(message);
break;
}
case "rpcError": {
this.receivedRpcError(message);
break;
}
case "signalUpdate": {
this.receivedSignalUpdate(message);
break;
}
case "signalError": {
this.receivedSignalError(message);
break;
}
case "writableSignalUpdate": {
this.receivedWritableSignalUpdate(message);
break;
}
case "writableSignalError": {
this.receivedWritableSignalError(message);
break;
}
case "communicationWarning": {
this.receivedCommunicationWarning(message);
break;
}
case "keepAliveAck": {
this.receivedKeepAliveAck(message);
break;
}
}
};
this.errored = (error) => {
for (const openChannel of this.openChannels.values()) {
openChannel.errored(error);
}
this.openChannels.clear();
for (const ongoingRpc of this.ongoingRpcs.values()) {
ongoingRpc.reject(error);
}
this.ongoingRpcs.clear();
for (const openSignalSubscription of this.openSignalSubscriptions.values()) {
openSignalSubscription.errored(error);
}
this.openSignalSubscriptions.clear();
for (const openWritableSignalSubscription of this.openWritableSignalSubscriptions.values()) {
openWritableSignalSubscription.errored(error);
}
this.openWritableSignalSubscriptions.clear();
this.updateOpenCommunicationsCount();
};
this.logger = new SimpleLogger("ClientPort", parentLogger);
this.errorDeserializer = errorDeserializer ?? defaultErrorDeserializer;
this.verboseErrorMessage = verboseErrorMessage ?? true;
this.transport = factory(this.receivedMessage, this.errored, this.logger);
}
communicationWarning(warning) {
if (this.producedCommunicationWarningsCount >= 5) {
return;
}
this.logger.warnText`
Produced communication warning: ${warning}
This is usually caused by communication protocol incompatibility. Please make sure you are
using the up-to-date versions of the SDK and LM Studio.
`;
this.transport.send({
type: "communicationWarning",
warning
});
this.producedCommunicationWarningsCount++;
if (this.producedCommunicationWarningsCount >= 5) {
this.logger.errorText`
5 communication warnings have been produced. Further warnings will not be printed.
`;
}
}
updateOpenCommunicationsCount() {
const previousCount = this.openCommunicationsCount;
this.openCommunicationsCount = this.openChannels.size + this.ongoingRpcs.size + this.openSignalSubscriptions.size + this.openWritableSignalSubscriptions.size;
if (this.openCommunicationsCount === 0 && previousCount > 0) {
this.transport.onHavingNoOpenCommunication();
} else if (this.openCommunicationsCount === 1 && previousCount === 0) {
this.transport.onHavingOneOrMoreOpenCommunication();
}
}
receivedChannelSend(message) {
const openChannel = this.openChannels.get(message.channelId);
if (openChannel === void 0) {
this.communicationWarning(`Received channelSend for unknown channel, channelId = ${message.channelId}`);
return;
}
const deserializedMessage = deserialize(openChannel.endpoint.serialization, message.message);
const parsed = openChannel.endpoint.toClientPacket.safeParse(deserializedMessage);
if (!parsed.success) {
this.communicationWarning(text`
Received invalid message for channel: endpointName = ${openChannel.endpoint.name}, message =
${deserializedMessage}. Zod error:
${Validator.prettyPrintZod("message", parsed.error)}
`);
return;
}
openChannel.receivedMessage(parsed.data);
}
receivedChannelAck(message) {
const openChannel = this.openChannels.get(message.channelId);
if (openChannel === void 0) {
this.communicationWarning(`Received channelAck for unknown channel, channelId = ${message.channelId}`);
return;
}
openChannel.receivedAck(message.ackId);
}
receivedChannelClose(message) {
const openChannel = this.openChannels.get(message.channelId);
if (openChannel === void 0) {
this.communicationWarning(`Received channelClose for unknown channel, channelId = ${message.channelId}`);
return;
}
this.openChannels.delete(message.channelId);
openChannel.closed();
this.updateOpenCommunicationsCount();
}
receivedChannelError(message) {
const openChannel = this.openChannels.get(message.channelId);
if (openChannel === void 0) {
this.communicationWarning(`Received channelError for unknown channel, channelId = ${message.channelId}`);
return;
}
this.openChannels.delete(message.channelId);
const error = this.errorDeserializer(message.error, "Channel Error", this.verboseErrorMessage ? openChannel.stack : void 0);
openChannel.errored(error);
this.updateOpenCommunicationsCount();
}
receivedRpcResult(message) {
const ongoingRpc = this.ongoingRpcs.get(message.callId);
if (ongoingRpc === void 0) {
this.communicationWarning(`Received rpcResult for unknown rpc, callId = ${message.callId}`);
return;
}
const deserializedResult = deserialize(ongoingRpc.endpoint.serialization, message.result);
const parsed = ongoingRpc.endpoint.returns.safeParse(deserializedResult);
if (!parsed.success) {
this.communicationWarning(text`
Received invalid result for rpc, endpointName = ${ongoingRpc.endpoint.name}, result =
${deserializedResult}. Zod error:
${Validator.prettyPrintZod("result", parsed.error)}
`);
return;
}
ongoingRpc.resolve(parsed.data);
this.ongoingRpcs.delete(message.callId);
this.updateOpenCommunicationsCount();
}
receivedRpcError(message) {
const ongoingRpc = this.ongoingRpcs.get(message.callId);
if (ongoingRpc === void 0) {
this.communicationWarning(`Received rpcError for unknown rpc, callId = ${message.callId}`);
return;
}
const error = this.errorDeserializer(message.error, "RPC Error", this.verboseErrorMessage ? ongoingRpc.stack : void 0);
ongoingRpc.reject(error);
this.ongoingRpcs.delete(message.callId);
this.updateOpenCommunicationsCount();
}
receivedSignalUpdate(message) {
const openSignalSubscription = this.openSignalSubscriptions.get(message.subscribeId);
if (openSignalSubscription === void 0) {
return;
}
const patches = message.patches.map((patch) => deserialize(openSignalSubscription.endpoint.serialization, patch));
const beforeValue = openSignalSubscription.getValue();
let afterValue;
try {
afterValue = applyPatches(beforeValue, patches);
} catch (error) {
this.communicationWarning(text`
Failed to apply patches to signal on signalUpdate. subscribeId = ${message.subscribeId}.
beforeValue = ${JSON.stringify(beforeValue, null, 2)},
patches = ${JSON.stringify(patches, null, 2)}.
Error: ${String(error)}
`);
return;
}
const parseResult = openSignalSubscription.endpoint.signalData.safeParse(afterValue);
if (!parseResult.success) {
this.communicationWarning(text`
Received invalid signal patch data, subscribeId = ${message.subscribeId}
patches = ${patches},
beforeValue = ${beforeValue},
afterValue = ${afterValue}.
Zod error:
${Validator.prettyPrintZod("value", parseResult.error)}
`);
return;
}
openSignalSubscription.receivedPatches(afterValue, patches, message.tags);
}
receivedSignalError(message) {
const openSignalSubscription = this.openSignalSubscriptions.get(message.subscribeId);
if (openSignalSubscription === void 0) {
this.communicationWarning(`Received signalError for unknown signal, subscribeId = ${message.subscribeId}`);
return;
}
const error = this.errorDeserializer(message.error, "Signal Error", this.verboseErrorMessage ? openSignalSubscription.stack : void 0);
openSignalSubscription.errored(error);
this.openSignalSubscriptions.delete(message.subscribeId);
this.updateOpenCommunicationsCount();
}
receivedWritableSignalUpdate(message) {
const openSignalSubscription = this.openWritableSignalSubscriptions.get(message.subscribeId);
if (openSignalSubscription === void 0) {
return;
}
const patches = message.patches.map((patch) => deserialize(openSignalSubscription.endpoint.serialization, patch));
const beforeValue = openSignalSubscription.getValue();
let afterValue;
try {
afterValue = applyPatches(openSignalSubscription.getValue(), patches);
} catch (error) {
this.communicationWarning(text`
Failed to apply patches to writable signal on writableSignalUpdate. subscribeId =
${message.subscribeId}.
beforeValue = ${JSON.stringify(beforeValue, null, 2)},
patches = ${JSON.stringify(patches, null, 2)}.
Error: ${String(error)}
`);
}
const parseResult = openSignalSubscription.endpoint.signalData.safeParse(afterValue);
if (!parseResult.success) {
this.communicationWarning(text`
Received invalid writable signal patch data, subscribeId = ${message.subscribeId}
patches = ${patches},
beforeValue = ${beforeValue},
afterValue = ${afterValue}.
Zod error:
${Validator.prettyPrintZod("value", parseResult.error)}
`);
return;
}
openSignalSubscription.firstUpdateReceived = true;
openSignalSubscription.receivedPatches(afterValue, patches, message.tags);
}
receivedWritableSignalError(message) {
const openSignalSubscription = this.openWritableSignalSubscriptions.get(message.subscribeId);
if (openSignalSubscription === void 0) {
this.communicationWarning(`Received writableSignalError for unknown signal, subscribeId = ${message.subscribeId}`);
return;
}
const error = this.errorDeserializer(message.error, "Writable Signal Error", this.verboseErrorMessage ? openSignalSubscription.stack : void 0);
openSignalSubscription.errored(error);
this.openWritableSignalSubscriptions.delete(message.subscribeId);
this.updateOpenCommunicationsCount();
}
receivedCommunicationWarning(message) {
this.logger.warnText`
Received communication warning from the server: ${message.warning}
This is usually caused by communication protocol incompatibility. Please make sure you are
using the up-to-date versions of the SDK and LM Studio.
Note: This warning was received from the server and is printed on the client for convenience.
`;
}
receivedKeepAliveAck(_message) {
}
async callRpc(endpointName, param, { stack } = {}) {
const endpoint = this.backendInterface.getRpcEndpoint(endpointName);
if (endpoint === void 0) {
throw new Error(`No Rpc endpoint with name ${endpointName}`);
}
const parameter = endpoint.parameter.parse(param);
const serializedParameter = serialize(endpoint.serialization, parameter);
const callId = this.nextChannelId;
this.nextChannelId++;
const { promise, resolve: resolve2, reject } = makePromise();
stack = stack ?? getCurrentStack(1);
this.ongoingRpcs.set(callId, {
endpoint,
stack,
resolve: resolve2,
reject
});
this.transport.send({
type: "rpcCall",
endpoint: endpointName,
callId,
parameter: serializedParameter
});
this.updateOpenCommunicationsCount();
return await promise;
}
createChannel(endpointName, param, onMessage, { stack } = {}) {
const channelEndpoint = this.backendInterface.getChannelEndpoint(endpointName);
if (channelEndpoint === void 0) {
throw new Error(`No channel endpoint with name ${endpointName}`);
}
const creationParameter = channelEndpoint.creationParameter.parse(param);
const serializedCreationParameter = serialize(channelEndpoint.serialization, creationParameter);
const channelId = this.nextChannelId;
this.nextChannelId++;
this.transport.send({
type: "channelCreate",
endpoint: endpointName,
channelId,
creationParameter: serializedCreationParameter
});
stack = stack ?? getCurrentStack(1);
const openChannel = {
endpoint: channelEndpoint,
stack,
...Channel.create((packet) => {
const parsed = channelEndpoint.toServerPacket.parse(packet);
const serializedMessage = serialize(channelEndpoint.serialization, parsed);
this.transport.send({
type: "channelSend",
channelId,
message: serializedMessage
});
})
};
if (onMessage !== void 0) {
openChannel.channel.onMessage.subscribe(onMessage);
}
this.openChannels.set(channelId, openChannel);
this.updateOpenCommunicationsCount();
return openChannel.channel;
}
/**
* Creates a readonly lazy signal will subscribe to the signal endpoint with the given name.
*/
createSignal(endpointName, param, { stack } = {}) {
const signalEndpoint = this.backendInterface.getSignalEndpoint(endpointName);
if (signalEndpoint === void 0) {
throw new Error(`No signal endpoint with name ${endpointName}`);
}
const creationParameter = signalEndpoint.creationParameter.parse(param);
const serializedCreationParameter = serialize(signalEndpoint.serialization, creationParameter);
stack = stack ?? getCurrentStack(1);
const signal = LazySignal.createWithoutInitialValue((setDownstream, errorListener) => {
const subscribeId = this.nextSubscribeId;
this.nextSubscribeId++;
this.transport.send({
type: "signalSubscribe",
endpoint: endpointName,
subscribeId,
creationParameter: serializedCreationParameter
});
this.openSignalSubscriptions.set(subscribeId, {
endpoint: signalEndpoint,
getValue: () => signal.get(),
receivedPatches: setDownstream.withValueAndPatches,
errored: errorListener,
stack
});
this.updateOpenCommunicationsCount();
return () => {
this.transport.send({
type: "signalUnsubscribe",
subscribeId
});
this.openSignalSubscriptions.delete(subscribeId);
};
});
return signal;
}
createWritableSignal(endpointName, param, { stack } = {}) {
const signalEndpoint = this.backendInterface.getWritableSignalEndpoint(endpointName);
if (signalEndpoint === void 0) {
throw new Error(`No writable signal endpoint with name ${endpointName}`);
}
const creationParameter = signalEndpoint.creationParameter.parse(param);
const serializedCreationParameter = serialize(signalEndpoint.serialization, creationParameter);
stack = stack ?? getCurrentStack(1);
let currentSubscribeId = null;
const writeUpstream = (_data, patches, tags) => {
if (currentSubscribeId === null) {
console.warn("writeUpstream called when not subscribed");
return false;
}
const subscription = this.openWritableSignalSubscriptions.get(currentSubscribeId);
if (!subscription?.firstUpdateReceived) {
console.warn("writeUpstream called before the first update is received");
return false;
}
this.transport.send({
type: "writableSignalUpdate",
subscribeId: currentSubscribeId,
patches: patches.map((patch) => serialize(signalEndpoint.serialization, patch)),
tags
});
return true;
};
const [signal, setter] = OWLSignal.createWithoutInitialValue((setDownstream, errorListener) => {
const subscribeId = this.nextWritableSubscribeId;
currentSubscribeId = subscribeId;
this.nextWritableSubscribeId++;
this.transport.send({
type: "writableSignalSubscribe",
endpoint: endpointName,
subscribeId,
creationParameter: serializedCreationParameter
});
this.openWritableSignalSubscriptions.set(subscribeId, {
endpoint: signalEndpoint,
getValue: () => signal.getPessimistic(),
receivedPatches: setDownstream.withValueAndPatches,
firstUpdateReceived: false,
errored: errorListener,
stack
});
this.updateOpenCommunicationsCount();
return () => {
currentSubscribeId = null;
this.transport.send({
type: "writableSignalUnsubscribe",
subscribeId
});
this.openWritableSignalSubscriptions.delete(subscribeId);
};
}, writeUpstream);
return [signal, setter];
}
async [Symbol.asyncDispose]() {
await this.transport[Symbol.asyncDispose]();
}
};
GenericClientTransport = class _GenericClientTransport extends ClientTransport {
constructor(onMessage, onClose, sendMessage2, receivedMessage, errored, parentLogger) {
super();
this.sendMessage = sendMessage2;
this.receivedMessage = receivedMessage;
this.errored = errored;
this.closed = false;
this.logger = new SimpleLogger("GenericClientTransport", parentLogger);
onMessage.subscribe((message) => {
let parsed;
try {
parsed = this.parseIncomingMessage(message);
} catch (error) {
this.logger.warn("Received invalid message from server:", message);
return;
}
this.receivedMessage(parsed);
});
onClose.subscribeOnce(() => {
if (this.closed) {
return;
}
this.closed = true;
this.errored(new Error("Server closed the connection"));
});
}
static createFactory(onMessage, onClose, sendMessage2) {
return (receivedMessage, errored, parentLogger) => new _GenericClientTransport(onMessage, onClose, sendMessage2, receivedMessage, errored, parentLogger);
}
sendViaTransport(message) {
this.sendMessage(message);
}
};
DiagnosticsNamespace = class {
/** @internal */
constructor(diagnosticsPort, validator2, parentLogger) {
this.diagnosticsPort = diagnosticsPort;
this.validator = validator2;
this.logger = new SimpleLogger("Diagnostics", parentLogger);
}
/**
* Register a callback to receive log events. Return a function to stop receiving log events.
*
* This method is in alpha. Do not use this method in production yet.
* @alpha
*/
unstable_streamLogs(listener) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("client.diagnostics", "unstable_streamLogs", "listener", external_exports.function(), listener, stack);
const channel = this.diagnosticsPort.createChannel("streamLogs", void 0, void 0, {
stack
});
const unsubscribe = channel.onMessage.subscribe((message) => {
if (message.type === "log") {
listener(message.log);
}
});
return () => {
unsubscribe();
channel.send({
type: "stop"
});
};
}
};
ModelNamespace = class {
/** @internal */
getLoadModelOptsSchema() {
if (this.loadModelOptsSchema === null) {
this.loadModelOptsSchema = makeLoadModelOptsSchema(this.loadModelConfigSchema);
}
return this.loadModelOptsSchema;
}
/** @internal */
constructor(client, port2, logger2, validator2) {
this.client = client;
this.port = port2;
this.logger = logger2;
this.validator = validator2;
this.loadModelOptsSchema = null;
}
/**
* Load a model for inferencing. The first parameter is the model key. The second parameter is an
* optional object with additional options.
*
* To find out what models are available, you can use the `lms ls` command, or programmatically
* use the `client.system.listDownloadedModels` method.
*
* Here are some examples:
*
* Loading Llama 3.2:
*
* ```typescript
* const model = await client.llm.load("llama-3.2-3b-instruct");
* ```
*
* Once loaded, see {@link LLMDynamicHandle} or {@link EmbeddingDynamicHandle} for how to use the
* model for inferencing or other things you can do with the model.
*
* @param modelKey - The path of the model to load.
* @param opts - Options for loading the model.
* @returns A promise that resolves to the model that can be used for inferencing
*/
async load(modelKey, opts = {}) {
const stack = getCurrentStack(1);
[modelKey, opts] = this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`, "load", ["modelKey", "opts"], [reasonableKeyStringSchema, this.getLoadModelOptsSchema()], [modelKey, opts], stack);
const { identifier, signal, verbose = "info", config, onProgress } = opts;
let lastVerboseCallTime = 0;
const { promise, resolve: resolve2, reject } = makePromise();
const verboseLevel = typeof verbose === "boolean" ? "info" : verbose;
const startTime = Date.now();
if (verbose) {
this.logger.logAtLevel(verboseLevel, text`
Verbose logging is enabled. To hide progress logs, set the "verbose" option to false in
client.llm.load.
`);
}
let fullPath = modelKey;
const channel = this.port.createChannel("loadModel", {
modelKey,
identifier,
ttlMs: opts.ttl === void 0 ? void 0 : opts.ttl * 1e3,
loadConfigStack: singleLayerKVConfigStackOf("apiOverride", this.loadConfigToKVConfig(config ?? this.defaultLoadConfig))
}, (message) => {
switch (message.type) {
case "resolved": {
fullPath = message.info.modelKey;
if (message.ambiguous !== void 0) {
this.logger.warn(text`
Multiple models found for key ${modelKey}:
${message.ambiguous.map((x2) => ` - ${x2}`).join("\n")}
Using the first one.
`);
}
if (verbose) {
this.logger.logAtLevel(verboseLevel, text`
Start loading model ${fullPath}...
`);
}
break;
}
case "success": {
if (verbose) {
this.logger.logAtLevel(verboseLevel, text`
Successfully loaded model ${fullPath} in ${Date.now() - startTime}ms
`);
}
resolve2(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger));
break;
}
case "progress": {
const { progress } = message;
if (onProgress !== void 0) {
safeCallCallback(this.logger, "onProgress", onProgress, [progress]);
} else if (verbose) {
const now = Date.now();
if (now - lastVerboseCallTime > 500 || progress === 1) {
const progressText = (progress * 100).toFixed(1);
this.logger.logAtLevel(verboseLevel, `Loading the model, progress: ${progressText}%`);
lastVerboseCallTime = now;
}
}
}
}
}, { stack });
channel.onError.subscribeOnce(reject);
if (signal !== void 0) {
if (signal.aborted) {
channel.send({ type: "cancel" });
reject(signal.reason);
} else {
signal.addEventListener("abort", () => {
channel.send({ type: "cancel" });
reject(signal.reason);
}, { once: true });
}
}
return await promise;
}
/**
* Unload a model. Once a model is unloaded, it can no longer be used. If you wish to use the
* model afterwards, you will need to load it with {@link LLMNamespace#loadModel} again.
*
* @param identifier - The identifier of the model to unload.
*/
unload(identifier) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "unload", "identifier", reasonableKeyStringSchema, identifier, stack);
return this.port.callRpc("unloadModel", { identifier }, { stack });
}
/**
* List all the currently loaded models.
*/
async listLoaded() {
const stack = getCurrentStack(1);
const infos = await this.port.callRpc("listLoaded", void 0, { stack });
return infos.map((info2) => this.createDomainSpecificModel(this.port, info2, this.validator, this.logger));
}
/**
* Get any loaded model of this domain.
*/
async getAny(stack) {
const info2 = await this.port.callRpc("getModelInfo", { specifier: { type: "query", query: {} }, throwIfNotFound: true }, { stack });
if (info2 === void 0) {
throw new Error("Backend should have thrown.");
}
return this.createDomainSpecificModel(this.port, info2, this.validator, new SimpleLogger("LLM", this.logger));
}
createDynamicHandle(param) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "createDynamicHandle", "param", external_exports.union([reasonableKeyStringSchema, modelQuerySchema]), param, stack);
let query;
if (typeof param === "string") {
query = {
identifier: param
};
} else {
query = param;
}
if (query.path?.includes("\\")) {
throw makePrettyError(text`
Model path should not contain backslashes, even if you are on Windows. Use forward
slashes instead.
`, stack);
}
return this.createDomainDynamicHandle(this.port, {
type: "query",
query
}, this.validator, new SimpleLogger("DynamicHandle", this.logger));
}
/**
* Create a dynamic handle from the internal instance reference.
*
* @alpha
*/
createDynamicHandleFromInstanceReference(instanceReference) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "createDynamicHandleFromInstanceReference", "instanceReference", external_exports.string(), instanceReference, stack);
return this.createDomainDynamicHandle(this.port, {
type: "instanceReference",
instanceReference
}, this.validator, new SimpleLogger("DynamicHandle", this.logger));
}
async model(modelKey, opts = {}) {
const stack = getCurrentStack(1);
if (modelKey === void 0) {
return await this.getAny(stack);
}
[modelKey, opts] = this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`, "model", ["modelKey", "opts"], [reasonableKeyStringSchema, this.getLoadModelOptsSchema()], [modelKey, opts], stack);
const { identifier, signal, verbose = "info", config, onProgress } = opts;
if (identifier !== void 0) {
throw new Error("The identifier option is not allowed when using `.model`.");
}
let lastVerboseCallTime = 0;
const { promise, resolve: resolve2, reject } = makePromise();
const verboseLevel = typeof verbose === "boolean" ? "info" : verbose;
const startTime = Date.now();
const channel = this.port.createChannel("getOrLoad", {
identifier: modelKey,
loadTtlMs: opts.ttl === void 0 ? void 0 : opts.ttl * 1e3,
loadConfigStack: singleLayerKVConfigStackOf("apiOverride", this.loadConfigToKVConfig(config ?? this.defaultLoadConfig))
}, (message) => {
switch (message.type) {
case "alreadyLoaded": {
return resolve2(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger));
}
case "unloadingOtherJITModel": {
if (verbose) {
this.logger.logAtLevel(verboseLevel, text`
Unloading other JIT model ${message.info.modelKey}. (You can disable this behavior
by going to LM Studio -> Settings -> Developer -> Turn OFF JIT models auto-evict)
`);
}
break;
}
case "startLoading": {
if (verbose) {
this.logger.logAtLevel(verboseLevel, text`
Verbose logging is enabled. To hide progress logs, set the "verbose" option to
false in .model().
`);
this.logger.logAtLevel(verboseLevel, text`
Model ${modelKey} is not loaded. Start loading...
`);
}
break;
}
case "loadProgress": {
const { progress } = message;
if (onProgress !== void 0) {
safeCallCallback(this.logger, "onProgress", onProgress, [progress]);
} else if (verbose) {
const now = Date.now();
if (now - lastVerboseCallTime > 500 || progress === 1) {
const progressText = (progress * 100).toFixed(1);
this.logger.logAtLevel(verboseLevel, `Loading the model, progress: ${progressText}%`);
lastVerboseCallTime = now;
}
}
break;
}
case "loadSuccess": {
if (verbose) {
this.logger.logAtLevel(verboseLevel, text`
Successfully loaded model ${message.info.modelKey} in ${Date.now() - startTime}ms
`);
}
resolve2(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger));
}
}
}, { stack });
channel.onError.subscribeOnce(reject);
signal?.addEventListener("abort", () => {
channel.send({ type: "cancel" });
reject(signal.reason);
});
return await promise;
}
};
DynamicHandle = class {
/**
* Don't construct this on your own. Use {@link LLMNamespace#get} or {@link LLMNamespace#load}
* instead.
*
* @internal
*/
constructor(port2, specifier) {
this.port = port2;
this.specifier = specifier;
}
/**
* Gets the information of the model that is currently associated with this `DynamicHandle`. If no
* model is currently associated, this will return `undefined`.
*
* Note: As models are loaded/unloaded, the model associated with this `LLMModel` may change at
* any moment.
*/
async getModelInfo() {
const info2 = await this.port.callRpc("getModelInfo", { specifier: this.specifier, throwIfNotFound: false }, { stack: getCurrentStack(1) });
if (info2 === void 0) {
return void 0;
}
return info2;
}
async getLoadConfig(stack) {
const loadConfig = await this.port.callRpc("getLoadConfig", { specifier: this.specifier }, { stack });
return loadConfig;
}
};
EmbeddingDynamicHandle = class extends DynamicHandle {
/**
* Don't construct this on your own. Use {@link EmbeddingNamespace#get} or
* {@link EmbeddingNamespace#load}
* instead.
*
* @internal
*/
constructor(port2, specifier, validator2, logger2 = new SimpleLogger(`EmbeddingModel`)) {
super(port2, specifier);
this.validator = validator2;
this.logger = logger2;
}
async embed(inputString) {
const stack = getCurrentStack(1);
inputString = this.validator.validateMethodParamOrThrow("client.embedding", "embed", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack);
if (Array.isArray(inputString)) {
return await Promise.all(inputString.map((s6) => this.port.callRpc("embedString", { inputString: s6, modelSpecifier: this.specifier }, { stack })));
} else {
return await this.port.callRpc("embedString", { inputString, modelSpecifier: this.specifier }, { stack });
}
}
async getContextLength() {
const stack = getCurrentStack(1);
const loadConfig = await this.getLoadConfig(stack);
return embeddingSharedLoadConfigSchematics.access(loadConfig, "contextLength");
}
async getEvalBatchSize() {
const stack = getCurrentStack(1);
const loadConfig = await this.getLoadConfig(stack);
return globalConfigSchematics.access(loadConfig, "embedding.load.llama.evalBatchSize");
}
async tokenize(inputString) {
const stack = getCurrentStack(1);
inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack);
if (Array.isArray(inputString)) {
return (await Promise.all(inputString.map((s6) => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s6 }, { stack })))).map((r8) => r8.tokens);
} else {
return (await this.port.callRpc("tokenize", {
specifier: this.specifier,
inputString
}, { stack })).tokens;
}
}
async countTokens(inputString) {
const stack = getCurrentStack(1);
inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", external_exports.string(), inputString, stack);
return (await this.port.callRpc("countTokens", {
specifier: this.specifier,
inputString
}, { stack })).tokenCount;
}
};
EmbeddingModel = class extends EmbeddingDynamicHandle {
/** @internal */
constructor(embeddingPort, info2, validator2, logger2 = new SimpleLogger(`EmbeddingModel`)) {
const specifier = {
type: "instanceReference",
instanceReference: info2.instanceReference
};
super(embeddingPort, specifier, validator2, logger2);
this.identifier = info2.identifier;
this.path = info2.path;
this.modelKey = info2.modelKey;
this.format = info2.format;
this.displayName = info2.displayName;
this.sizeBytes = info2.sizeBytes;
}
async unload() {
const stack = getCurrentStack(1);
await this.port.callRpc("unloadModel", { identifier: this.identifier }, { stack });
}
async getModelInfo() {
const info2 = await super.getModelInfo();
if (info2 === void 0) {
const stack = getCurrentStack(1);
throw makePrettyError("This model has already been unloaded", stack);
}
return info2;
}
};
EmbeddingNamespace = class extends ModelNamespace {
constructor() {
super(...arguments);
this.namespace = "embedding";
this.defaultLoadConfig = {};
this.loadModelConfigSchema = embeddingLoadModelConfigSchema;
}
/** @internal */
loadConfigToKVConfig(config) {
return embeddingLlamaLoadConfigSchematics.buildPartialConfig({
"llama.acceleration.offloadRatio": config.gpu?.ratio,
"load.gpuSplitConfig": convertGPUSettingToGPUSplitConfig(config.gpu),
"contextLength": config.contextLength,
"llama.ropeFrequencyBase": numberToCheckboxNumeric(config.ropeFrequencyBase, 0, 0),
"llama.ropeFrequencyScale": numberToCheckboxNumeric(config.ropeFrequencyScale, 0, 0),
"llama.keepModelInMemory": config.keepModelInMemory,
"llama.tryMmap": config.tryMmap
});
}
/** @internal */
createDomainSpecificModel(port2, info2, validator2, logger2) {
return new EmbeddingModel(port2, info2, validator2, logger2);
}
/** @internal */
createDomainDynamicHandle(port2, specifier, validator2, logger2) {
return new EmbeddingDynamicHandle(port2, specifier, validator2, logger2);
}
};
parseDocumentOptsSchema = documentParsingOptsSchema.extend({
onProgress: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional()
});
retrievalCallbacksSchema = external_exports.object({
onFileProcessList: external_exports.function().optional(),
onFileProcessingStart: external_exports.function().optional(),
onFileProcessingEnd: external_exports.function().optional(),
onFileProcessingStepStart: external_exports.function().optional(),
onFileProcessingStepProgress: external_exports.function().optional(),
onFileProcessingStepEnd: external_exports.function().optional(),
onSearchingStart: external_exports.function().optional(),
onSearchingEnd: external_exports.function().optional(),
verbose: external_exports.union([external_exports.boolean(), external_exports.string()]).optional()
});
retrievalOptsSchema = external_exports.object({
chunkingMethod: retrievalChunkingMethodSchema.optional(),
limit: external_exports.number().int().optional(),
embeddingModel: external_exports.instanceof(EmbeddingDynamicHandle).optional(),
databasePath: external_exports.string().optional(),
signal: external_exports.instanceof(AbortSignal).optional(),
...retrievalCallbacksSchema.shape
});
FilesNamespace = class {
/** @internal */
constructor(filesPort, validator2, parentLogger) {
this.filesPort = filesPort;
this.validator = validator2;
this.logger = new SimpleLogger("File", parentLogger);
}
/**
* Gets the absolute path to a local file.
*
* @internal
*/
async getLocalFileAbsolutePath(fileName, stack) {
return await this.filesPort.callRpc("getLocalFileAbsolutePath", { fileName }, { stack });
}
/**
* Creates a file handle from a chat message part file data. Used internally.
*
* @internal
*/
createFileHandleFromChatMessagePartFileData(data) {
return new FileHandle(this, data.identifier, data.fileType, data.sizeBytes, data.name);
}
/**
* Adds a temporary image to LM Studio, and returns a FileHandle that can be used to reference
* this image. This image will be deleted when the client disconnects.
*
* This method can only be used in environments that have file system access (such as Node.js).
*/
async prepareImage(path6) {
const result = await (0, import_lms_isomorphic.readFileAsBase64)(path6);
if (result.success === false) {
throw new Error(text`
Your current JavaScript environment does not support reading files. If you can read the file
using other methods, please use "prepareImageBase64".
`);
}
const fileName = path6.split(/[\\/]/).at(-1);
const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", {
name: fileName,
contentBase64: result.base64
});
return new FileHandle(this, identifier, fileType, sizeBytes, fileName);
}
/**
* Adds a temporary image to LM Studio. The content of the file is specified using base64. If you
* are using Node.js and have a file laying around, consider using `prepareImage` instead.
*/
async prepareImageBase64(fileName, contentBase64) {
const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", {
name: fileName,
contentBase64
});
return new FileHandle(this, identifier, fileType, sizeBytes, fileName);
}
/**
* Adds a temporary file to LM Studio, and returns a FileHandle that can be used to reference this
* file. This file will be deleted when the client disconnects.
*
* This method can only be used in environments that have file system access (such as Node.js).
*
* @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for
* updates.
*/
async prepareFile(path6) {
const result = await (0, import_lms_isomorphic.readFileAsBase64)(path6);
if (result.success === false) {
throw new Error(text`
Your current JavaScript environment does not support reading files. If you can read the file
using other methods, please use "prepareFileBase64".
`);
}
const fileName = path6.split(/[\\/]/).at(-1);
const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", {
name: fileName,
contentBase64: result.base64
});
return new FileHandle(this, identifier, fileType, sizeBytes, fileName);
}
/**
* Adds a temporary file to LM Studio. The content of the file is specified using base64. If you
* are using Node.js and have a file laying around, consider using `prepareFile` instead.
*
* @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for
* updates. */
async prepareFileBase64(fileName, contentBase64) {
const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", {
name: fileName,
contentBase64
});
return new FileHandle(this, identifier, fileType, sizeBytes, fileName);
}
/**
* @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for
* updates. */
async retrieve(query, files, opts = {}) {
const logger2 = this.logger;
const stack = getCurrentStack(1);
this.validator.validateMethodParamsOrThrow("client.retrieval", "retrieve", ["query", "filePaths", "opts"], [external_exports.string(), external_exports.array(external_exports.instanceof(FileHandle)), retrievalOptsSchema], [query, files, opts], stack);
const { verbose = "info" } = opts;
const verboseLevel = typeof verbose === "boolean" ? "info" : verbose;
const shouldLog = verbose && opts.onFileProcessList === void 0 && opts.onFileProcessingStart === void 0 && opts.onFileProcessingEnd === void 0 && opts.onFileProcessingStepStart === void 0 && opts.onFileProcessingStepProgress === void 0 && opts.onFileProcessingStepEnd === void 0 && opts.onSearchingStart === void 0 && opts.onSearchingEnd === void 0;
if (opts.embeddingModel === void 0) {
throw new Error("Embedding model currently is required.");
}
const resolveFileIndex = (index2) => {
const file = files[index2];
if (file === void 0) {
throw new Error(`File not found: ${index2}`);
}
return file;
};
const resolveFileIndices = (indices) => {
return indices.map(resolveFileIndex);
};
const kvConfig = retrievalSchematics.buildPartialConfig({
chunkingMethod: opts.chunkingMethod,
databaseFile: opts.databasePath,
embeddingModel: (await opts.embeddingModel.getModelInfo())?.identifier,
limit: opts.limit
});
let filesToProcess;
const filesProcessingStartTimes = [];
let searchingStartTime = 0;
let lastVerboseCallTime = 0;
let lastVerboseLine = "";
return await new Promise((resolve2, reject) => {
const channel = this.filesPort.createChannel("retrieve", { query, fileIdentifiers: files.map((file) => file.identifier), config: kvConfig }, (message) => {
switch (message.type) {
case "onFileProcessList":
filesToProcess = resolveFileIndices(message.indices);
safeCallCallback(logger2, "onFileProcessList", opts.onFileProcessList, [
filesToProcess
]);
if (shouldLog) {
logger2.logAtLevel(verboseLevel, text`
Found ${filesToProcess.length} files need processing:
${filesToProcess.map((file) => file.name).join(", ")}
`);
}
break;
case "onFileProcessingStart": {
if (filesToProcess === null) {
throw new Error("onFileProcessList must be called before onFileProcessingStart");
}
const file = resolveFileIndex(message.index);
safeCallCallback(logger2, "onFileProcessingStart", opts.onFileProcessingStart, [
file,
filesToProcess.indexOf(file),
filesToProcess
]);
if (shouldLog) {
filesProcessingStartTimes[message.index] = Date.now();
logger2.logAtLevel(verboseLevel, text`
Start processing file: ${file.name}
(${message.index + 1}/${filesToProcess.length})
`);
}
break;
}
case "onFileProcessingEnd": {
if (filesToProcess === null) {
throw new Error("onFileProcessList must be called before onFileProcessingEnd");
}
const file = resolveFileIndex(message.index);
safeCallCallback(logger2, "onFileProcessingEnd", opts.onFileProcessingEnd, [
file,
filesToProcess.indexOf(file),
filesToProcess
]);
if (shouldLog) {
logger2.logAtLevel(verboseLevel, text`
File processed: ${file.name}.
Time took: ${Date.now() - filesProcessingStartTimes[message.index]}ms
`);
}
break;
}
case "onFileProcessingStepStart":
safeCallCallback(logger2, "onFileProcessingStepStart", opts.onFileProcessingStepStart, [resolveFileIndex(message.index), message.step]);
break;
case "onFileProcessingStepProgress": {
safeCallCallback(logger2, "onFileProcessingStepProgress", opts.onFileProcessingStepProgress, [resolveFileIndex(message.index), message.step, message.progress]);
const now = Date.now();
if (shouldLog && (now - lastVerboseCallTime > 500 || message.progress === 1)) {
lastVerboseCallTime = now;
const line = text`
> ${getProcessingStepName(message.step)}: ${Math.round(message.progress * 100)}%
`;
if (lastVerboseLine !== line) {
lastVerboseLine = line;
logger2.logAtLevel(verboseLevel, line);
}
}
break;
}
case "onFileProcessingStepEnd":
safeCallCallback(logger2, "onFileProcessingStepEnd", opts.onFileProcessingStepEnd, [
resolveFileIndex(message.index),
message.step
]);
break;
case "onSearchingStart":
safeCallCallback(logger2, "onSearchingStart", opts.onSearchingStart, []);
if (shouldLog) {
searchingStartTime = Date.now();
logger2.logAtLevel(verboseLevel, "Start searching in the vector database...");
}
break;
case "onSearchingEnd":
safeCallCallback(logger2, "onSearchingEnd", opts.onSearchingEnd, []);
if (shouldLog) {
logger2.logAtLevel(verboseLevel, text`
Finished searching in the vector database.
Time took: ${Date.now() - searchingStartTime}ms
`);
}
break;
case "result": {
resolve2({
entries: message.result.entries.map((entry) => ({
content: entry.content,
score: entry.score,
source: files[entry.sourceIndex]
}))
});
break;
}
}
});
if (opts.signal !== void 0) {
if (opts.signal.aborted) {
reject(opts.signal.reason);
channel.send({ type: "stop" });
} else {
opts.signal?.addEventListener("abort", () => {
reject(opts.signal.reason);
channel.send({ type: "stop" });
});
}
}
channel.onError.subscribeOnce(reject);
});
}
/**
* Parse a document
*
* @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for
* updates.
*/
async parseDocument(fileHandle, opts = {}) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamsOrThrow("client.files", "parseDocument", ["fileHandle", "opts"], [external_exports.instanceof(FileHandle), parseDocumentOptsSchema], [fileHandle, opts], stack);
const { onParserLoaded, onProgress, signal, ...config } = opts;
const { promise, resolve: resolve2, reject } = makePromise();
opts.signal?.throwIfAborted();
let finished2 = false;
const channel = this.filesPort.createChannel("parseDocument", { fileIdentifier: fileHandle.identifier, parseOpts: config }, (message) => {
const messageType = message.type;
switch (messageType) {
case "progress": {
safeCallCallback(this.logger, "onProgress", onProgress, [message.progress]);
break;
}
case "parserLoaded": {
safeCallCallback(this.logger, "onParserLoaded", onParserLoaded, [message.parser]);
break;
}
case "result": {
resolve2({
content: message.content,
parser: message.parser
});
finished2 = true;
break;
}
}
}, { stack });
signal?.addEventListener("abort", () => {
if (finished2) {
return;
}
reject(signal.reason);
channel.send({ type: "cancel" });
});
channel.onError.subscribeOnce(reject);
channel.onClose.subscribeOnce(() => {
if (!finished2) {
reject(new Error("Channel closed before receiving a result."));
}
});
return await promise;
}
/**
* Get the parsing method for a document.
*
* @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for
* updates.
*/
async getDocumentParsingLibrary(fileHandle) {
const stack = getCurrentStack(1);
return await this.filesPort.callRpc("getDocumentParsingLibrary", { fileIdentifier: fileHandle.identifier }, { stack });
}
};
errorDeserializersMap = /* @__PURE__ */ new Map();
registerErrorDeserializer("generic.pathNotFound", ({ availablePathsSample, path: path6, totalModels }, stack) => {
return makeTitledPrettyError(`Cannot find a model with path "${import_chalk.default.yellowBright(path6)}"`, text`
Here are your available models:
${formatAvailableLLMs(availablePathsSample, totalModels)}
Run
${import_chalk.default.yellowBright("lms ls")}
to see a full list of loadable models
`, stack);
});
registerErrorDeserializer("generic.identifierNotFound", ({ loadedModelsSample, identifier, totalLoadedModels }, stack) => {
return makeTitledPrettyError(`Cannot find a model with identifier "${import_chalk.default.yellowBright(identifier)}"`, text`
Here are your loaded models:
${formatLoadedModels(loadedModelsSample, totalLoadedModels)}
Run
${import_chalk.default.yellowBright("lms ps")}
to see a full list of loaded models
`, stack);
});
registerErrorDeserializer("generic.specificModelUnloaded", (_3, stack) => {
return makePrettyError(import_chalk.default.bgRed.white(text`
This model has already been unloaded.
`), stack);
});
registerErrorDeserializer("generic.noModelMatchingQuery", ({ loadedModelsSample, totalLoadedModels, query }, stack) => {
return makePrettyError(text`
${import_chalk.default.bgRed.white(" No loaded model satisfies all requirements specified in the query. ")}
Loaded Models:
${formatLoadedModels(loadedModelsSample, totalLoadedModels)}
Your query:
${formatQuery(query)}
Run
${import_chalk.default.yellowBright("lms ps")}
to see a full list of loaded models with details
`, stack);
});
registerErrorDeserializer("generic.domainMismatch", ({ actualDomain, expectedDomain, path: path6 }, stack) => {
return makePrettyError(text`
${import_chalk.default.bgRed.white(" Model has wrong domain. ")}
Expecting ${import_chalk.default.greenBright(path6)} to be ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(expectedDomain))}, but it is actually ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(actualDomain))}.
`, stack);
});
registerErrorDeserializer("generic.presetNotFound", ({ specifiedFuzzyPresetIdentifier, availablePresetsSample, totalAvailablePresets }) => {
return makeTitledPrettyError(`Cannot find a preset with identifier "${import_chalk.default.yellowBright(specifiedFuzzyPresetIdentifier)}"`, text`
Here are your available presets:
${formatAvailablePresets(availablePresetsSample, totalAvailablePresets)}
Note: To specify a preset in the SDK, you need to use its identifier (in parentheses). You
can get a preset's identifier by right-clicking on it and then select "Copy Preset
Identifier".
`);
});
ActResult = class {
constructor(rounds, totalExecutionTimeSeconds) {
this.rounds = rounds;
this.totalExecutionTimeSeconds = totalExecutionTimeSeconds;
}
};
callIdGiver = new IdGiver(Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER / 2 / 1e4)) * 1e4);
NoQueueQueue = class {
needsQueueing() {
return false;
}
async runInQueue(fn, signal) {
if (signal?.aborted) {
throw new Error("Operation aborted");
}
return fn();
}
};
FIFOQueue = class {
constructor() {
this.queue = [];
this.executing = false;
this.poisoned = false;
this.poisonError = null;
}
needsQueueing() {
return this.executing || this.queue.length > 0;
}
async runInQueue(fn, signal) {
if (signal?.aborted) {
throw new Error("Operation aborted");
}
if (this.poisoned) {
throw this.poisonError ?? new Error("Queue has been poisoned by a previous error");
}
if (!this.needsQueueing()) {
this.executing = true;
try {
if (signal?.aborted) {
throw new Error("Operation aborted");
}
return await fn();
} catch (error) {
this.poisoned = true;
this.poisonError = error;
this.clearQueue(error);
throw error;
} finally {
this.executing = false;
this.processQueue();
}
}
return new Promise((resolve2, reject) => {
if (signal) {
if (signal.aborted) {
return reject(new Error("Operation aborted"));
}
signal.addEventListener("abort", () => {
const index2 = this.queue.findIndex((item) => item.resolve === resolve2 && item.reject === reject);
if (index2 !== -1) {
this.queue.splice(index2, 1);
reject(new Error("Operation aborted"));
}
}, { once: true });
}
this.queue.push({
fn: async () => {
try {
if (signal?.aborted) {
throw new Error("Operation aborted");
}
const result = await fn();
resolve2(result);
return result;
} catch (error) {
reject(error);
throw error;
}
},
resolve: resolve2,
reject,
signal
});
});
}
async processQueue() {
if (this.executing || this.queue.length === 0 || this.poisoned) {
return;
}
const nextItem = this.queue.shift();
if (!nextItem)
return;
if (nextItem.signal?.aborted) {
nextItem.reject(new Error("Operation aborted"));
this.processQueue();
return;
}
this.executing = true;
try {
await nextItem.fn();
} catch (error) {
this.poisoned = true;
this.poisonError = error;
this.clearQueue(error);
} finally {
this.executing = false;
if (!this.poisoned) {
this.processQueue();
}
}
}
clearQueue(error) {
for (const item of this.queue) {
item.reject(error);
}
this.queue = [];
}
};
GuardToolCallController = class {
/**
* Don't construct this object yourself.
*/
constructor(toolCallRequest, tool, resultContainer) {
this.toolCallRequest = toolCallRequest;
this.tool = tool;
this.resultContainer = resultContainer;
this.allow = () => {
this.assertNoResultYet("allow", getCurrentStack(1));
this.resultContainer[0] = { type: "allow" };
};
this.allowAndOverrideParameters = (newParameters) => {
this.assertNoResultYet("allowAndOverrideParameters", getCurrentStack(1));
this.resultContainer[0] = { type: "allowAndOverrideParameters", parameters: newParameters };
};
this.deny = (reason) => {
this.assertNoResultYet("deny", getCurrentStack(1));
this.resultContainer[0] = { type: "deny", reason };
};
}
assertNoResultYet(calledMethodName, stack) {
if (this.resultContainer[0] === null) {
return;
}
throw makeTitledPrettyError(`Cannot call ${calledMethodName} after a result has been set`, text`
This tool call guard has already set a result previously (${this.resultContainer[0].type}).
You cannot set a result more than once.
`, stack);
}
};
llmActBaseOptsSchema = external_exports.object({
onFirstToken: external_exports.function().optional(),
onPredictionFragment: external_exports.function().optional(),
onMessage: external_exports.function().optional(),
onRoundStart: external_exports.function().optional(),
onRoundEnd: external_exports.function().optional(),
onPredictionCompleted: external_exports.function().optional(),
onPromptProcessingProgress: external_exports.function().optional(),
onToolCallRequestStart: external_exports.function().optional(),
onToolCallRequestNameReceived: external_exports.function().optional(),
onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(),
onToolCallRequestEnd: external_exports.function().optional(),
onToolCallRequestFinalized: external_exports.function().optional(),
onToolCallRequestFailure: external_exports.function().optional(),
onToolCallRequestDequeued: external_exports.function().optional(),
guardToolCall: external_exports.function().optional(),
handleInvalidToolRequest: external_exports.function().optional(),
maxPredictionRounds: external_exports.number().int().min(1).optional(),
signal: external_exports.instanceof(AbortSignal).optional(),
allowParallelToolExecution: external_exports.boolean().optional()
});
defaultHandleInvalidToolRequest = (error, request) => {
if (request) {
return error.message;
}
throw error;
};
PredictionResult = class {
constructor(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig) {
this.content = content;
this.reasoningContent = reasoningContent;
this.nonReasoningContent = nonReasoningContent;
this.stats = stats;
this.modelInfo = modelInfo;
this.roundIndex = roundIndex;
this.loadConfig = loadConfig;
this.predictionConfig = predictionConfig;
}
};
StructuredPredictionResult = class extends PredictionResult {
constructor(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig, parsed) {
super(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig);
this.parsed = parsed;
}
};
OngoingPrediction = class _OngoingPrediction extends StreamablePromise {
async collect(fragments) {
const content = fragments.map(({ content: content2 }) => content2).join("");
const reasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "reasoning").map(({ content: content2 }) => content2).join("");
const nonReasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "none").map(({ content: content2 }) => content2).join("");
if (this.stats === null) {
throw new Error("Stats should not be null");
}
if (this.modelInfo === null) {
throw new Error("Model info should not be null");
}
if (this.loadModelConfig === null) {
throw new Error("Load model config should not be null");
}
if (this.predictionConfig === null) {
throw new Error("Prediction config should not be null");
}
if (this.parser === null) {
return new PredictionResult(
content,
reasoningContent,
nonReasoningContent,
this.stats,
this.modelInfo,
// Currently, OngoingPrediction is only used with single round predictions. Thus always
// use roundIndex 0.
/* roundIndex */
0,
this.loadModelConfig,
this.predictionConfig
);
} else {
return new StructuredPredictionResult(
content,
reasoningContent,
nonReasoningContent,
this.stats,
this.modelInfo,
// Currently, OngoingPrediction is only used with single round predictions. Thus always
// use roundIndex 0.
/* predictionIndex */
0,
this.loadModelConfig,
this.predictionConfig,
this.parser(content)
);
}
}
constructor(onCancel, parser) {
super();
this.onCancel = onCancel;
this.parser = parser;
this.stats = null;
this.modelInfo = null;
this.loadModelConfig = null;
this.predictionConfig = null;
}
/** @internal */
static create(onCancel, parser) {
const ongoingPrediction = new _OngoingPrediction(onCancel, parser);
const finished2 = (stats, modelInfo, loadModelConfig, predictionConfig) => {
ongoingPrediction.stats = stats;
ongoingPrediction.modelInfo = modelInfo;
ongoingPrediction.loadModelConfig = loadModelConfig;
ongoingPrediction.predictionConfig = predictionConfig;
ongoingPrediction.finished();
};
const failed = (error) => ongoingPrediction.finished(error);
const push = (fragment2) => ongoingPrediction.push(fragment2);
return { ongoingPrediction, finished: finished2, failed, push };
}
/**
* Get the final prediction results. If you have been streaming the results, awaiting on this
* method will take no extra effort, as the results are already available in the internal buffer.
*
* Example:
*
* ```typescript
* const prediction = model.complete("When will The Winds of Winter be released?");
* for await (const { content } of prediction) {
* process.stdout.write(content);
* }
* const result = await prediction.result();
* console.log(result.stats);
* ```
*
* Technically, awaiting on this method is the same as awaiting on the instance itself:
*
* ```typescript
* await prediction.result();
*
* // Is the same as:
*
* await prediction;
* ```
*/
async result() {
return await this;
}
/**
* Cancels the prediction. This will stop the prediction with stop reason `userStopped`. See
* {@link LLMPredictionStopReason} for other reasons that a prediction might stop.
*/
async cancel() {
this.onCancel();
}
};
llmPredictionOptsSchema = llmPredictionConfigInputSchema.extend({
onPromptProcessingProgress: external_exports.function().optional(),
onFirstToken: external_exports.function().optional(),
onPredictionFragment: external_exports.function().optional(),
onToolCallRequestStart: external_exports.function().optional(),
onToolCallRequestNameReceived: external_exports.function().optional(),
onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(),
onToolCallRequestEnd: external_exports.function().optional(),
onToolCallRequestFailure: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional(),
preset: external_exports.string().optional()
});
llmRespondOptsSchema = llmPredictionOptsSchema.extend({
onMessage: external_exports.function().optional(),
onToolCallRequestStart: external_exports.function().optional(),
onToolCallRequestNameReceived: external_exports.function().optional(),
onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(),
onToolCallRequestEnd: external_exports.function().optional(),
onToolCallRequestFailure: external_exports.function().optional()
});
llmActionOptsSchema = llmPredictionConfigInputSchema.extend(llmActBaseOptsSchema.shape).extend({
preset: external_exports.string().optional()
});
noFormattingTemplate = text`
{% for message in messages %}{{ message['content'] }}{% endfor %}
`;
LLMDynamicHandle = class extends DynamicHandle {
/**
* Don't construct this on your own. Use {@link LLMNamespace#model} or
* {@link LLMNamespace#createDynamicHandle} instead.
*
* @internal
*/
constructor(port2, specifier, validator2, logger2 = new SimpleLogger(`LLMModel`)) {
super(port2, specifier);
this.validator = validator2;
this.logger = logger2;
this.internalKVConfigStack = { layers: [] };
this.internalIgnoreServerSessionConfig = void 0;
}
/** @internal */
internalPredict(history, predictionConfigStack, cancelEvent, extraOpts, onFragment, onFinished, onError) {
let finished2 = false;
let firstTokenTriggered = false;
let currentCallId = null;
let receivedEagerToolNameReporting = false;
let receivedToolArgumentsStreaming = false;
const channel = this.port.createChannel("predict", {
modelSpecifier: this.specifier,
history,
predictionConfigStack,
fuzzyPresetIdentifier: extraOpts.preset,
ignoreServerSessionConfig: this.internalIgnoreServerSessionConfig
}, (message) => {
switch (message.type) {
case "fragment": {
if (!firstTokenTriggered) {
firstTokenTriggered = true;
safeCallCallback(this.logger, "onFirstToken", extraOpts.onFirstToken, []);
}
safeCallCallback(this.logger, "onFragment", extraOpts.onPredictionFragment, [
message.fragment
]);
onFragment(message.fragment);
break;
}
case "promptProcessingProgress": {
safeCallCallback(this.logger, "onPromptProcessingProgress", extraOpts.onPromptProcessingProgress, [message.progress]);
break;
}
case "toolCallGenerationStart": {
if (currentCallId === null) {
currentCallId = 0;
} else {
currentCallId++;
}
receivedEagerToolNameReporting = false;
receivedToolArgumentsStreaming = false;
safeCallCallback(this.logger, "onToolCallGenerationStart", extraOpts.onToolCallRequestStart, [currentCallId, { toolCallId: message.toolCallId }]);
break;
}
case "toolCallGenerationNameReceived": {
receivedEagerToolNameReporting = true;
safeCallCallback(this.logger, "onToolCallGenerationNameReceived", extraOpts.onToolCallRequestNameReceived, [currentCallId ?? -1, message.name]);
break;
}
case "toolCallGenerationArgumentFragmentGenerated": {
receivedToolArgumentsStreaming = true;
safeCallCallback(this.logger, "onToolCallGenerationArgumentFragmentGenerated", extraOpts.onToolCallRequestArgumentFragmentGenerated, [currentCallId ?? -1, message.content]);
break;
}
case "toolCallGenerationEnd": {
if (!receivedEagerToolNameReporting) {
safeCallCallback(this.logger, "onToolCallGenerationNameReceived", extraOpts.onToolCallRequestNameReceived, [currentCallId ?? -1, message.toolCallRequest.name]);
}
if (!receivedToolArgumentsStreaming) {
safeCallCallback(this.logger, "onToolCallGenerationArgumentFragmentGenerated", extraOpts.onToolCallRequestArgumentFragmentGenerated, [
currentCallId ?? -1,
JSON.stringify(message.toolCallRequest.arguments ?? {}, null, 2)
]);
}
safeCallCallback(this.logger, "onToolCallGenerationEnd", extraOpts.onToolCallRequestEnd, [
currentCallId ?? -1,
{ toolCallRequest: message.toolCallRequest, rawContent: message.rawContent }
]);
break;
}
case "toolCallGenerationFailed": {
const toolCallRequestError = new ToolCallRequestError(fromSerializedError(message.error).message, message.rawContent);
safeCallCallback(this.logger, "onToolCallGenerationFailed", extraOpts.onToolCallRequestFailure, [currentCallId ?? -1, toolCallRequestError]);
break;
}
case "success": {
finished2 = true;
onFinished(message.stats, message.modelInfo, message.loadModelConfig, message.predictionConfig);
break;
}
}
}, { stack: getCurrentStack(2) });
cancelEvent.subscribeOnce(() => {
if (finished2) {
return;
}
channel.send({ type: "cancel" });
});
channel.onError.subscribeOnce(onError);
}
predictionConfigInputToKVConfig(config) {
let structuredField = void 0;
if (typeof config.structured?.parse === "function") {
structuredField = {
type: "json",
jsonSchema: zodToJsonSchema(config.structured)
};
} else {
structuredField = config.structured;
}
const convertedConfig = {
...config,
structured: structuredField
};
return llmPredictionConfigToKVConfig(convertedConfig);
}
createZodParser(zodSchema) {
return (content) => {
try {
return zodSchema.parse(JSON.parse(content));
} catch (e9) {
throw new Error("Failed to parse structured output: " + JSON.stringify(content), {
cause: e9
});
}
};
}
/**
* Use the loaded model to predict text.
*
* This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a
* promise (if you only care about the final result) or as an async iterable (if you want to
* stream the results as they are being generated).
*
* Example usage as a promise (Resolves to a {@link PredictionResult}):
*
* ```typescript
* const result = await model.complete("When will The Winds of Winter be released?");
* console.log(result.content);
* ```
*
* Or
*
* ```typescript
* model.complete("When will The Winds of Winter be released?")
* .then(result =\> console.log(result.content))
* .catch(error =\> console.error(error));
* ```
*
* Example usage as an async iterable (streaming):
*
* ```typescript
* for await (const { content } of model.complete("When will The Winds of Winter be released?")) {
* process.stdout.write(content);
* }
* ```
*
* If you wish to stream the result, but also getting the final prediction results (for example,
* you wish to get the prediction stats), you can use the following pattern:
*
* ```typescript
* const prediction = model.complete("When will The Winds of Winter be released?");
* for await (const { content } of prediction) {
* process.stdout.write(content);
* }
* const result = await prediction.result();
* console.log(result.stats);
* ```
*
* @param prompt - The prompt to use for prediction.
* @param opts - Options for the prediction.
*/
complete(prompt, opts = {}) {
const stack = getCurrentStack(1);
[prompt, opts] = this.validator.validateMethodParamsOrThrow("model", "complete", ["prompt", "opts"], [external_exports.string(), llmPredictionOptsSchema], [prompt, opts], stack);
const [config, extraOpts] = splitPredictionOpts(opts);
const [cancelEvent, emitCancelEvent] = BufferedEvent.create();
if (extraOpts.signal !== void 0) {
if (extraOpts.signal.aborted) {
emitCancelEvent();
} else {
extraOpts.signal.addEventListener("abort", () => {
emitCancelEvent();
}, { once: true });
}
}
const zodSchemaParseResult = zodSchemaSchema.safeParse(config.structured);
const { ongoingPrediction, finished: finished2, failed, push } = OngoingPrediction.create(emitCancelEvent, !zodSchemaParseResult.success ? null : this.createZodParser(zodSchemaParseResult.data));
this.internalPredict(this.resolveCompletionContext(prompt), {
layers: [
...this.internalKVConfigStack.layers,
{
layerName: "apiOverride",
config: this.predictionConfigInputToKVConfig({
// If the user did not specify `stopStrings`, we default to an empty array. This is to
// prevent the model from using the value set in the preset.
stopStrings: [],
...config
})
},
{
layerName: "completeModeFormatting",
config: llmSharedPredictionConfigSchematics.buildPartialConfig({
promptTemplate: {
type: "jinja",
jinjaPromptTemplate: {
template: noFormattingTemplate
},
stopStrings: []
}
})
}
]
}, cancelEvent, extraOpts, (fragment2) => push(fragment2), (stats, modelInfo, loadModelConfig, predictionConfig) => finished2(stats, modelInfo, loadModelConfig, predictionConfig), (error) => failed(error));
return ongoingPrediction;
}
resolveCompletionContext(contextInput) {
return {
messages: [
{
role: "user",
content: [{ type: "text", text: contextInput }]
}
]
};
}
/**
* Use the loaded model to generate a response based on the given history.
*
* This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a
* promise (if you only care about the final result) or as an async iterable (if you want to
* stream the results as they are being generated).
*
* Example usage as a promise (Resolves to a {@link PredictionResult}):
*
* ```typescript
* const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }];
* const result = await model.respond(history);
* console.log(result.content);
* ```
*
* Or
*
* ```typescript
* const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }];
* model.respond(history)
* .then(result => console.log(result.content))
* .catch(error => console.error(error));
* ```
*
* Example usage as an async iterable (streaming):
*
* ```typescript
* const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }];
* for await (const { content } of model.respond(history)) {
* process.stdout.write(content);
* }
* ```
*
* If you wish to stream the result, but also getting the final prediction results (for example,
* you wish to get the prediction stats), you can use the following pattern:
*
* ```typescript
* const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }];
* const prediction = model.respond(history);
* for await (const { content } of prediction) {
* process.stdout.write(content);
* }
* const result = await prediction;
* console.log(result.stats);
* ```
*
* @param chat - The LLMChatHistory array to use for generating a response.
* @param opts - Options for the prediction.
*/
respond(chat, opts = {}) {
const stack = getCurrentStack(1);
[chat, opts] = this.validator.validateMethodParamsOrThrow("model", "respond", ["chat", "opts"], [chatHistoryLikeSchema, llmRespondOptsSchema], [chat, opts], stack);
const [cancelEvent, emitCancelEvent] = BufferedEvent.create();
const [config, predictionOpts, respondOpts] = splitRespondOpts(opts);
if (predictionOpts.signal !== void 0) {
if (predictionOpts.signal.aborted) {
emitCancelEvent();
} else {
predictionOpts.signal.addEventListener("abort", () => {
emitCancelEvent();
}, { once: true });
}
}
const zodSchemaParseResult = zodSchemaSchema.safeParse(config.structured);
const { ongoingPrediction, finished: finished2, failed, push } = OngoingPrediction.create(emitCancelEvent, !zodSchemaParseResult.success ? null : this.createZodParser(zodSchemaParseResult.data));
this.internalPredict(accessMaybeMutableInternals(Chat3.from(chat))._internalGetData(), addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig(config)), cancelEvent, predictionOpts, (fragment2) => push(fragment2), (stats, modelInfo, loadModelConfig, predictionConfig) => finished2(stats, modelInfo, loadModelConfig, predictionConfig), (error) => failed(error));
ongoingPrediction.then((result) => {
safeCallCallback(this.logger, "onMessage", respondOpts.onMessage, [
ChatMessage.create("assistant", result.content)
]);
}, () => {
});
return ongoingPrediction;
}
/**
* @param chat - The LLMChatHistory array to act from as the base
* @param tool - An array of tools that the model can use during the operation. You can create
* tools by using the `tool` function.
* @param opts - Additional options
*
* Example:
*
* ```
* import { LMStudioClient, tool } from "@lmstudio/sdk";
* import { z } from "zod";
*
* const client = new LMStudioClient();
* const model = await client.llm.model();
*
* const additionTool = tool({
* name: "add",
* description: "Add two numbers",
* parameters: {
* a: z.number(),
* b: z.number(),
* },
* implementation: ({ a, b }) => a + b,
* });
*
* await model.act("What is 1234 + 4321?", [additionTool], {
* onMessage: message => console.log(message.toString()),
* });
* ```
*/
async act(chat, tools, opts = {}) {
const startTime = performance.now();
const stack = getCurrentStack(1);
[chat, opts] = this.validator.validateMethodParamsOrThrow("model", "act", ["chat", "opts"], [chatHistoryLikeSchema, llmActionOptsSchema], [chat, opts], stack);
const [config, { preset, ...baseOpts }] = splitActOpts(opts);
if (config.structured !== void 0 && config.structured.type !== "none" && tools.length > 0) {
throw makePrettyError("Structured output is currently not supported in .act() when there are tools.", stack);
}
if (config.structured !== void 0 && config.structured.parse !== void 0) {
throw makePrettyError("zod schema is not supported in .act().", stack);
}
if (config.rawTools !== void 0) {
throw makePrettyError("`rawTools` is not supported in act. Use `tools` instead", stack);
}
let rawTools;
if (tools.length === 0) {
rawTools = { type: "none" };
} else {
rawTools = {
type: "toolArray",
tools: tools.map(toolToLLMTool)
};
}
const configWithTools = addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig({
...config,
rawTools
}));
const configWithoutTools = addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig({
...config,
rawTools: { type: "none" }
}));
return await internalAct(
chat,
tools,
baseOpts,
stack,
this.logger,
startTime,
// Implementation of the prediction function. This performs the prediction by creating a
// predict channel and redirect the messages to the appropriate handlers.
async ({ allowTools, history, signal, handleFragment, handlePromptProcessingProgress, handleToolCallGenerationStart, handleToolCallGenerationNameReceived, handleToolCallGenerationArgumentFragmentGenerated, handleToolCallGenerationEnd, handleToolCallGenerationFailed, handlePredictionEnd, handleError }) => {
const channel = this.port.createChannel("predict", {
modelSpecifier: this.specifier,
history,
predictionConfigStack: allowTools ? configWithTools : configWithoutTools,
fuzzyPresetIdentifier: preset,
ignoreServerSessionConfig: this.internalIgnoreServerSessionConfig
}, (message) => {
const messageType = message.type;
switch (messageType) {
case "fragment": {
handleFragment(message.fragment);
break;
}
case "promptProcessingProgress": {
handlePromptProcessingProgress(message.progress);
break;
}
case "toolCallGenerationStart": {
handleToolCallGenerationStart(message.toolCallId);
break;
}
case "toolCallGenerationNameReceived": {
handleToolCallGenerationNameReceived(message.name);
break;
}
case "toolCallGenerationArgumentFragmentGenerated": {
handleToolCallGenerationArgumentFragmentGenerated(message.content);
break;
}
case "toolCallGenerationEnd": {
handleToolCallGenerationEnd(message.toolCallRequest, message.rawContent);
break;
}
case "toolCallGenerationFailed": {
handleToolCallGenerationFailed(fromSerializedError(message.error), message.rawContent);
break;
}
case "success": {
handlePredictionEnd({
stats: message.stats,
modelInfo: message.modelInfo,
loadModelConfig: message.loadModelConfig,
predictionConfig: message.predictionConfig
});
break;
}
}
}, { stack });
if (signal.aborted) {
channel.send({ type: "cancel" });
} else {
signal.addEventListener("abort", () => {
channel.send({ type: "cancel" });
}, { once: true });
}
channel.onError.subscribeOnce(handleError);
},
({ endPacket, content, nonReasoningContent, reasoningContent, predictionsPerformed }) => {
return new PredictionResult(content, reasoningContent, nonReasoningContent, endPacket.stats, endPacket.modelInfo, predictionsPerformed, endPacket.loadModelConfig, endPacket.predictionConfig);
}
);
}
async getContextLength() {
const stack = getCurrentStack(1);
const loadConfig = await this.getLoadConfig(stack);
return llmSharedLoadConfigSchematics.access(loadConfig, "contextLength");
}
async applyPromptTemplate(history, opts = {}) {
const stack = getCurrentStack(1);
[history, opts] = this.validator.validateMethodParamsOrThrow("model", "applyPromptTemplate", ["history", "opts"], [chatHistoryLikeSchema, llmApplyPromptTemplateOptsSchema], [history, opts], stack);
return (await this.port.callRpc("applyPromptTemplate", {
specifier: this.specifier,
history: accessMaybeMutableInternals(Chat3.from(history))._internalGetData(),
predictionConfigStack: this.internalKVConfigStack,
opts
}, {
stack
})).formatted;
}
async tokenize(inputString) {
const stack = getCurrentStack(1);
inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack);
if (Array.isArray(inputString)) {
return (await Promise.all(inputString.map((s6) => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s6 }, { stack })))).map((r8) => r8.tokens);
} else {
return (await this.port.callRpc("tokenize", {
specifier: this.specifier,
inputString
}, { stack })).tokens;
}
}
async countTokens(inputString) {
const stack = getCurrentStack(1);
inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", external_exports.string(), inputString, stack);
return (await this.port.callRpc("countTokens", {
specifier: this.specifier,
inputString
}, { stack })).tokenCount;
}
/**
* Starts to eagerly preload a draft model. This is useful when you want a draft model to be ready
* for speculative decoding.
*
* Preloading is done on a best-effort basis and may not always succeed. It is not guaranteed that
* the draft model is actually loaded when this method returns. Thus, this method should only be
* used as an optimization. The actual draft model used only depends on the parameter set when
* performing the prediction.
*/
async unstable_preloadDraftModel(draftModelKey) {
const stack = getCurrentStack(1);
draftModelKey = this.validator.validateMethodParamOrThrow("model", "unstable_preloadDraftModel", "draftModelKey", external_exports.string(), draftModelKey, stack);
await this.port.callRpc("preloadDraftModel", { specifier: this.specifier, draftModelKey }, { stack });
}
};
LLM = class extends LLMDynamicHandle {
/** @internal */
constructor(llmPort, info2, validator2, logger2 = new SimpleLogger(`LLM`)) {
const specifier = {
type: "instanceReference",
instanceReference: info2.instanceReference
};
super(llmPort, specifier, validator2, logger2);
this.identifier = info2.identifier;
this.path = info2.path;
this.modelKey = info2.modelKey;
this.format = info2.format;
this.displayName = info2.displayName;
this.sizeBytes = info2.sizeBytes;
this.vision = info2.vision;
this.trainedForToolUse = info2.trainedForToolUse;
}
async unload() {
const stack = getCurrentStack(1);
await this.port.callRpc("unloadModel", { identifier: this.identifier }, { stack });
}
async getModelInfo() {
const info2 = await super.getModelInfo();
if (info2 === void 0) {
const stack = getCurrentStack(1);
throw makePrettyError("This model has already been unloaded", stack);
}
return info2;
}
};
LLMNamespace = class extends ModelNamespace {
constructor() {
super(...arguments);
this.namespace = "llm";
this.defaultLoadConfig = {};
this.loadModelConfigSchema = llmLoadModelConfigSchema;
}
/** @internal */
loadConfigToKVConfig(config) {
return llmLlamaMoeLoadConfigSchematics.buildPartialConfig({
"contextLength": config.contextLength,
"llama.evalBatchSize": config.evalBatchSize,
"llama.acceleration.offloadRatio": config.gpu?.ratio,
"numCpuExpertLayersRatio": config.gpu?.numCpuExpertLayersRatio,
"load.gpuSplitConfig": convertGPUSettingToGPUSplitConfig(config.gpu),
"llama.flashAttention": config.flashAttention,
"llama.ropeFrequencyBase": numberToCheckboxNumeric(config.ropeFrequencyBase, 0, 0),
"llama.ropeFrequencyScale": numberToCheckboxNumeric(config.ropeFrequencyScale, 0, 0),
"llama.keepModelInMemory": config.keepModelInMemory,
"seed": numberToCheckboxNumeric(config.seed, -1, 0),
"llama.useFp16ForKVCache": config.useFp16ForKVCache,
"llama.tryMmap": config.tryMmap,
"numExperts": config.numExperts,
"llama.kCacheQuantizationType": cacheQuantizationTypeToCheckbox({
value: config.llamaKCacheQuantizationType,
falseDefault: "f16"
}),
"llama.vCacheQuantizationType": cacheQuantizationTypeToCheckbox({
value: config.llamaVCacheQuantizationType,
falseDefault: "f16"
})
});
}
/** @internal */
createDomainSpecificModel(port2, info2, validator2, logger2) {
return new LLM(port2, info2, validator2, logger2);
}
/** @internal */
createDomainDynamicHandle(port2, specifier, validator2, logger2) {
return new LLMDynamicHandle(port2, specifier, validator2, logger2);
}
};
GeneratorPredictionResult = class {
constructor(content, reasoningContent, nonReasoningContent, pluginIdentifier) {
this.content = content;
this.reasoningContent = reasoningContent;
this.nonReasoningContent = nonReasoningContent;
this.pluginIdentifier = pluginIdentifier;
}
};
OngoingGeneratorPrediction = class _OngoingGeneratorPrediction extends StreamablePromise {
async collect(fragments) {
const content = fragments.map(({ content: content2 }) => content2).join("");
const reasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "reasoning").map(({ content: content2 }) => content2).join("");
const nonReasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "none").map(({ content: content2 }) => content2).join("");
return new GeneratorPredictionResult(content, reasoningContent, nonReasoningContent, this.pluginIdentifier);
}
constructor(pluginIdentifier, onCancel) {
super();
this.pluginIdentifier = pluginIdentifier;
this.onCancel = onCancel;
}
/** @internal */
static create(pluginIdentifier, onCancel) {
const ongoingPrediction = new _OngoingGeneratorPrediction(pluginIdentifier, onCancel);
const finished2 = () => ongoingPrediction.finished();
const failed = (error) => ongoingPrediction.finished(error);
const push = (fragment2) => ongoingPrediction.push(fragment2);
return { ongoingPrediction, finished: finished2, failed, push };
}
/**
* Get the final prediction results. If you have been streaming the results, awaiting on this
* method will take no extra effort, as the results are already available in the internal buffer.
*
* Example:
*
* ```typescript
* const prediction = generator.complete("When will The Winds of Winter be released?");
* for await (const { content } of prediction) {
* process.stdout.write(content);
* }
* const result = await prediction.result();
* console.log(result.stats);
* ```
*
* Technically, awaiting on this method is the same as awaiting on the instance itself:
*
* ```typescript
* await prediction.result();
*
* // Is the same as:
*
* await prediction;
* ```
*/
async result() {
return await this;
}
/**
* Cancels the prediction.
*/
async cancel() {
this.onCancel();
}
};
llmGeneratorPredictionOptsSchema = external_exports.object({
onFirstToken: external_exports.function().optional(),
onPredictionFragment: external_exports.function().optional(),
onMessage: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional(),
pluginConfig: kvConfigSchema.optional(),
workingDirectory: external_exports.string().optional()
});
llmGeneratorActOptsSchema = llmActBaseOptsSchema.extend({
pluginConfig: kvConfigSchema.optional(),
workingDirectory: external_exports.string().optional()
});
LLMGeneratorHandle = class {
/**
* Don't use this method directly, use {@link LLMNamespace#createGeneratorHandle} instead.
*
* @internal
*/
constructor(port2, pluginIdentifier, validator2, associatedPredictionProcess, logger2 = new SimpleLogger(`LLMGeneratorHandle`)) {
this.port = port2;
this.pluginIdentifier = pluginIdentifier;
this.validator = validator2;
this.associatedPredictionProcess = associatedPredictionProcess;
this.logger = logger2;
this.identifier = this.pluginIdentifier;
}
getPluginConfigSpecifier(userSuppliedPluginConfig, userSuppliedWorkingDirectory, stack) {
if (this.associatedPredictionProcess === null) {
return {
type: "direct",
config: userSuppliedPluginConfig ?? emptyKVConfig,
workingDirectoryPath: userSuppliedWorkingDirectory ?? void 0
};
}
if (userSuppliedPluginConfig !== void 0) {
throw makeTitledPrettyError("Cannot use plugin config with prediction process", text`
You cannot provide a plugin config to the generator handle when it is associated with a
prediction process. The plugin config that was configured for the prediction process will
be used instead.
If you want to use a different plugin config, you will need to create a separate
GeneratorHandle instead.
`, stack);
}
if (userSuppliedWorkingDirectory !== void 0) {
throw makeTitledPrettyError("Cannot use working directory with prediction process", text`
You cannot provide a working directory to the generator handle when it is associated with
a prediction process. The working directory that was configured for the prediction process
will be used instead.
If you want to use a different working directory, you will need to create a separate
GeneratorHandle instead.
`, stack);
}
return {
type: "predictionProcess",
pci: this.associatedPredictionProcess.pci,
token: this.associatedPredictionProcess.token
};
}
/**
* Use the generator to produce a response based on the given history.
*/
respond(chat, opts = {}) {
const stack = getCurrentStack(1);
[chat, opts] = this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle", "respond", ["chat", "opts"], [chatHistoryLikeSchema, llmGeneratorPredictionOptsSchema], [chat, opts], stack);
const { onFirstToken, onPredictionFragment, onMessage, signal, pluginConfig, workingDirectory } = opts;
let resolved = false;
let firstTokenTriggered = false;
const cancelEvent = new CancelEvent();
if (signal !== void 0) {
if (signal.aborted) {
cancelEvent.cancel();
} else {
signal.addEventListener("abort", () => cancelEvent.cancel(), { once: true });
}
}
const { ongoingPrediction, finished: finished2, failed, push } = OngoingGeneratorPrediction.create(this.pluginIdentifier, () => {
cancelEvent.cancel();
});
const channel = this.port.createChannel("generateWithGenerator", {
pluginIdentifier: this.pluginIdentifier,
pluginConfigSpecifier: this.getPluginConfigSpecifier(pluginConfig, workingDirectory, stack),
tools: [],
history: accessMaybeMutableInternals(Chat3.from(chat))._internalGetData()
}, (message) => {
const messageType = message.type;
switch (messageType) {
case "fragment": {
if (!firstTokenTriggered) {
firstTokenTriggered = true;
safeCallCallback(this.logger, "onFirstToken", onFirstToken, []);
}
safeCallCallback(this.logger, "onPredictionFragment", onPredictionFragment, [
message.fragment
]);
push(message.fragment);
break;
}
case "success": {
resolved = true;
finished2();
break;
}
}
}, { stack });
channel.onError.subscribeOnce((error) => {
if (resolved) {
return;
}
resolved = true;
failed(error);
});
cancelEvent.subscribeOnce(() => {
if (resolved) {
return;
}
channel.send({ type: "cancel" });
});
ongoingPrediction.then((result) => {
safeCallCallback(this.logger, "onMessage", onMessage, [
ChatMessage.create("assistant", result.content)
]);
}, () => {
});
return ongoingPrediction;
}
async act(chat, tools, opts = {}) {
const startTime = performance.now();
const stack = getCurrentStack(1);
[chat, opts] = this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle", "act", ["chat", "opts"], [chatHistoryLikeSchema, llmGeneratorActOptsSchema], [chat, opts], stack);
const { pluginConfig, workingDirectory, ...baseOpts } = opts;
const toolDefinitions = tools.map(toolToLLMTool);
return await internalAct(
chat,
tools,
baseOpts,
stack,
this.logger,
startTime,
// Implementation of the prediction function. This performs the prediction by creating a
// predict channel and redirect the messages to the appropriate handlers.
async ({ allowTools, history, signal, handleFragment, handlePromptProcessingProgress, handleToolCallGenerationStart, handleToolCallGenerationNameReceived, handleToolCallGenerationArgumentFragmentGenerated, handleToolCallGenerationEnd, handleToolCallGenerationFailed, handlePredictionEnd, handleError }) => {
const channel = this.port.createChannel("generateWithGenerator", {
pluginIdentifier: this.pluginIdentifier,
pluginConfigSpecifier: this.getPluginConfigSpecifier(pluginConfig, workingDirectory, stack),
tools: allowTools ? toolDefinitions : [],
history
}, (message) => {
const messageType = message.type;
switch (messageType) {
case "fragment": {
handleFragment(message.fragment);
break;
}
case "promptProcessingProgress": {
handlePromptProcessingProgress(message.progress);
break;
}
case "toolCallGenerationStart": {
handleToolCallGenerationStart(message.toolCallId);
break;
}
case "toolCallGenerationNameReceived": {
handleToolCallGenerationNameReceived(message.name);
break;
}
case "toolCallGenerationArgumentFragmentGenerated": {
handleToolCallGenerationArgumentFragmentGenerated(message.content);
break;
}
case "toolCallGenerationEnd": {
handleToolCallGenerationEnd(message.toolCallRequest, void 0);
break;
}
case "toolCallGenerationFailed": {
handleToolCallGenerationFailed(
new Error("Tool call generation failed"),
// Placeholder error for now
void 0
);
break;
}
case "success": {
handlePredictionEnd(void 0);
break;
}
}
}, { stack });
if (signal.aborted) {
channel.send({ type: "cancel" });
} else {
signal.addEventListener("abort", () => {
channel.send({ type: "cancel" });
}, { once: true });
}
channel.onError.subscribeOnce(handleError);
},
({ content, nonReasoningContent, reasoningContent }) => new GeneratorPredictionResult(content, reasoningContent, nonReasoningContent, this.pluginIdentifier)
);
}
};
generatorSchema = external_exports.function();
BaseController = class {
constructor(client, abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath) {
this.client = client;
this.abortSignal = abortSignal;
this.pluginConfig = pluginConfig;
this.globalPluginConfig = globalPluginConfig;
this.workingDirectoryPath = workingDirectoryPath;
}
/**
* Gets the working directory for the current prediction. If your plugin produces files, you
* should aim to put them in this directory.
*/
getWorkingDirectory() {
if (this.workingDirectoryPath === null) {
throw new Error("This prediction process is not attached to a working directory.");
}
return this.workingDirectoryPath;
}
/**
* Get the per-chat config for the plugin. Takes in the configSchematics. You can get the
* values of fields like so:
*
* ```ts
* const config = ctl.getPluginConfig(configSchematics);
* const value = config.get("fieldKey");
* ```
*
* @remarks
*
* If you need to name the type of the returned value, use:
*
* `InferParsedConfig`.
*
* Example:
*
* ```ts
* function myFunction(config: InferParsedConfig) {
* // ...
* }
*
* myFunction(ctl.getPluginConfig(configSchematics));
* ```
*/
getPluginConfig(configSchematics) {
return configSchematics.parse(this.pluginConfig);
}
/**
* Get the application-wide config for the plugin. Takes in the globalConfigSchematics. You can
* get the values of fields like so:
*
* ```ts
* const config = ctl.getGlobalPluginConfig(globalConfigSchematics);
* const value = config.get("fieldKey");
* ```
*
* @remarks
*
* If you need to name the type of the returned value, use:
*
* `InferParsedConfig`.
*
* Example:
*
* ```ts
* function myFunction(config: InferParsedConfig) {
* // ...
* }
*
* myFunction(ctl.getGlobalPluginConfig(globalConfigSchematics));
* ```
*/
getGlobalPluginConfig(globalConfigSchematics2) {
return globalConfigSchematics2.parse(this.globalPluginConfig);
}
/**
* Provides a callback that will be called when the prediction is aborted. If the prediction is
* already aborted, the callback will be called immediately.
*
* You can also use {@link BaseController.abortSignal} if you are using an async function that
* supports abort signals.
*
* See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal for more information about
* abort signals.
*/
onAborted(callback2) {
if (this.abortSignal.aborted) {
callback2();
} else {
this.abortSignal.addEventListener("abort", callback2, { once: true });
}
}
};
GeneratorController = class extends BaseController {
/**
* @internal Do not construct this class yourself.
*/
constructor(client, pluginConfig, globalPluginConfig, workingDirectoryPath, abortSignal, toolDefinitions, connector, validator2) {
super(client, abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath);
this.toolDefinitions = toolDefinitions;
this.connector = connector;
this.validator = validator2;
}
/**
* Get the definitions of the tools available for this generation.
*/
getToolDefinitions() {
return this.toolDefinitions;
}
/**
* Use this function to report a text fragment has been generated.
*
* @param content - The content that has been generated.
* @param opts - Additional info about the generated content, such as how many tokens it contains.
* See {@link LLMPredictionFragmentInputOpts} for more info. All the fields are optional.
*/
fragmentGenerated(content, opts = {}) {
const stack = getCurrentStack(1);
[content, opts] = this.validator.validateMethodParamsOrThrow("GeneratorController", "fragmentGenerated", ["content", "opts"], [external_exports.string(), llmPredictionFragmentInputOptsSchema], [content, opts], stack);
this.connector.fragmentGenerated(content, opts);
}
/**
* Use this function to report that a tool call generation has started. Each
* `toolCallGenerationStarted` must be paired up with a `toolCallGenerationEnded` call for
* successfully generated tool calls, or a `toolCallGenerationFailed` call for
* failed tool calls.
*/
toolCallGenerationStarted({ toolCallId } = {}) {
this.connector.toolCallGenerationStarted(toolCallId);
}
/**
* Use this function to report that the name of the tool call has been generated. This function
* should only be called once for each `toolCallGenerationStarted`.
*
* @param toolName - The name of the tool that has been generated.
*/
toolCallGenerationNameReceived(toolName) {
const stack = getCurrentStack(1);
toolName = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationNameReceived", "toolName", external_exports.string(), toolName, stack);
this.connector.toolCallGenerationNameReceived(toolName);
}
/**
* Use this function to report that a new argument fragment has been generated for the tool call.
* This function can be called multiple times for each `toolCallGenerationStarted`.
*
* @param content - The new fragment that has been generated for the tool call.
*/
toolCallGenerationArgumentFragmentGenerated(content) {
const stack = getCurrentStack(1);
content = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationArgumentFragmentGenerated", "content", external_exports.string(), content, stack);
this.connector.toolCallGenerationArgumentFragmentGenerated(content);
}
/**
* Use this function to report that a tool call generation has successfully ended. This function
* should only be called after a `toolCallGenerationStarted` call.
*/
toolCallGenerationEnded(toolCallRequest) {
const stack = getCurrentStack(1);
toolCallRequest = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationEnded", "toolCallRequest", toolCallRequestSchema, toolCallRequest, stack);
this.connector.toolCallGenerationEnded(toolCallRequest);
}
/**
* Use this function to report that a tool call generation has failed. This function should only
* be called after a `toolCallGenerationStarted` call.
*
* @param error - The error that occurred during the tool call generation.
*/
toolCallGenerationFailed(error) {
const stack = getCurrentStack(1);
error = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationFailed", "error", external_exports.instanceof(Error), error, stack);
this.connector.toolCallGenerationFailed(error);
}
};
__addDisposableResource$1 = globalThis && globalThis.__addDisposableResource || function(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose, inner2;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner2 = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner2) dispose = function() {
try {
inner2.call(this);
} catch (e9) {
return Promise.reject(e9);
}
};
env.stack.push({ value, dispose, async });
} else if (async) {
env.stack.push({ async: true });
}
return value;
};
__disposeResources$1 = globalThis && globalThis.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
return function(env) {
function fail(e9) {
env.error = env.hasError ? new SuppressedError2(e9, env.error, "An error was suppressed during disposal.") : e9;
env.hasError = true;
}
var r8, s6 = 0;
function next() {
while (r8 = env.stack.pop()) {
try {
if (!r8.async && s6 === 1) return s6 = 0, env.stack.push(r8), Promise.resolve().then(next);
if (r8.dispose) {
var result = r8.dispose.call(r8.value);
if (r8.async) return s6 |= 2, Promise.resolve(result).then(next, function(e9) {
fail(e9);
return next();
});
} else s6 |= 1;
} catch (e9) {
fail(e9);
}
}
if (s6 === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
};
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
var e9 = new Error(message);
return e9.name = "SuppressedError", e9.error = error, e9.suppressed = suppressed, e9;
});
ProcessingConnector = class {
constructor(pluginsPort, abortSignal, processingContextIdentifier, token, logger2) {
this.pluginsPort = pluginsPort;
this.abortSignal = abortSignal;
this.processingContextIdentifier = processingContextIdentifier;
this.token = token;
this.logger = logger2;
}
handleUpdate(update) {
this.pluginsPort.callRpc("processingHandleUpdate", {
pci: this.processingContextIdentifier,
token: this.token,
update
}).catch((error) => {
this.logger.error("Failed to send update", error);
});
}
async handleRequest(request) {
const { response } = await this.pluginsPort.callRpc("processingHandleRequest", {
pci: this.processingContextIdentifier,
token: this.token,
request
});
return response;
}
async pullHistory(includeCurrent) {
const chatHistoryData = await this.pluginsPort.callRpc("processingPullHistory", {
pci: this.processingContextIdentifier,
token: this.token,
includeCurrent
});
return Chat3.createRaw(
chatHistoryData,
/* mutable */
false
).asMutableCopy();
}
async getOrLoadTokenSource() {
const result = await this.pluginsPort.callRpc("processingGetOrLoadTokenSource", {
pci: this.processingContextIdentifier,
token: this.token
});
return result.tokenSourceIdentifier;
}
async hasStatus() {
return await this.pluginsPort.callRpc("processingHasStatus", {
pci: this.processingContextIdentifier,
token: this.token
});
}
async needsNaming() {
return await this.pluginsPort.callRpc("processingNeedsNaming", {
pci: this.processingContextIdentifier,
token: this.token
});
}
async suggestName(name) {
await this.pluginsPort.callRpc("processingSuggestName", {
pci: this.processingContextIdentifier,
token: this.token,
name
});
}
};
ProcessingController = class extends BaseController {
/** @internal */
constructor(client, pluginConfig, globalPluginConfig, workingDirectoryPath, enabledPluginInfos, connector, config, shouldIncludeCurrentInHistory) {
super(client, connector.abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath);
this.enabledPluginInfos = enabledPluginInfos;
this.connector = connector;
this.config = config;
this.shouldIncludeCurrentInHistory = shouldIncludeCurrentInHistory;
this.processingControllerHandle = {
abortSignal: connector.abortSignal,
sendUpdate: (update) => {
connector.handleUpdate(update);
},
sendRequest: async (request) => {
const type = request.type;
const response = await connector.handleRequest(request);
if (response.type !== type) {
throw new Error(`Expected response type ${type}, but got ${response.type}. This is a bug.`);
}
return response;
}
};
}
sendUpdate(update) {
this.processingControllerHandle.sendUpdate(update);
}
/**
* Gets a mutable copy of the current history. The returned history is a copy, so mutating it will
* not affect the actual history. It is mutable for convenience reasons.
*
* - If you are a promptPreprocessor, this will not include the user message you are currently
* preprocessing.
* - If you are a prediction loop handler, this will include the user message, and can be fed into
* the {@link LLMDynamicHandle#respond} method directly.
*/
async pullHistory() {
return await this.connector.pullHistory(this.shouldIncludeCurrentInHistory);
}
createStatus(initialState) {
const id = createId();
this.sendUpdate({
type: "status.create",
id,
state: initialState
});
const statusController = new PredictionProcessStatusController(this.processingControllerHandle, initialState, id);
return statusController;
}
addCitations(arg) {
if (Array.isArray(arg)) {
for (const entry of arg) {
this.createCitationBlock(entry.content, {
fileName: entry.source.name,
fileIdentifier: entry.source.identifier
});
}
} else {
for (const entry of arg.entries) {
this.createCitationBlock(entry.content, {
fileName: entry.source.name,
fileIdentifier: entry.source.identifier
});
}
}
}
createCitationBlock(citedText, source) {
const id = createId();
this.sendUpdate({
type: "citationBlock.create",
id,
citedText,
...source
});
const citationBlockController = new PredictionProcessCitationBlockController(this.processingControllerHandle, id);
return citationBlockController;
}
/**
* @internal
*/
createDebugInfoBlock(debugInfo) {
const id = createId();
this.sendUpdate({
type: "debugInfoBlock.create",
id,
debugInfo
});
const debugInfoBlockController = new PredictionProcessDebugInfoBlockController(this.processingControllerHandle, id);
return debugInfoBlockController;
}
createContentBlock({ roleOverride, includeInContext = true, style, prefix, suffix } = {}) {
const id = createId();
this.sendUpdate({
type: "contentBlock.create",
id,
roleOverride,
includeInContext,
style,
prefix,
suffix
});
const contentBlockController = new PredictionProcessContentBlockController(this.processingControllerHandle, id, roleOverride ?? "assistant");
return contentBlockController;
}
debug(...messages) {
this.createDebugInfoBlock(concatenateDebugMessages(...messages));
}
/**
* Gets the token source associated with this prediction process (i.e. what the user has selected
* on the top navigation bar).
*
* The token source can either be a model or a generator plugin. In both cases, the returned
* object will contain a ".act" and a ".respond" method, which can be used to generate text.
*
* The token source is already pre-configured to use user's prediction config - you don't need to
* pass through any additional configuration.
*/
async tokenSource() {
const tokenSourceIdentifier = await this.connector.getOrLoadTokenSource();
const tokenSourceIdentifierType = tokenSourceIdentifier.type;
switch (tokenSourceIdentifierType) {
case "model": {
const model = await this.client.llm.model(tokenSourceIdentifier.identifier);
model.internalIgnoreServerSessionConfig = true;
model.internalKVConfigStack = {
layers: [
{
layerName: "conversationSpecific",
config: this.config
}
]
};
return model;
}
case "generator": {
const generator = this.client.plugins.createGeneratorHandleAssociatedWithPredictionProcess(tokenSourceIdentifier.pluginIdentifier, this.connector.processingContextIdentifier, this.connector.token);
return generator;
}
}
}
/**
* Sets the sender name for this message. The sender name shown above the message in the chat.
*/
async setSenderName(name) {
this.sendUpdate({
type: "setSenderName",
name
});
}
/**
* Throws an error if the prediction process has been aborted. Sprinkle this throughout your code
* to ensure that the prediction process is aborted as soon as possible.
*/
guardAbort() {
this.abortSignal.throwIfAborted();
}
/**
* Whether this prediction process has had any status.
*/
async hasStatus() {
return await this.connector.hasStatus();
}
/**
* Returns whether this conversation needs a name.
*/
async needsNaming() {
return await this.connector.needsNaming();
}
/**
* Suggests a name for this conversation.
*/
async suggestName(name) {
await this.connector.suggestName(name);
}
async requestConfirmToolCall({ callId, pluginIdentifier, name, parameters }) {
const { result } = await raceWithAbortSignal(this.processingControllerHandle.sendRequest({
type: "confirmToolCall",
callId,
pluginIdentifier,
name,
parameters
}), this.abortSignal);
const resultType = result.type;
switch (resultType) {
case "allow": {
return {
type: "allow",
toolArgsOverride: result.toolArgsOverride
};
}
case "deny": {
return {
type: "deny",
denyReason: result.denyReason
};
}
default: {
const exhaustiveCheck = resultType;
throw new Error(`Unexpected result type ${exhaustiveCheck}. This is a bug. Please report it.`);
}
}
}
createToolStatus(callId, initialStatus) {
const id = createId();
this.sendUpdate({
type: "toolStatus.create",
id,
callId,
state: {
status: initialStatus,
customStatus: "",
customWarnings: []
}
});
const toolStatusController = new PredictionProcessToolStatusController(this.processingControllerHandle, id, initialStatus);
return toolStatusController;
}
/**
* Starts a tool use session with tools available in the prediction process. Note, this method
* should be used with "Explicit Resource Management". That is, you should use it like so:
*
* ```typescript
* using toolUseSession = await ctl.startToolUseSession();
* // ^ Notice the `using` keyword here.
* ```
*
* If you do not `using`, you should call `toolUseSession[Symbol.dispose]()` after you are done.
*
* If you don't, lmstudio-js will close the session upon the end of the prediction step
* automatically. However, it is not recommended.
*
* @public
* @deprecated WIP
*/
async startToolUseSession() {
const identifiersOfPluginsWithTools = this.enabledPluginInfos.filter(({ hasToolsProvider }) => hasToolsProvider).map(({ identifier }) => identifier);
return await this.client.plugins.startToolUseSessionUsingPredictionProcess(
// We start a tool use session with all the plugins that have tools available
identifiersOfPluginsWithTools,
this.connector.processingContextIdentifier,
this.connector.token
);
}
};
PredictionProcessStatusController = class _PredictionProcessStatusController {
/** @internal */
constructor(handle, initialState, id, indentation = 0) {
this.handle = handle;
this.id = id;
this.indentation = indentation;
this.lastSubStatus = this;
this.lastState = initialState;
}
setText(text3) {
this.lastState.text = text3;
this.handle.sendUpdate({
type: "status.update",
id: this.id,
state: this.lastState
});
}
setState(state) {
this.lastState = state;
this.handle.sendUpdate({
type: "status.update",
id: this.id,
state
});
}
remove() {
this.handle.sendUpdate({
type: "status.remove",
id: this.id
});
}
getNestedLastSubStatusBlockId() {
let current2 = this.lastSubStatus;
while (current2 !== current2.lastSubStatus) {
current2 = current2.lastSubStatus;
}
return current2.id;
}
addSubStatus(initialState) {
const id = createId();
this.handle.sendUpdate({
type: "status.create",
id,
state: initialState,
location: {
type: "afterId",
id: this.getNestedLastSubStatusBlockId()
},
indentation: this.indentation + 1
});
const controller = new _PredictionProcessStatusController(this.handle, initialState, id, this.indentation + 1);
this.lastSubStatus = controller;
return controller;
}
};
PredictionProcessCitationBlockController = class {
/** @internal */
constructor(handle, id) {
this.handle = handle;
this.id = id;
}
};
PredictionProcessDebugInfoBlockController = class {
/** @internal */
constructor(handle, id) {
this.handle = handle;
this.id = id;
}
};
PredictionProcessContentBlockController = class {
/** @internal */
constructor(handle, id, role) {
this.handle = handle;
this.id = id;
this.role = role;
}
appendText(text3, { tokensCount, fromDraftModel, isStructural } = {}) {
if (this.role === "tool") {
throw new Error("Text cannot be appended to tool blocks.");
}
this.handle.sendUpdate({
type: "contentBlock.appendText",
id: this.id,
text: text3,
tokensCount,
fromDraftModel,
isStructural
});
}
appendToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier }) {
if (this.role !== "assistant") {
throw new Error(`Tool requests can only be appended to assistant blocks. This is a ${this.role} block.`);
}
this.handle.sendUpdate({
type: "contentBlock.appendToolRequest",
id: this.id,
callId,
toolCallRequestId,
name,
parameters,
pluginIdentifier
});
}
replaceToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier }) {
if (this.role !== "assistant") {
throw new Error(`Tool requests can only be replaced in assistant blocks. This is a ${this.role} block.`);
}
this.handle.sendUpdate({
type: "contentBlock.replaceToolRequest",
id: this.id,
callId,
toolCallRequestId,
name,
parameters,
pluginIdentifier
});
}
appendToolResult({ callId, toolCallRequestId, content }) {
if (this.role !== "tool") {
throw new Error(`Tool results can only be appended to tool blocks. This is a ${this.role} block.`);
}
this.handle.sendUpdate({
type: "contentBlock.appendToolResult",
id: this.id,
callId,
toolCallRequestId,
content
});
}
replaceText(text3) {
if (this.role === "tool") {
throw new Error("Text cannot be set in tool blocks.");
}
this.handle.sendUpdate({
type: "contentBlock.replaceText",
id: this.id,
text: text3
});
}
setStyle(style) {
this.handle.sendUpdate({
type: "contentBlock.setStyle",
id: this.id,
style
});
}
setPrefix(prefix) {
this.handle.sendUpdate({
type: "contentBlock.setPrefix",
id: this.id,
prefix
});
}
setSuffix(suffix) {
this.handle.sendUpdate({
type: "contentBlock.setSuffix",
id: this.id,
suffix
});
}
attachGenInfo(genInfo) {
this.handle.sendUpdate({
type: "contentBlock.attachGenInfo",
id: this.id,
genInfo
});
}
async pipeFrom(prediction) {
const env_1 = { stack: [], error: void 0, hasError: false };
try {
const cleaner = __addDisposableResource$1(env_1, new Cleaner(), false);
const abortListener = () => {
prediction.cancel();
};
this.handle.abortSignal.addEventListener("abort", abortListener);
cleaner.register(() => {
this.handle.abortSignal.removeEventListener("abort", abortListener);
});
for await (const { content } of prediction) {
this.appendText(content);
}
const result = await prediction;
this.attachGenInfo({
indexedModelIdentifier: result.modelInfo.path,
identifier: result.modelInfo.identifier,
loadModelConfig: result.loadConfig,
predictionConfig: result.predictionConfig,
stats: result.stats
});
this.handle.abortSignal.throwIfAborted();
return result;
} catch (e_1) {
env_1.error = e_1;
env_1.hasError = true;
} finally {
__disposeResources$1(env_1);
}
}
};
PredictionProcessToolStatusController = class {
/** @internal */
constructor(handle, id, initialStatus) {
this.handle = handle;
this.id = id;
this.customStatus = "";
this.customWarnings = [];
this.status = initialStatus;
}
updateState() {
this.handle.sendUpdate({
type: "toolStatus.update",
id: this.id,
state: {
status: this.status,
customStatus: this.customStatus,
customWarnings: this.customWarnings
}
});
}
setCustomStatusText(status) {
this.customStatus = status;
this.updateState();
}
addWarning(warning) {
this.customWarnings.push(warning);
this.updateState();
}
setStatus(status) {
this.status = status;
this.updateState();
}
appendArgumentFragment(content) {
this.handle.sendUpdate({
type: "toolStatus.argumentFragment",
id: this.id,
content
});
}
};
ToolsProviderController = class extends BaseController {
/**
* @internal Do not construct this class yourself.
*/
constructor(client, signal, pluginConfig, globalPluginConfig, workingDirectoryPath) {
super(client, signal, pluginConfig, globalPluginConfig, workingDirectoryPath);
}
};
GeneratorConnectorImpl = class {
constructor(channel, taskId) {
this.channel = channel;
this.taskId = taskId;
}
fragmentGenerated(content, opts) {
this.channel.send({
type: "fragmentGenerated",
taskId: this.taskId,
content,
opts
});
}
toolCallGenerationStarted(toolCallId) {
this.channel.send({
type: "toolCallGenerationStarted",
taskId: this.taskId,
toolCallId
});
}
toolCallGenerationNameReceived(toolName) {
this.channel.send({
type: "toolCallGenerationNameReceived",
taskId: this.taskId,
toolName
});
}
toolCallGenerationArgumentFragmentGenerated(content) {
this.channel.send({
type: "toolCallGenerationArgumentFragmentGenerated",
taskId: this.taskId,
content
});
}
toolCallGenerationEnded(toolCallRequest) {
this.channel.send({
type: "toolCallGenerationEnded",
taskId: this.taskId,
toolCallRequest
});
}
toolCallGenerationFailed(error) {
this.channel.send({
type: "toolCallGenerationFailed",
taskId: this.taskId,
error: serializeError(error)
});
}
};
PluginSelfRegistrationHost = class {
constructor(port2, client, rootLogger, validator2) {
this.port = port2;
this.client = client;
this.rootLogger = rootLogger;
this.validator = validator2;
}
/**
* Sets the promptPreprocessor to be used by the plugin represented by this client.
*
* @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
* future without warning.
*/
setPromptPreprocessor(promptPreprocessor) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("plugins", "registerPromptPreprocessor", "promptPreprocessor", external_exports.function(), promptPreprocessor, stack);
const logger2 = new SimpleLogger(`PromptPreprocessor`, this.rootLogger);
logger2.info("Register with LM Studio");
const tasks = /* @__PURE__ */ new Map();
const channel = this.port.createChannel("setPromptPreprocessor", void 0, (message) => {
switch (message.type) {
case "preprocess": {
const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger2);
taskLogger.info(`New preprocess request received.`);
const abortController = new AbortController();
const connector = new ProcessingConnector(this.port, abortController.signal, message.pci, message.token, taskLogger);
const input = ChatMessage.createRaw(
message.input,
/* mutable */
false
);
const controller = new ProcessingController(
this.client,
message.pluginConfig,
message.globalPluginConfig,
message.workingDirectoryPath,
message.enabledPluginInfos,
connector,
message.config,
/* shouldIncludeInputInHistory */
false
);
tasks.set(message.taskId, {
cancel: () => {
abortController.abort();
},
taskLogger
});
promptPreprocessor(controller, input.asMutableCopy()).then((result) => {
taskLogger.info(`Preprocess request completed.`);
const parsedReturned = external_exports.union([external_exports.string(), external_exports.custom((v4) => v4 instanceof ChatMessage)]).safeParse(result);
if (!parsedReturned.success) {
throw new Error("PromptPreprocessor returned an invalid value:" + Validator.prettyPrintZod("result", parsedReturned.error));
}
const returned = parsedReturned.data;
let processed;
if (typeof returned === "string") {
const messageCopy = input.asMutableCopy();
messageCopy.replaceText(returned);
processed = messageCopy.getRaw();
} else {
processed = returned.getRaw();
}
channel.send({
type: "complete",
taskId: message.taskId,
processed
});
}).catch((error) => {
if (error.name === "AbortError") {
logger2.info(`Request successfully aborted.`);
channel.send({
type: "aborted",
taskId: message.taskId
});
return;
}
logger2.warn(`Preprocessing failed.`, error);
channel.send({
type: "error",
taskId: message.taskId,
error: serializeError(error)
});
}).finally(() => {
tasks.delete(message.taskId);
});
break;
}
case "abort": {
const task = tasks.get(message.taskId);
if (task !== void 0) {
task.taskLogger.info(`Received abort request.`);
task.cancel();
tasks.delete(message.taskId);
}
break;
}
}
}, { stack });
}
/**
* Sets the prediction loop handler to be used by the plugin represented by this client.
*
* @deprecated [DEP-PLUGIN-PREDICTION-LOOP-HANDLER] Prediction loop handler support is still in
* development. Stay tuned for updates.
*/
setPredictionLoopHandler(predictionLoopHandler) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("plugins", "setPredictionLoopHandler", "predictionLoopHandler", external_exports.function(), predictionLoopHandler, stack);
const logger2 = new SimpleLogger(` PredictionLoopHandler`, this.rootLogger);
logger2.info("Register with LM Studio");
const tasks = /* @__PURE__ */ new Map();
const channel = this.port.createChannel("setPredictionLoopHandler", void 0, (message) => {
switch (message.type) {
case "handlePredictionLoop": {
const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger2);
taskLogger.info(`New prediction loop handling request received.`);
const abortController = new AbortController();
const connector = new ProcessingConnector(this.port, abortController.signal, message.pci, message.token, taskLogger);
const controller = new ProcessingController(
this.client,
message.pluginConfig,
message.globalPluginConfig,
message.workingDirectoryPath,
message.enabledPluginInfos,
connector,
message.config,
/* shouldIncludeInputInHistory */
true
);
tasks.set(message.taskId, {
cancel: () => {
abortController.abort();
},
taskLogger
});
predictionLoopHandler(controller).then(() => {
channel.send({
type: "complete",
taskId: message.taskId
});
}).catch((error) => {
if (error.name === "AbortError") {
logger2.info(`Request successfully aborted.`);
channel.send({
type: "aborted",
taskId: message.taskId
});
return;
}
logger2.warn(`Generation failed.`, error);
channel.send({
type: "error",
taskId: message.taskId,
error: serializeError(error)
});
}).finally(() => {
tasks.delete(message.taskId);
});
break;
}
case "abort": {
const task = tasks.get(message.taskId);
if (task !== void 0) {
task.taskLogger.info(`Received abort request.`);
task.cancel();
tasks.delete(message.taskId);
}
break;
}
}
}, { stack });
}
/**
* @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
* future without warning.
*/
async setConfigSchematics(configSchematics) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("plugins", "setConfigSchematics", "configSchematics", external_exports.instanceof(KVConfigSchematics), configSchematics, stack);
await this.port.callRpc("setConfigSchematics", {
schematics: configSchematics.serialize()
}, { stack });
}
/**
* @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
* future without warning.
*/
async setGlobalConfigSchematics(globalConfigSchematics2) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("plugins", "setGlobalConfigSchematics", "globalConfigSchematics", external_exports.instanceof(KVConfigSchematics), globalConfigSchematics2, stack);
await this.port.callRpc("setGlobalConfigSchematics", {
schematics: globalConfigSchematics2.serialize()
}, { stack });
}
/**
* @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
* future without warning.
*/
setToolsProvider(toolsProvider) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("plugins", "setToolsProvider", "toolsProvider", external_exports.function(), toolsProvider, stack);
const logger2 = new SimpleLogger(`Tools Prvdr.`, this.rootLogger);
logger2.info("Register with LM Studio");
const openSessions = /* @__PURE__ */ new Map();
const channel = this.port.createChannel("setToolsProvider", void 0, (message) => {
const messageType = message.type;
switch (messageType) {
case "initSession": {
const sessionId = message.sessionId;
const sessionAbortController = new AbortController();
const openSession = {
tools: null,
ongoingToolCalls: /* @__PURE__ */ new Map(),
discarded: false,
abortController: sessionAbortController
};
openSessions.set(sessionId, openSession);
const controller = new ToolsProviderController(this.client, sessionAbortController.signal, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath);
toolsProvider(controller).then((tools) => {
const llmTools = tools.map(toolToLLMTool);
if (openSession.discarded) {
return;
}
channel.send({
type: "sessionInitialized",
sessionId,
toolDefinitions: llmTools
});
openSession.tools = new Map(tools.map((tool) => [tool.name, tool]));
}, (error) => {
if (openSession.discarded) {
return;
}
channel.send({
type: "sessionInitializationFailed",
sessionId,
error: serializeError(error)
});
openSession.discarded = true;
openSessions.delete(sessionId);
});
break;
}
case "discardSession": {
const sessionId = message.sessionId;
const openSession = openSessions.get(sessionId);
if (openSession === void 0) {
return;
}
openSession.discarded = true;
openSession.abortController.abort();
openSessions.delete(sessionId);
break;
}
case "callTool": {
const sessionId = message.sessionId;
const openSession = openSessions.get(sessionId);
if (openSession === void 0) {
return;
}
if (openSession.tools === null) {
throw new Error("Tool called before initialization completed. This is unexpected.");
}
const tool = openSession.tools.get(message.toolName);
if (tool === void 0) {
throw new Error(`Tool ${message.toolName} not found.`);
}
const callId = message.callId;
const ongoingToolCall = {
settled: false,
abortController: new AbortController()
};
openSession.ongoingToolCalls.set(callId, ongoingToolCall);
new SimpleLogger(`Tool (${message.toolName})`, this.rootLogger);
const toolCallContext = {
status(text3) {
channel.send({
type: "toolCallStatus",
sessionId,
callId,
statusText: text3
});
},
warn(text3) {
channel.send({
type: "toolCallWarn",
sessionId,
callId,
warnText: text3
});
},
signal: ongoingToolCall.abortController.signal,
// Call ID is used to match up life cycle events of the same tool call. In this case,
// each call does not have different parts, thus call ID is useless. We can just use 0.
// If the user wants a "unique" ID, they can just have variable that goes up by one
// each time the function is called.
callId: 0
};
(async () => {
return await tool.implementation(message.parameters, toolCallContext);
})().then((result) => {
if (openSession.discarded) {
return;
}
if (ongoingToolCall.settled) {
return;
}
if (ongoingToolCall.abortController.signal.aborted) {
return;
}
if (result === void 0) {
result = "undefined";
channel.send({
type: "toolCallWarn",
sessionId,
callId,
warnText: text`
Tool call returned undefined. This is not expected as the model always expects
a result. If you don't want to return anything, you can just return a string
reporting that the tool call was successful. For example: "operation
successful." In this case, we will give the model string "${result}".
`
});
}
try {
JSON.stringify(result);
} catch (error) {
result = text`
Error: Tool call completed but returned a value that cannot be serialized to JSON
`;
channel.send({
type: "toolCallWarn",
sessionId,
callId,
warnText: text`
Tool call succeeded, but returned a value that is not JSON serializable. In
order to provide the result to the model, return values of tools must be JSON
serializable. In this case, we will give the model string "${result}".
`
});
}
channel.send({
type: "toolCallComplete",
sessionId,
callId,
result
});
ongoingToolCall.settled = true;
openSession.ongoingToolCalls.delete(callId);
}, (error) => {
if (openSession.discarded) {
return;
}
if (ongoingToolCall.settled) {
return;
}
if (ongoingToolCall.abortController.signal.aborted) {
return;
}
channel.send({
type: "toolCallError",
sessionId,
callId,
error: serializeError(error)
});
ongoingToolCall.settled = true;
openSession.ongoingToolCalls.delete(callId);
});
break;
}
case "abortToolCall": {
const sessionId = message.sessionId;
const callId = message.callId;
const openSession = openSessions.get(sessionId);
if (openSession === void 0) {
return;
}
const ongoingToolCall = openSession.ongoingToolCalls.get(callId);
if (ongoingToolCall === void 0) {
return;
}
ongoingToolCall.settled = true;
ongoingToolCall.abortController.abort();
openSession.ongoingToolCalls.delete(callId);
break;
}
default: {
const exhaustiveCheck = messageType;
throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
}
}
});
}
/**
* Sets the generator to be used by the plugin represented by this client.
*
* @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
* future without warning.
*/
setGenerator(generator) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("plugins", "setGenerator", "generator", generatorSchema, generator, stack);
const logger2 = new SimpleLogger(`Generator`, this.rootLogger);
logger2.info("Register with LM Studio");
const tasks = /* @__PURE__ */ new Map();
const channel = this.port.createChannel("setGenerator", void 0, (message) => {
const messageType = message.type;
switch (messageType) {
case "generate": {
const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger2);
taskLogger.info(`New generate request received.`);
const abortController = new AbortController();
const connector = new GeneratorConnectorImpl(channel, message.taskId);
const controller = new GeneratorController(this.client, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath, abortController.signal, message.toolDefinitions, connector, this.validator);
tasks.set(message.taskId, {
cancel: () => {
abortController.abort();
},
taskLogger
});
const history = Chat3.createRaw(message.input, false);
generator(controller, history).then((result) => {
if (result !== void 0) {
taskLogger.warnText`
The generator has returned a value. This it not expected. You should report
generated content using method on the controller. The returned value will be
ignored.
`;
}
channel.send({
type: "complete",
taskId: message.taskId
});
}, (error) => {
if (error.name === "AbortError") {
taskLogger.info(`Request successfully aborted.`);
channel.send({
type: "aborted",
taskId: message.taskId
});
} else {
channel.send({
type: "error",
taskId: message.taskId,
error: serializeError(error)
});
taskLogger.warn(`Generation failed.`, error);
}
}).finally(() => {
tasks.delete(message.taskId);
});
break;
}
case "abort": {
const task = tasks.get(message.taskId);
if (task !== void 0) {
task.taskLogger.info(`Received abort request.`);
task.cancel();
tasks.delete(message.taskId);
}
break;
}
default: {
const exhaustiveCheck = messageType;
throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
}
}
});
}
/**
* @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
* future without warning.
*/
async initCompleted() {
const stack = getCurrentStack(1);
await this.port.callRpc("pluginInitCompleted", void 0, { stack });
}
};
__addDisposableResource = globalThis && globalThis.__addDisposableResource || function(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose, inner2;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner2 = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner2) dispose = function() {
try {
inner2.call(this);
} catch (e9) {
return Promise.reject(e9);
}
};
env.stack.push({ value, dispose, async });
} else if (async) {
env.stack.push({ async: true });
}
return value;
};
__disposeResources = globalThis && globalThis.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
return function(env) {
function fail(e9) {
env.error = env.hasError ? new SuppressedError2(e9, env.error, "An error was suppressed during disposal.") : e9;
env.hasError = true;
}
var r8, s6 = 0;
function next() {
while (r8 = env.stack.pop()) {
try {
if (!r8.async && s6 === 1) return s6 = 0, env.stack.push(r8), Promise.resolve().then(next);
if (r8.dispose) {
var result = r8.dispose.call(r8.value);
if (r8.async) return s6 |= 2, Promise.resolve(result).then(next, function(e9) {
fail(e9);
return next();
});
} else s6 |= 1;
} catch (e9) {
fail(e9);
}
}
if (s6 === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
};
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
var e9 = new Error(message);
return e9.name = "SuppressedError", e9.error = error, e9.suppressed = suppressed, e9;
});
SingleRemoteToolUseSession = class _SingleRemoteToolUseSession {
static async create(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger2, stack) {
const session = new _SingleRemoteToolUseSession(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger2);
await session.init(stack);
return session;
}
constructor(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger2) {
this.pluginsPort = pluginsPort;
this.pluginIdentifier = pluginIdentifier;
this.pluginConfigSpecifier = pluginConfigSpecifier;
this.logger = logger2;
this.status = "initializing";
this.poison = null;
this.ongoingToolCalls = /* @__PURE__ */ new Map();
this.callIdGiver = new IdGiver(0);
}
async init(stack) {
const { promise: initPromise, resolve: resolveInit, reject: rejectInit } = makePromise();
const channel = this.pluginsPort.createChannel("startToolUseSession", {
pluginIdentifier: this.pluginIdentifier,
pluginConfigSpecifier: this.pluginConfigSpecifier
}, (message) => {
const messageType = message.type;
switch (messageType) {
// Upon receiving session ready, mark self as ready and resolve the promise.
case "sessionReady": {
if (this.status !== "initializing") {
this.logger.error("Received sessionReady message while not initializing");
return;
}
this.status = "ready";
resolveInit();
this.tools = message.toolDefinitions.map((toolDefinition) => this.makeTool(toolDefinition));
break;
}
case "toolCallComplete": {
const ongoingCall = this.ongoingToolCalls.get(message.callId);
if (ongoingCall === void 0) {
return;
}
ongoingCall.resolve(message.result);
break;
}
case "toolCallError": {
const ongoingCall = this.ongoingToolCalls.get(message.callId);
if (ongoingCall === void 0) {
return;
}
ongoingCall.reject(fromSerializedError(message.error));
break;
}
case "toolCallStatus": {
const ongoingCall = this.ongoingToolCalls.get(message.callId);
if (ongoingCall === void 0) {
return;
}
ongoingCall.reportStatus(message.statusText);
break;
}
case "toolCallWarn": {
const ongoingCall = this.ongoingToolCalls.get(message.callId);
if (ongoingCall === void 0) {
return;
}
ongoingCall.reportWarning(message.warnText);
break;
}
default: {
const exhaustiveCheck = messageType;
this.logger.warn(`Received unexpected message type in tool use session: ${exhaustiveCheck}`);
}
}
}, { stack });
channel.onError.subscribeOnce((error) => {
if (this.status === "initializing") {
rejectInit(error);
} else {
this.logger.error("Tool use session error.", error);
this.poison = error;
}
for (const ongoingCall of this.ongoingToolCalls.values()) {
ongoingCall.reject(error);
}
this.status = "disposed";
});
channel.onClose.subscribeOnce(() => {
let error;
if (this.status === "initializing") {
error = new Error("Tool use session channel closed unexpectedly during initialization.");
rejectInit(error);
} else {
error = new Error("Tool use session has already ended.");
this.poison = error;
}
for (const ongoingCall of this.ongoingToolCalls.values()) {
ongoingCall.reject(error);
}
this.status = "disposed";
});
this.channel = channel;
await initPromise;
}
[Symbol.dispose]() {
if (this.status !== "disposed") {
this.channel.send({ type: "discardSession" });
this.status = "disposed";
const error = new Error("Session disposed by client.");
for (const ongoingCall of this.ongoingToolCalls.values()) {
ongoingCall.reject(error);
}
this.poison = error;
}
}
makeTool(toolDefinition) {
return internalCreateRemoteTool({
name: toolDefinition.function.name,
description: toolDefinition.function.description ?? "",
pluginIdentifier: this.pluginIdentifier,
parametersJsonSchema: toolDefinition.function.parameters ?? {},
implementation: async (args, ctx) => {
const env_1 = { stack: [], error: void 0, hasError: false };
try {
if (this.poison !== null) {
throw this.poison;
}
if (ctx.signal.aborted) {
throw ctx.signal.reason;
}
const callId = this.callIdGiver.next();
const { promise, resolve: resolve2, reject } = makePromise();
const cleaner = __addDisposableResource(env_1, new Cleaner(), false);
this.ongoingToolCalls.set(callId, {
callId,
resolve: resolve2,
reject,
reportStatus: (status) => ctx.status(status),
reportWarning: (warning) => ctx.warn(warning)
});
cleaner.register(() => {
this.ongoingToolCalls.delete(callId);
});
this.channel.send({
type: "callTool",
callId,
name: toolDefinition.function.name,
arguments: args
});
ctx.signal.addEventListener("abort", () => {
if (this.status === "disposed") {
return;
}
this.channel.send({
type: "abortToolCall",
callId
});
reject(ctx.signal.reason);
}, { once: true });
return await promise;
} catch (e_1) {
env_1.error = e_1;
env_1.hasError = true;
} finally {
__disposeResources(env_1);
}
}
});
}
};
MultiRemoteToolUseSession = class _MultiRemoteToolUseSession {
static async createUsingPredictionProcess(pluginsPort, pluginIdentifiers, predictionContextIdentifier, token, logger2, stack) {
const results = await Promise.allSettled(pluginIdentifiers.map((pluginIdentifier) => SingleRemoteToolUseSession.create(pluginsPort, pluginIdentifier, {
type: "predictionProcess",
pci: predictionContextIdentifier,
token
}, logger2, stack)));
const failed = results.filter((result) => result.status === "rejected");
if (failed.length > 0) {
for (const result of results) {
if (result.status === "fulfilled") {
try {
result.value[Symbol.dispose]();
} catch (error) {
logger2.error("Failed to dispose a session after initialization failure.", error);
}
}
}
throw new AggregateError(failed.map((result) => result.reason), "Failed to initialize some tool use sessions.");
}
return new _MultiRemoteToolUseSession(results.map((result) => result.value), logger2);
}
constructor(sessions, logger2) {
this.sessions = sessions;
this.logger = logger2;
this.tools = [];
this.tools = sessions.flatMap((session) => session.tools);
}
[Symbol.dispose]() {
for (const session of this.sessions) {
try {
session[Symbol.dispose]();
} catch (error) {
this.logger.error("Failed to dispose a session.", error);
}
}
}
};
pluginToolsOptsSchema = external_exports.object({
pluginConfig: kvConfigSchema.optional(),
workingDirectory: external_exports.string().optional()
});
registerDevelopmentPluginOptsSchema = external_exports.object({
manifest: pluginManifestSchema
});
PluginsNamespace = class {
/** @internal */
constructor(port2, client, validator2, parentLogger, rootLogger) {
this.port = port2;
this.client = client;
this.validator = validator2;
this.rootLogger = rootLogger;
this.logger = new SimpleLogger("Plugins", parentLogger);
}
/**
* @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
* future without warning.
*/
async registerDevelopmentPlugin(opts) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("plugins", "registerDevelopmentPlugin", "opts", registerDevelopmentPluginOptsSchema, opts, stack);
const { promise, resolve: resolve2 } = makePromise();
const channel = this.port.createChannel("registerDevelopmentPlugin", opts, (message) => {
if (message.type === "ready") {
resolve2({
clientIdentifier: message.clientIdentifier,
clientPasskey: message.clientPasskey
});
}
}, { stack });
let unregisterCalled = false;
const unregister = async () => {
if (unregisterCalled) {
return;
}
unregisterCalled = true;
channel.send({ type: "end" });
const { promise: promise2, resolve: resolve3 } = makePromise();
channel.onClose.subscribeOnce(resolve3);
await promise2;
};
const base = await promise;
return {
...base,
unregister
};
}
/**
* Requests LM Studio to reindex all the plugins.
*
* CAVEAT: Currently, we do not wait for the reindex to complete before returning. In the future,
* we will change this behavior and only return after the reindex is completed.
*
* @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the
* future without warning.
*/
async reindexPlugins() {
const stack = getCurrentStack(1);
await this.port.callRpc("reindexPlugins", void 0, { stack });
}
/**
* If this client is currently running as a plugin, get the self registration host which can be
* used to register hooks.
*
* @deprecated This method is used by plugins internally to register hooks. Do not use directly.
*/
getSelfRegistrationHost() {
return new PluginSelfRegistrationHost(this.port, this.client, this.rootLogger, this.validator);
}
/**
* Starts a tool use session use any config specifier.
*/
async internalStartToolUseSession(pluginIdentifier, pluginConfigSpecifier, _stack) {
return await SingleRemoteToolUseSession.create(this.port, pluginIdentifier, pluginConfigSpecifier, this.logger);
}
/**
* Start a tool use session with a plugin. Note, this method must be used with "Explicit Resource
* Management". That is, you should use it like so:
*
* ```typescript
* using pluginTools = await client.plugins.pluginTools("owner/name", { ... });
* // ^ Notice the `using` keyword here.
* ```
*
* If you do not use `using`, you must call `pluginTools[Symbol.dispose]()` after you are done.
* Otherwise, there will be a memory leak and the plugins you requested tools from will be loaded
* indefinitely.
*
* @experimental [EXP-USE-USE-PLUGIN-TOOLS] Using tools from other applications is still in
* development. This may change in the future without warning.
*/
async pluginTools(pluginIdentifier, opts = {}) {
const stack = getCurrentStack(1);
[pluginIdentifier, opts] = this.validator.validateMethodParamsOrThrow("plugins", "pluginTools", ["pluginIdentifier", "opts"], [artifactIdentifierSchema, pluginToolsOptsSchema], [pluginIdentifier, opts], stack);
return await this.internalStartToolUseSession(pluginIdentifier, {
type: "direct",
config: opts.pluginConfig ?? emptyKVConfig,
workingDirectoryPath: opts.workingDirectory
});
}
/**
* Start a tool use session associated with a prediction process.
*
* This method is used internally by processing controllers and will be stripped by the internal
* tag.
*
* @internal
*/
async startToolUseSessionUsingPredictionProcess(pluginIdentifiers, predictionContextIdentifier, token, stack) {
return await MultiRemoteToolUseSession.createUsingPredictionProcess(this.port, pluginIdentifiers, predictionContextIdentifier, token, this.logger, stack);
}
/**
* @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in
* development. This may change in the future without warning.
*/
createGeneratorHandle(pluginIdentifier) {
return new LLMGeneratorHandle(this.port, pluginIdentifier, this.validator, null, this.logger);
}
/**
* Creates a generator handle that is already associated with a prediction process.
*
* This method is used internally by the processing controllers to create generator handles. It is
* marked as internal and will be stripped.
*
* @internal
*/
createGeneratorHandleAssociatedWithPredictionProcess(pluginIdentifier, predictionContextIdentifier, token) {
return new LLMGeneratorHandle(this.port, pluginIdentifier, this.validator, { pci: predictionContextIdentifier, token }, this.logger);
}
};
artifactDownloadPlannerDownloadOptsSchema = external_exports.object({
onStartFinalizing: external_exports.function().optional(),
onProgress: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional()
});
ArtifactDownloadPlanner = class {
/**
* @internal Do not construct this class yourself.
*/
constructor(owner, name, onPlanUpdated, channel, validator2, onDisposed) {
this.owner = owner;
this.name = name;
this.onPlanUpdated = onPlanUpdated;
this.channel = channel;
this.validator = validator2;
this.onDisposed = onDisposed;
this.readyDeferredPromise = makePromise();
this.isReadyBoolean = false;
this.currentDownload = null;
this.errorReceivedBeforeDownloadStart = null;
this.logger = new SimpleLogger(`ArtifactDownloadPlanner(${owner}/${name})`);
this.readyDeferredPromise.promise.catch(() => {
});
this.planValue = {
nodes: [
{
type: "artifact",
owner,
name,
state: "pending",
dependencyNodes: []
}
],
downloadSizeBytes: 0
};
this.channel.onMessage.subscribe((message) => {
const messageType = message.type;
switch (messageType) {
case "planReady": {
this.isReadyBoolean = true;
this.readyDeferredPromise.resolve();
this.planValue = message.plan;
break;
}
case "planUpdated": {
this.planValue = message.plan;
safeCallCallback(this.logger, "onPlanUpdated", this.onPlanUpdated, [message.plan]);
break;
}
case "success": {
if (this.currentDownload === null) {
throw new Error("Unexpected: received success message without a download.");
}
this.currentDownload.downloadFinished();
break;
}
case "downloadProgress": {
if (this.currentDownload === null) {
throw new Error("Unexpected: received progress message without a download.");
}
this.currentDownload.progressUpdate(message.update);
break;
}
case "startFinalizing": {
if (this.currentDownload === null) {
throw new Error("Unexpected: received startFinalizing message without a download.");
}
this.currentDownload.startFinalizing();
break;
}
}
});
this.channel.onError.subscribeOnce((error) => {
if (this.currentDownload === null) {
this.errorReceivedBeforeDownloadStart = error;
this.readyDeferredPromise.reject(error);
} else {
this.currentDownload.downloadFailed(error);
}
});
}
[Symbol.dispose]() {
this.channel.send({ type: "cancel" });
this.onDisposed();
}
isReady() {
return this.isReadyBoolean;
}
async untilReady() {
return await this.readyDeferredPromise.promise;
}
getPlan() {
return this.planValue;
}
/**
* Download this artifact. `download` can only be called once.
*/
async download(opts) {
const stack = getCurrentStack(1);
opts = this.validator.validateMethodParamOrThrow("ArtifactDownloadPlanner", "download", "opts", artifactDownloadPlannerDownloadOptsSchema, opts, stack);
const { onProgress, onStartFinalizing, signal = new AbortController().signal } = opts;
if (this.currentDownload !== null) {
throw new Error("You can only call `download` once for each planner.");
}
if (this.errorReceivedBeforeDownloadStart !== null) {
const error = this.errorReceivedBeforeDownloadStart;
this.errorReceivedBeforeDownloadStart = null;
throw error;
}
const { promise, resolve: resolve2, reject } = makePromise();
this.currentDownload = {
downloadFinished: () => {
resolve2();
},
startFinalizing: () => {
safeCallCallback(this.logger, "onStartFinalizing", onStartFinalizing, []);
},
progressUpdate: (update) => {
safeCallCallback(this.logger, "onProgress", onProgress, [update]);
},
downloadFailed: (error) => {
reject(error);
}
};
this.channel.send({ type: "commit" });
if (signal.aborted) {
this.channel.send({ type: "cancel" });
} else {
signal.addEventListener("abort", () => {
this.channel.send({ type: "cancel" });
});
}
return await promise.catch((error) => {
if (signal.aborted) {
throw signal.reason;
} else {
throw error;
}
});
}
};
downloadOptsSchema = external_exports.object({
onProgress: external_exports.function().optional(),
onStartFinalizing: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional()
});
ModelSearchResultDownloadOption = class {
/** @internal */
constructor(repositoryPort, validator2, logger2, data) {
this.repositoryPort = repositoryPort;
this.validator = validator2;
this.logger = logger2;
this.data = data;
this.quantization = data.quantization;
this.name = data.name;
this.sizeBytes = data.sizeBytes;
this.fitEstimation = this.data.fitEstimation;
this.indexedModelIdentifier = this.data.indexedModelIdentifier;
}
isRecommended() {
return this.data.recommended ?? false;
}
/**
* Download the model. Returns the model key which can be used to load the model.
*/
async download(opts = {}) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("ModelSearchResultDownloadOption", "download", "opts", downloadOptsSchema, opts, stack);
const { promise, resolve: resolve2, reject } = makePromise();
const channel = this.repositoryPort.createChannel("downloadModel", {
downloadIdentifier: this.data.downloadIdentifier
}, (message) => {
switch (message.type) {
case "downloadProgress": {
safeCallCallback(this.logger, "onProgress", opts.onProgress, [message.update]);
break;
}
case "startFinalizing": {
safeCallCallback(this.logger, "onStartFinalizing", opts.onStartFinalizing, []);
break;
}
case "success": {
resolve2(message.defaultIdentifier);
break;
}
default: {
const exhaustiveCheck = message;
throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
}
}
}, { stack });
channel.onError.subscribeOnce((error) => {
if (opts.signal?.aborted) {
reject(opts.signal.reason);
} else {
reject(error);
}
});
channel.onClose.subscribeOnce(() => {
if (opts.signal?.aborted) {
reject(opts.signal.reason);
} else {
reject(new Error("Channel closed unexpectedly."));
}
});
const abortListener = () => {
channel.send({ type: "cancel" });
};
opts.signal?.addEventListener("abort", abortListener);
promise.finally(() => {
opts.signal?.removeEventListener("abort", abortListener);
});
return await promise;
}
};
ModelSearchResultEntry = class {
/**
* @internal
*/
constructor(repositoryPort, validator2, logger2, data) {
this.repositoryPort = repositoryPort;
this.validator = validator2;
this.logger = logger2;
this.data = data;
this.name = data.name;
}
isExactMatch() {
return this.data.exact ?? false;
}
isStaffPick() {
return this.data.staffPick ?? false;
}
async getDownloadOptions() {
const { results } = await this.repositoryPort.callRpc("getModelDownloadOptions", {
modelSearchResultIdentifier: this.data.identifier
});
return results.map((data) => new ModelSearchResultDownloadOption(this.repositoryPort, this.validator, this.logger, data));
}
};
downloadArtifactOptsSchema = external_exports.object({
owner: external_exports.string(),
name: external_exports.string(),
revisionNumber: external_exports.number(),
path: external_exports.string(),
onProgress: external_exports.function().optional(),
onStartFinalizing: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional()
});
pushArtifactOptsSchema = external_exports.object({
path: external_exports.string(),
description: external_exports.string().optional(),
makePrivate: external_exports.boolean().optional(),
writeRevision: external_exports.boolean().optional(),
overrides: jsonSerializableSchema.optional(),
onMessage: external_exports.function().optional()
});
ensureAuthenticatedOptsSchema = external_exports.object({
onAuthenticationUrl: external_exports.function()
});
loginWithPreAuthenticatedKeysOptsSchema = external_exports.object({
keyId: external_exports.string(),
publicKey: external_exports.string(),
privateKey: external_exports.string()
});
external_exports.object({
userName: external_exports.string()
});
createArtifactDownloadPlannerOptsSchema = external_exports.object({
owner: external_exports.string(),
name: external_exports.string(),
onPlanUpdated: external_exports.function().optional()
});
RepositoryNamespace = class {
/** @internal */
constructor(repositoryPort, validator2, parentLogger) {
this.repositoryPort = repositoryPort;
this.validator = validator2;
this.downloadPlanFinalizationRegistry = new FinalizationRegistry(({ owner, name }) => {
this.logger.warn(`
A download plan for artifact ${owner}/${name} has been garbage collected without being
disposed. Please make sure you are creating the download plan with the "using" keyword.
This is a memory leak and needs to be fixed.
`);
});
this.logger = new SimpleLogger("Repository", parentLogger);
}
async searchModels(opts) {
const stack = getCurrentStack(1);
opts = this.validator.validateMethodParamOrThrow("repository", "search", "opts", modelSearchOptsSchema, opts, stack);
const { results } = await this.repositoryPort.callRpc("searchModels", { opts }, { stack });
return results.map((data) => new ModelSearchResultEntry(this.repositoryPort, this.validator, this.logger, data));
}
/**
* @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
* tuned for updates.
*/
async installPluginDependencies(pluginFolder) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("repository", "installPluginDependencies", "pluginFolder", external_exports.string(), pluginFolder, stack);
await this.repositoryPort.callRpc("installPluginDependencies", { pluginFolder }, { stack });
}
/**
* @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
* tuned for updates.
*/
async downloadArtifact(opts) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("client.repository", "downloadArtifact", "opts", downloadArtifactOptsSchema, opts, stack);
const { owner, name, revisionNumber, path: path6, onProgress, onStartFinalizing, signal } = opts;
const { promise, resolve: resolve2, reject } = makePromise();
const channel = this.repositoryPort.createChannel("downloadArtifact", { artifactOwner: owner, artifactName: name, revisionNumber, path: path6 }, (message) => {
switch (message.type) {
case "downloadProgress": {
safeCallCallback(this.logger, "onProgress", onProgress, [message.update]);
break;
}
case "startFinalizing": {
safeCallCallback(this.logger, "onStartFinalizing", onStartFinalizing, []);
break;
}
case "success": {
resolve2();
break;
}
default: {
const exhaustiveCheck = message;
throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
}
}
}, { stack });
channel.onError.subscribeOnce(reject);
channel.onClose.subscribeOnce(() => {
if (signal?.aborted) {
reject(signal.reason);
} else {
reject(new Error("Channel closed unexpectedly."));
}
});
const abortListener = () => {
channel.send({ type: "cancel" });
};
signal?.addEventListener("abort", abortListener);
promise.finally(() => {
signal?.removeEventListener("abort", abortListener);
});
return await promise;
}
/**
* @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
* tuned for updates.
*/
async pushArtifact(opts) {
const stack = getCurrentStack(1);
const { path: path6, description, makePrivate, writeRevision, overrides: overrides2, onMessage } = this.validator.validateMethodParamOrThrow("repository", "pushArtifact", "opts", pushArtifactOptsSchema, opts, stack);
const channel = this.repositoryPort.createChannel("pushArtifact", { path: path6, description, makePrivate, writeRevision, overrides: overrides2 }, (message) => {
const type = message.type;
switch (type) {
case "message": {
safeCallCallback(this.logger, "onMessage", onMessage, [message.message]);
break;
}
default: {
const exhaustiveCheck = type;
throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
}
}
}, { stack });
const { promise, resolve: resolve2, reject } = makePromise();
channel.onError.subscribeOnce(reject);
channel.onClose.subscribeOnce(resolve2);
await promise;
}
/**
* @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
* tuned for updates.
*/
async getLocalArtifactFileList(path6) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("repository", "getLocalArtifactFileList", "path", external_exports.string(), path6, stack);
const { fileList } = await this.repositoryPort.callRpc("getLocalArtifactFiles", { path: path6 }, { stack });
return fileList;
}
/**
* @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
* tuned for updates.
*/
async ensureAuthenticated(opts) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("repository", "ensureAuthenticated", "opts", ensureAuthenticatedOptsSchema, opts, stack);
const { promise, resolve: resolve2, reject } = makePromise();
const channel = this.repositoryPort.createChannel("ensureAuthenticated", void 0, (message) => {
const type = message.type;
switch (type) {
case "authenticationUrl": {
safeCallCallback(this.logger, "onAuthenticationUrl", opts.onAuthenticationUrl, [
message.url
]);
break;
}
case "authenticated": {
resolve2();
break;
}
default: {
const exhaustiveCheck = type;
throw new Error(`Unexpected message type: ${exhaustiveCheck}`);
}
}
});
channel.onError.subscribeOnce(reject);
await promise;
}
async loginWithPreAuthenticatedKeys(opts) {
const stack = getCurrentStack(1);
this.validator.validateMethodParamOrThrow("repository", "loginWithPreAuthenticatedKeys", "opts", loginWithPreAuthenticatedKeysOptsSchema, opts, stack);
const { keyId, publicKey, privateKey } = opts;
const { userName } = await this.repositoryPort.callRpc("loginWithPreAuthenticatedKeys", { keyId, publicKey, privateKey }, { stack });
return { userName };
}
/**
* @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay
* tuned for updates.
*/
createArtifactDownloadPlanner(opts) {
const { owner, name, onPlanUpdated } = this.validator.validateMethodParamOrThrow("repository", "createArtifactDownloadPlanner", "opts", createArtifactDownloadPlannerOptsSchema, opts);
const stack = getCurrentStack(1);
const channel = this.repositoryPort.createChannel(
"createArtifactDownloadPlan",
{ owner, name },
void 0,
// Don't listen to the messages yet.
{ stack }
);
const planner = new ArtifactDownloadPlanner(owner, name, onPlanUpdated, channel, this.validator, () => {
this.downloadPlanFinalizationRegistry.unregister(planner);
});
this.downloadPlanFinalizationRegistry.register(planner, { owner, name }, planner);
return planner;
}
};
startHttpServerOptsSchema = external_exports.object({
port: external_exports.number().int().min(1).max(65535).describe("Port to run the API server on. Must be between 1 and 65535."),
cors: external_exports.boolean().describe("Enable CORS on the API server. Allows any website to access the server.")
});
SystemNamespace = class {
/** @internal */
constructor(systemPort, validator2, parentLogger) {
this.systemPort = systemPort;
this.validator = validator2;
this.logger = new SimpleLogger("System", parentLogger);
}
async listDownloadedModels(domain) {
const stack = getCurrentStack(1);
domain = this.validator.validateMethodParamOrThrow("client.system", "listDownloadedModels", "domain", external_exports.union([external_exports.literal("llm"), external_exports.literal("embedding"), external_exports.undefined()]), domain, stack);
const models = await this.systemPort.callRpc("listDownloadedModels", void 0, {
stack: getCurrentStack(1)
});
if (domain === void 0) {
return models;
}
return models.filter((model) => model.type === domain);
}
async whenDisconnected() {
const stack = getCurrentStack(1);
const channel = this.systemPort.createChannel("alive", void 0, void 0, { stack });
const { promise, resolve: resolve2 } = makePromise();
channel.onError.subscribeOnce(resolve2);
channel.onClose.subscribeOnce(resolve2);
await promise;
}
async notify(notification) {
const stack = getCurrentStack(1);
notification = this.validator.validateMethodParamOrThrow("client.system", "notify", "notification", backendNotificationSchema, notification, stack);
await this.systemPort.callRpc("notify", notification, { stack });
}
async getLMStudioVersion() {
const stack = getCurrentStack(1);
return await this.systemPort.callRpc("version", void 0, { stack });
}
/**
* Sets an experiment flags for LM Studio. This is an unstable API and may change without notice.
*
* @experimental
*/
async unstable_setExperimentFlag(flag, value) {
const stack = getCurrentStack(1);
[flag, value] = this.validator.validateMethodParamsOrThrow("client.system", "setExperimentFlag", ["flag", "value"], [external_exports.string(), external_exports.boolean()], [flag, value], stack);
await this.systemPort.callRpc("setExperimentFlag", { code: flag, value }, { stack });
}
/**
* Gets all experiment flags for LM Studio. This is an unstable API and may change without notice.
*
* @experimental
*/
async unstable_getExperimentFlags() {
const stack = getCurrentStack(1);
return await this.systemPort.callRpc("getExperimentFlags", void 0, { stack });
}
/**
* Starts the API server on the specified port.
*
* @experimental
*/
async startHttpServer(opts) {
const stack = getCurrentStack(1);
opts = this.validator.validateMethodParamOrThrow("client.system", "startHttpServer", "args", startHttpServerOptsSchema, opts);
return await this.systemPort.callRpc("startHttpServer", { port: opts.port, cors: opts.cors }, {
stack
});
}
/**
* Stops the API server if it is running.
*
* @experimental
*/
async stopHttpServer() {
const stack = getCurrentStack(1);
return await this.systemPort.callRpc("stopHttpServer", void 0, { stack });
}
};
constructorOptsSchema = external_exports.object({
logger: external_exports.any().optional(),
baseUrl: external_exports.string().optional(),
verboseErrorMessages: external_exports.boolean().optional(),
clientIdentifier: external_exports.string().optional(),
clientPasskey: external_exports.string().optional(),
// Internal testing options
disableConnection: external_exports.boolean().optional(),
llmPort: external_exports.any().optional(),
embeddingPort: external_exports.any().optional(),
systemPort: external_exports.any().optional(),
diagnosticsPort: external_exports.any().optional(),
retrievalPort: external_exports.any().optional(),
filesPort: external_exports.any().optional(),
repositoryPort: external_exports.any().optional(),
pluginsPort: external_exports.any().optional()
}).strict();
LMStudioClient = class {
/** @internal */
validateBaseUrlOrThrow(baseUrl) {
let url;
try {
url = new URL(baseUrl);
} catch (e9) {
this.logger.throw(text`
Failed to construct LMStudioClient. The baseUrl passed in is invalid. Received: ${baseUrl}
`);
}
if (!["ws:", "wss:"].includes(url.protocol)) {
this.logger.throw(text`
Failed to construct LMStudioClient. The baseUrl passed in must have protocol "ws" or "wss".
Received: ${baseUrl}
`);
}
if (url.search !== "") {
this.logger.throw(text`
Failed to construct LMStudioClient. The baseUrl passed contains search parameters
("${url.search}").
`);
}
if (url.hash !== "") {
this.logger.throw(text`
Failed to construct LMStudioClient. The baseUrl passed contains a hash ("${url.hash}").
`);
}
if (url.username !== "" || url.password !== "") {
this.logger.throw(text`
Failed to construct LMStudioClient. The baseUrl passed contains a username or password. We
do not support these in the baseUrl. Received: ${baseUrl}
`);
}
if (baseUrl.endsWith("/")) {
this.logger.throw(text`
Failed to construct LMStudioClient. The baseUrl passed in must not end with a "/". If you
are reverse-proxying, you should remove the trailing slash from the baseUrl. Received:
${baseUrl}
`);
}
}
async isLocalhostWithGivenPortLMStudioServer(port2) {
const response = await fetch(`http://127.0.0.1:${port2}/lmstudio-greeting`);
if (response.status !== 200) {
throw new Error("Status is not 200.");
}
const json2 = await response.json();
if (json2?.lmstudio !== true) {
throw new Error("Not an LM Studio server.");
}
return port2;
}
/**
* Guess the base URL of the LM Studio server by visiting localhost on various default ports.
*/
async guessBaseUrl(stack) {
if (getHostedEnv() !== null) {
return Promise.resolve("Using hosted env");
}
if (process_shim_default.browser) {
try {
this.isLocalhostWithGivenPortLMStudioServer(1234);
return "ws://127.0.0.1:1234";
} catch (error) {
text`
${import_chalk.default.redBright("Failed to connect to LM Studio.")}
Is LM Studio running? If not, please start it by running:
${import_chalk.default.yellow("lms server start --cors")}
If you are attempting to connect to LM Studio on a separate machine, please provide the
baseUrl option when creating the LMStudioClient:
${import_chalk.default.blueBright(text`
const client = new LMStudioClient({ baseUrl: 'ws://:' });
`)}
${import_chalk.default.white("(i) For more information, refer to the LM Studio documentation:")}
${import_chalk.default.gray("https://lmstudio.ai/docs/local-server")}
`;
}
}
return Promise.any(apiServerPorts.map(this.isLocalhostWithGivenPortLMStudioServer)).then((port2) => `ws://127.0.0.1:${port2}`, () => {
throw makePrettyError(text`
${import_chalk.default.redBright("Failed to connect to LM Studio.")}
Please make sure LM Studio is running on your machine.
If you are attempting to connect to LM Studio on a separate machine, please provide the
baseUrl option when creating the LMStudioClient:
${import_chalk.default.blueBright(text`
const client = new LMStudioClient({ baseUrl: 'ws://:' });
`)}
${import_chalk.default.white("(i) For more information, refer to the LM Studio documentation:")}
${import_chalk.default.gray("https://lmstudio.ai/docs/local-server")}
`, stack);
});
}
createPort(namespace, name, backendInterface) {
return createAuthenticatedClientPort(backendInterface, this.resolvingBaseUrl, namespace, this.clientIdentifier, this.clientPasskey, new SimpleLogger(name, this.logger), {
errorDeserializer: friendlyErrorDeserializer,
verboseErrorMessage: this.verboseErrorMessages
});
}
constructor(opts = {}) {
const { logger: logger2, baseUrl, verboseErrorMessages, clientIdentifier, clientPasskey, disableConnection, llmPort, embeddingPort, systemPort, diagnosticsPort, retrievalPort, filesPort, repositoryPort, pluginsPort } = new Validator().validateConstructorParamOrThrow("LMStudioClient", "opts", constructorOptsSchema, opts);
if (globalThis.__LMS_PLUGIN_CONTEXT && opts.baseUrl === void 0) {
throw new Error(text`
You cannot create a local LMStudioClient in a plugin context. To use LM Studio APIs, use
the "client" property attached to the Controllers.
For example, instead of:
${"const client = new LMStudioClient(); // <-- Error\nexport async function generate(ctl: GeneratorController) {\n const model = await client.llm.model(...);\n}"}
Do this:
${"export async function generate(ctl: GeneratorController) {\n const model = await ctl.client.llm.model(...);\n}"}
If you need to connect to a remote LM Studio, you should pass in the \`baseUrl\` option to
the LMStudioClient constructor:
${"const client = new LMStudioClient({ baseUrl: 'ws://:' });"}
`);
}
this.logger = new SimpleLogger("LMStudioClient", logger2);
this.clientIdentifier = clientIdentifier ?? (0, import_lms_isomorphic.generateRandomBase64)(18);
this.clientPasskey = clientPasskey ?? (0, import_lms_isomorphic.generateRandomBase64)(18);
const stack = getCurrentStack(1);
if (disableConnection) {
this.resolvingBaseUrl = new Promise(() => void 0);
} else {
if (baseUrl === void 0) {
this.resolvingBaseUrl = this.guessBaseUrl(verboseErrorMessages ? stack : void 0);
} else {
this.validateBaseUrlOrThrow(baseUrl);
this.resolvingBaseUrl = baseUrl;
}
}
this.verboseErrorMessages = verboseErrorMessages ?? true;
this.llmPort = llmPort ?? this.createPort("llm", "LLM", createLlmBackendInterface());
this.embeddingPort = embeddingPort ?? this.createPort("embedding", "Embedding", createEmbeddingBackendInterface());
this.systemPort = systemPort ?? this.createPort("system", "System", createSystemBackendInterface());
this.diagnosticsPort = diagnosticsPort ?? this.createPort("diagnostics", "Diagnostics", createDiagnosticsBackendInterface());
this.filesPort = filesPort ?? this.createPort("files", "Files", createFilesBackendInterface());
this.repositoryPort = repositoryPort ?? this.createPort("repository", "Repository", createRepositoryBackendInterface());
this.pluginsPort = pluginsPort ?? this.createPort("plugins", "Plugins", createPluginsBackendInterface());
const validator2 = new Validator();
this.llm = new LLMNamespace(this, this.llmPort, new SimpleLogger("LLM", this.logger), validator2);
this.embedding = new EmbeddingNamespace(this, this.embeddingPort, new SimpleLogger("Embedding", this.logger), validator2);
this.system = new SystemNamespace(this.systemPort, validator2, this.logger);
this.diagnostics = new DiagnosticsNamespace(this.diagnosticsPort, validator2, this.logger);
this.files = new FilesNamespace(this.filesPort, validator2, this.logger);
this.repository = new RepositoryNamespace(this.repositoryPort, validator2, this.logger);
this.plugins = new PluginsNamespace(this.pluginsPort, this, validator2, this.logger, logger2);
}
async [Symbol.asyncDispose]() {
await Promise.all([
this.llmPort[Symbol.asyncDispose](),
this.embeddingPort[Symbol.asyncDispose](),
this.systemPort[Symbol.asyncDispose](),
this.diagnosticsPort[Symbol.asyncDispose](),
this.filesPort[Symbol.asyncDispose](),
this.repositoryPort[Symbol.asyncDispose](),
this.pluginsPort[Symbol.asyncDispose]()
]);
}
};
}
});
// ../pi-mono/node_modules/whatwg-fetch/fetch.js
function isDataView(obj) {
return obj && DataView.prototype.isPrototypeOf(obj);
}
function normalizeName(name) {
if (typeof name !== "string") {
name = String(name);
}
if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === "") {
throw new TypeError('Invalid character in header field name: "' + name + '"');
}
return name.toLowerCase();
}
function normalizeValue(value) {
if (typeof value !== "string") {
value = String(value);
}
return value;
}
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift();
return { done: value === void 0, value };
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator;
};
}
return iterator;
}
function Headers2(headers) {
this.map = {};
if (headers instanceof Headers2) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
if (header.length != 2) {
throw new TypeError("Headers constructor: expected name/value pair to be length 2, found" + header.length);
}
this.append(header[0], header[1]);
}, this);
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name]);
}, this);
}
}
function consumed(body) {
if (body._noBody) return;
if (body.bodyUsed) {
return Promise.reject(new TypeError("Already read"));
}
body.bodyUsed = true;
}
function fileReaderReady(reader) {
return new Promise(function(resolve2, reject) {
reader.onload = function() {
resolve2(reader.result);
};
reader.onerror = function() {
reject(reader.error);
};
});
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise;
}
function readBlobAsText(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
var match2 = /charset=([A-Za-z0-9_-]+)/.exec(blob.type);
var encoding = match2 ? match2[1] : "utf-8";
reader.readAsText(blob, encoding);
return promise;
}
function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf);
var chars = new Array(view.length);
for (var i7 = 0; i7 < view.length; i7++) {
chars[i7] = String.fromCharCode(view[i7]);
}
return chars.join("");
}
function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0);
} else {
var view = new Uint8Array(buf.byteLength);
view.set(new Uint8Array(buf));
return view.buffer;
}
}
function Body() {
this.bodyUsed = false;
this._initBody = function(body) {
this.bodyUsed = this.bodyUsed;
this._bodyInit = body;
if (!body) {
this._noBody = true;
this._bodyText = "";
} else if (typeof body === "string") {
this._bodyText = body;
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString();
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body);
} else {
this._bodyText = body = Object.prototype.toString.call(body);
}
if (!this.headers.get("content-type")) {
if (typeof body === "string") {
this.headers.set("content-type", "text/plain;charset=UTF-8");
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set("content-type", this._bodyBlob.type);
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
}
}
};
if (support.blob) {
this.blob = function() {
var rejected = consumed(this);
if (rejected) {
return rejected;
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]));
} else if (this._bodyFormData) {
throw new Error("could not read FormData body as blob");
} else {
return Promise.resolve(new Blob([this._bodyText]));
}
};
}
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
var isConsumed = consumed(this);
if (isConsumed) {
return isConsumed;
} else if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
return Promise.resolve(
this._bodyArrayBuffer.buffer.slice(
this._bodyArrayBuffer.byteOffset,
this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
)
);
} else {
return Promise.resolve(this._bodyArrayBuffer);
}
} else if (support.blob) {
return this.blob().then(readBlobAsArrayBuffer);
} else {
throw new Error("could not read as ArrayBuffer");
}
};
this.text = function() {
var rejected = consumed(this);
if (rejected) {
return rejected;
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));
} else if (this._bodyFormData) {
throw new Error("could not read FormData body as text");
} else {
return Promise.resolve(this._bodyText);
}
};
if (support.formData) {
this.formData = function() {
return this.text().then(decode);
};
}
this.json = function() {
return this.text().then(JSON.parse);
};
return this;
}
function normalizeMethod(method) {
var upcased = method.toUpperCase();
return methods.indexOf(upcased) > -1 ? upcased : method;
}
function Request2(input, options) {
if (!(this instanceof Request2)) {
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
}
options = options || {};
var body = options.body;
if (input instanceof Request2) {
if (input.bodyUsed) {
throw new TypeError("Already read");
}
this.url = input.url;
this.credentials = input.credentials;
if (!options.headers) {
this.headers = new Headers2(input.headers);
}
this.method = input.method;
this.mode = input.mode;
this.signal = input.signal;
if (!body && input._bodyInit != null) {
body = input._bodyInit;
input.bodyUsed = true;
}
} else {
this.url = String(input);
}
this.credentials = options.credentials || this.credentials || "same-origin";
if (options.headers || !this.headers) {
this.headers = new Headers2(options.headers);
}
this.method = normalizeMethod(options.method || this.method || "GET");
this.mode = options.mode || this.mode || null;
this.signal = options.signal || this.signal || (function() {
if ("AbortController" in g2) {
var ctrl = new AbortController();
return ctrl.signal;
}
})();
this.referrer = null;
if ((this.method === "GET" || this.method === "HEAD") && body) {
throw new TypeError("Body not allowed for GET or HEAD requests");
}
this._initBody(body);
if (this.method === "GET" || this.method === "HEAD") {
if (options.cache === "no-store" || options.cache === "no-cache") {
var reParamSearch = /([?&])_=[^&]*/;
if (reParamSearch.test(this.url)) {
this.url = this.url.replace(reParamSearch, "$1_=" + (/* @__PURE__ */ new Date()).getTime());
} else {
var reQueryString = /\?/;
this.url += (reQueryString.test(this.url) ? "&" : "?") + "_=" + (/* @__PURE__ */ new Date()).getTime();
}
}
}
}
function decode(body) {
var form = new FormData();
body.trim().split("&").forEach(function(bytes) {
if (bytes) {
var split = bytes.split("=");
var name = split.shift().replace(/\+/g, " ");
var value = split.join("=").replace(/\+/g, " ");
form.append(decodeURIComponent(name), decodeURIComponent(value));
}
});
return form;
}
function parseHeaders(rawHeaders) {
var headers = new Headers2();
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, " ");
preProcessedHeaders.split("\r").map(function(header) {
return header.indexOf("\n") === 0 ? header.substr(1, header.length) : header;
}).forEach(function(line) {
var parts = line.split(":");
var key = parts.shift().trim();
if (key) {
var value = parts.join(":").trim();
try {
headers.append(key, value);
} catch (error) {
console.warn("Response " + error.message);
}
}
});
return headers;
}
function Response2(bodyInit, options) {
if (!(this instanceof Response2)) {
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
}
if (!options) {
options = {};
}
this.type = "default";
this.status = options.status === void 0 ? 200 : options.status;
if (this.status < 200 || this.status > 599) {
throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");
}
this.ok = this.status >= 200 && this.status < 300;
this.statusText = options.statusText === void 0 ? "" : "" + options.statusText;
this.headers = new Headers2(options.headers);
this.url = options.url || "";
this._initBody(bodyInit);
}
function fetch2(input, init) {
return new Promise(function(resolve2, reject) {
var request = new Request2(input, init);
if (request.signal && request.signal.aborted) {
return reject(new DOMException("Aborted", "AbortError"));
}
var xhr = new XMLHttpRequest();
function abortXhr() {
xhr.abort();
}
xhr.onload = function() {
var options = {
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || "")
};
if (request.url.indexOf("file://") === 0 && (xhr.status < 200 || xhr.status > 599)) {
options.status = 200;
} else {
options.status = xhr.status;
}
options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL");
var body = "response" in xhr ? xhr.response : xhr.responseText;
setTimeout(function() {
resolve2(new Response2(body, options));
}, 0);
};
xhr.onerror = function() {
setTimeout(function() {
reject(new TypeError("Network request failed"));
}, 0);
};
xhr.ontimeout = function() {
setTimeout(function() {
reject(new TypeError("Network request timed out"));
}, 0);
};
xhr.onabort = function() {
setTimeout(function() {
reject(new DOMException("Aborted", "AbortError"));
}, 0);
};
function fixUrl(url) {
try {
return url === "" && g2.location.href ? g2.location.href : url;
} catch (e9) {
return url;
}
}
xhr.open(request.method, fixUrl(request.url), true);
if (request.credentials === "include") {
xhr.withCredentials = true;
} else if (request.credentials === "omit") {
xhr.withCredentials = false;
}
if ("responseType" in xhr) {
if (support.blob) {
xhr.responseType = "blob";
} else if (support.arrayBuffer) {
xhr.responseType = "arraybuffer";
}
}
if (init && typeof init.headers === "object" && !(init.headers instanceof Headers2 || g2.Headers && init.headers instanceof g2.Headers)) {
var names2 = [];
Object.getOwnPropertyNames(init.headers).forEach(function(name) {
names2.push(normalizeName(name));
xhr.setRequestHeader(name, normalizeValue(init.headers[name]));
});
request.headers.forEach(function(value, name) {
if (names2.indexOf(name) === -1) {
xhr.setRequestHeader(name, value);
}
});
} else {
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
});
}
if (request.signal) {
request.signal.addEventListener("abort", abortXhr);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
request.signal.removeEventListener("abort", abortXhr);
}
};
}
xhr.send(typeof request._bodyInit === "undefined" ? null : request._bodyInit);
});
}
var g2, support, viewClasses, isArrayBufferView, methods, redirectStatuses, DOMException;
var init_fetch = __esm({
"../pi-mono/node_modules/whatwg-fetch/fetch.js"() {
init_process_shim();
g2 = typeof globalThis !== "undefined" && globalThis || typeof self !== "undefined" && self || // eslint-disable-next-line no-undef
typeof globalThis !== "undefined" && globalThis || {};
support = {
searchParams: "URLSearchParams" in g2,
iterable: "Symbol" in g2 && "iterator" in Symbol,
blob: "FileReader" in g2 && "Blob" in g2 && (function() {
try {
new Blob();
return true;
} catch (e9) {
return false;
}
})(),
formData: "FormData" in g2,
arrayBuffer: "ArrayBuffer" in g2
};
if (support.arrayBuffer) {
viewClasses = [
"[object Int8Array]",
"[object Uint8Array]",
"[object Uint8ClampedArray]",
"[object Int16Array]",
"[object Uint16Array]",
"[object Int32Array]",
"[object Uint32Array]",
"[object Float32Array]",
"[object Float64Array]"
];
isArrayBufferView = ArrayBuffer.isView || function(obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1;
};
}
Headers2.prototype.append = function(name, value) {
name = normalizeName(name);
value = normalizeValue(value);
var oldValue = this.map[name];
this.map[name] = oldValue ? oldValue + ", " + value : value;
};
Headers2.prototype["delete"] = function(name) {
delete this.map[normalizeName(name)];
};
Headers2.prototype.get = function(name) {
name = normalizeName(name);
return this.has(name) ? this.map[name] : null;
};
Headers2.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name));
};
Headers2.prototype.set = function(name, value) {
this.map[normalizeName(name)] = normalizeValue(value);
};
Headers2.prototype.forEach = function(callback2, thisArg) {
for (var name in this.map) {
if (this.map.hasOwnProperty(name)) {
callback2.call(thisArg, this.map[name], name, this);
}
}
};
Headers2.prototype.keys = function() {
var items = [];
this.forEach(function(value, name) {
items.push(name);
});
return iteratorFor(items);
};
Headers2.prototype.values = function() {
var items = [];
this.forEach(function(value) {
items.push(value);
});
return iteratorFor(items);
};
Headers2.prototype.entries = function() {
var items = [];
this.forEach(function(value, name) {
items.push([name, value]);
});
return iteratorFor(items);
};
if (support.iterable) {
Headers2.prototype[Symbol.iterator] = Headers2.prototype.entries;
}
methods = ["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"];
Request2.prototype.clone = function() {
return new Request2(this, { body: this._bodyInit });
};
Body.call(Request2.prototype);
Body.call(Response2.prototype);
Response2.prototype.clone = function() {
return new Response2(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers2(this.headers),
url: this.url
});
};
Response2.error = function() {
var response = new Response2(null, { status: 200, statusText: "" });
response.ok = false;
response.status = 0;
response.type = "error";
return response;
};
redirectStatuses = [301, 302, 303, 307, 308];
Response2.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError("Invalid status code");
}
return new Response2(null, { status, headers: { location: url } });
};
DOMException = g2.DOMException;
try {
new DOMException();
} catch (err) {
DOMException = function(message, name) {
this.message = message;
this.name = name;
var error = Error(message);
this.stack = error.stack;
};
DOMException.prototype = Object.create(Error.prototype);
DOMException.prototype.constructor = DOMException;
}
fetch2.polyfill = true;
if (!g2.fetch) {
g2.fetch = fetch2;
g2.Headers = Headers2;
g2.Request = Request2;
g2.Response = Response2;
}
}
});
// ../pi-mono/node_modules/ollama/dist/browser.mjs
function getPlatform() {
if (typeof window !== "undefined" && window.navigator) {
const nav = navigator;
if ("userAgentData" in nav && nav.userAgentData?.platform) {
return `${nav.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`;
}
if (navigator.platform) {
return `${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`;
}
return `unknown Browser/${navigator.userAgent};`;
} else if (typeof process !== "undefined") {
return `${process.arch} ${process.platform} Node.js/${process.version}`;
}
return "";
}
function normalizeHeaders(headers) {
if (headers instanceof Headers) {
const obj = {};
headers.forEach((value, key) => {
obj[key] = value;
});
return obj;
} else if (Array.isArray(headers)) {
return Object.fromEntries(headers);
} else {
return headers || {};
}
}
var defaultPort, defaultHost, version, __defProp$1, __defNormalProp$1, __publicField$1, ResponseError, AbortableAsyncIterator, checkOk, readEnvVar, fetchWithHeaders, get2, post, del, parseJSON2, formatHost, __defProp2, __defNormalProp, __publicField, Ollama$1, browser;
var init_browser = __esm({
"../pi-mono/node_modules/ollama/dist/browser.mjs"() {
init_process_shim();
init_fetch();
defaultPort = "11434";
defaultHost = `http://127.0.0.1:${defaultPort}`;
version = "0.6.3";
__defProp$1 = Object.defineProperty;
__defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
__publicField$1 = (obj, key, value) => {
__defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
ResponseError = class _ResponseError extends Error {
constructor(error, status_code) {
super(error);
this.error = error;
this.status_code = status_code;
this.name = "ResponseError";
if (Error.captureStackTrace) {
Error.captureStackTrace(this, _ResponseError);
}
}
};
AbortableAsyncIterator = class {
constructor(abortController, itr, doneCallback) {
__publicField$1(this, "abortController");
__publicField$1(this, "itr");
__publicField$1(this, "doneCallback");
this.abortController = abortController;
this.itr = itr;
this.doneCallback = doneCallback;
}
abort() {
this.abortController.abort();
}
async *[Symbol.asyncIterator]() {
for await (const message of this.itr) {
if ("error" in message) {
throw new Error(message.error);
}
yield message;
if (message.done || message.status === "success") {
this.doneCallback();
return;
}
}
throw new Error("Did not receive done or success response in stream.");
}
};
checkOk = async (response) => {
if (response.ok) {
return;
}
let message = `Error ${response.status}: ${response.statusText}`;
let errorData = null;
if (response.headers.get("content-type")?.includes("application/json")) {
try {
errorData = await response.json();
message = errorData.error || message;
} catch (error) {
console.log("Failed to parse error response as JSON");
}
} else {
try {
console.log("Getting text from response");
const textResponse = await response.text();
message = textResponse || message;
} catch (error) {
console.log("Failed to get text from error response");
}
}
throw new ResponseError(message, response.status);
};
readEnvVar = (obj, key) => {
return obj[key];
};
fetchWithHeaders = async (fetch3, url, options = {}) => {
const defaultHeaders = {
"Content-Type": "application/json",
Accept: "application/json",
"User-Agent": `ollama-js/${version} (${getPlatform()})`
};
options.headers = normalizeHeaders(options.headers);
try {
const parsed = new URL(url);
if (parsed.protocol === "https:" && parsed.hostname === "ollama.com") {
const apiKey = typeof process === "object" && process !== null && typeof process.env === "object" && process.env !== null ? readEnvVar(process.env, "OLLAMA_API_KEY") : void 0;
const authorization = options.headers["authorization"] || options.headers["Authorization"];
if (!authorization && apiKey) {
options.headers["Authorization"] = `Bearer ${apiKey}`;
}
}
} catch (error) {
console.error("error parsing url", error);
}
const customHeaders = Object.fromEntries(
Object.entries(options.headers).filter(
([key]) => !Object.keys(defaultHeaders).some(
(defaultKey) => defaultKey.toLowerCase() === key.toLowerCase()
)
)
);
options.headers = {
...defaultHeaders,
...customHeaders
};
return fetch3(url, options);
};
get2 = async (fetch3, host, options) => {
const response = await fetchWithHeaders(fetch3, host, {
headers: options?.headers
});
await checkOk(response);
return response;
};
post = async (fetch3, host, data, options) => {
const isRecord = (input) => {
return input !== null && typeof input === "object" && !Array.isArray(input);
};
const formattedData = isRecord(data) ? JSON.stringify(data) : data;
const response = await fetchWithHeaders(fetch3, host, {
method: "POST",
body: formattedData,
signal: options?.signal,
headers: options?.headers
});
await checkOk(response);
return response;
};
del = async (fetch3, host, data, options) => {
const response = await fetchWithHeaders(fetch3, host, {
method: "DELETE",
body: JSON.stringify(data),
headers: options?.headers
});
await checkOk(response);
return response;
};
parseJSON2 = async function* (itr) {
const decoder = new TextDecoder("utf-8");
let buffer = "";
const reader = itr.getReader();
while (true) {
const { done, value: chunk } = await reader.read();
if (done) {
break;
}
buffer += decoder.decode(chunk, { stream: true });
const parts = buffer.split("\n");
buffer = parts.pop() ?? "";
for (const part of parts) {
try {
yield JSON.parse(part);
} catch (error) {
console.warn("invalid json: ", part);
}
}
}
buffer += decoder.decode();
for (const part of buffer.split("\n").filter((p4) => p4 !== "")) {
try {
yield JSON.parse(part);
} catch (error) {
console.warn("invalid json: ", part);
}
}
};
formatHost = (host) => {
if (!host) {
return defaultHost;
}
let isExplicitProtocol = host.includes("://");
if (host.startsWith(":")) {
host = `http://127.0.0.1${host}`;
isExplicitProtocol = true;
}
if (!isExplicitProtocol) {
host = `http://${host}`;
}
const url = new URL(host);
let port2 = url.port;
if (!port2) {
if (!isExplicitProtocol) {
port2 = defaultPort;
} else {
port2 = url.protocol === "https:" ? "443" : "80";
}
}
let auth = "";
if (url.username) {
auth = url.username;
if (url.password) {
auth += `:${url.password}`;
}
auth += "@";
}
let formattedHost = `${url.protocol}//${auth}${url.hostname}:${port2}${url.pathname}`;
if (formattedHost.endsWith("/")) {
formattedHost = formattedHost.slice(0, -1);
}
return formattedHost;
};
__defProp2 = Object.defineProperty;
__defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
__publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
Ollama$1 = class Ollama {
constructor(config) {
__publicField(this, "config");
__publicField(this, "fetch");
__publicField(this, "ongoingStreamedRequests", []);
this.config = {
host: "",
headers: config?.headers
};
if (!config?.proxy) {
this.config.host = formatHost(config?.host ?? defaultHost);
}
this.fetch = config?.fetch ?? fetch;
}
// Abort any ongoing streamed requests to Ollama
abort() {
for (const request of this.ongoingStreamedRequests) {
request.abort();
}
this.ongoingStreamedRequests.length = 0;
}
/**
* Processes a request to the Ollama server. If the request is streamable, it will return a
* AbortableAsyncIterator that yields the response messages. Otherwise, it will return the response
* object.
* @param endpoint {string} - The endpoint to send the request to.
* @param request {object} - The request object to send to the endpoint.
* @protected {T | AbortableAsyncIterator} - The response object or a AbortableAsyncIterator that yields
* response messages.
* @throws {Error} - If the response body is missing or if the response is an error.
* @returns {Promise>} - The response object or a AbortableAsyncIterator that yields the streamed response.
*/
async processStreamableRequest(endpoint, request) {
request.stream = request.stream ?? false;
const host = `${this.config.host}/api/${endpoint}`;
if (request.stream) {
const abortController = new AbortController();
const response2 = await post(this.fetch, host, request, {
signal: abortController.signal,
headers: this.config.headers
});
if (!response2.body) {
throw new Error("Missing body");
}
const itr = parseJSON2(response2.body);
const abortableAsyncIterator = new AbortableAsyncIterator(
abortController,
itr,
() => {
const i7 = this.ongoingStreamedRequests.indexOf(abortableAsyncIterator);
if (i7 > -1) {
this.ongoingStreamedRequests.splice(i7, 1);
}
}
);
this.ongoingStreamedRequests.push(abortableAsyncIterator);
return abortableAsyncIterator;
}
const response = await post(this.fetch, host, request, {
headers: this.config.headers
});
return await response.json();
}
/**
* Encodes an image to base64 if it is a Uint8Array.
* @param image {Uint8Array | string} - The image to encode.
* @returns {Promise} - The base64 encoded image.
*/
async encodeImage(image) {
if (typeof image !== "string") {
const uint8Array = new Uint8Array(image);
let byteString = "";
const len = uint8Array.byteLength;
for (let i7 = 0; i7 < len; i7++) {
byteString += String.fromCharCode(uint8Array[i7]);
}
return btoa(byteString);
}
return image;
}
/**
* Generates a response from a text prompt.
* @param request {GenerateRequest} - The request object.
* @returns {Promise>} - The response object or
* an AbortableAsyncIterator that yields response messages.
*/
async generate(request) {
if (request.images) {
request.images = await Promise.all(request.images.map(this.encodeImage.bind(this)));
}
return this.processStreamableRequest("generate", request);
}
/**
* Chats with the model. The request object can contain messages with images that are either
* Uint8Arrays or base64 encoded strings. The images will be base64 encoded before sending the
* request.
* @param request {ChatRequest} - The request object.
* @returns {Promise>} - The response object or an
* AbortableAsyncIterator that yields response messages.
*/
async chat(request) {
if (request.messages) {
for (const message of request.messages) {
if (message.images) {
message.images = await Promise.all(
message.images.map(this.encodeImage.bind(this))
);
}
}
}
return this.processStreamableRequest("chat", request);
}
/**
* Creates a new model from a stream of data.
* @param request {CreateRequest} - The request object.
* @returns {Promise>} - The response object or a stream of progress responses.
*/
async create(request) {
return this.processStreamableRequest("create", {
...request
});
}
/**
* Pulls a model from the Ollama registry. The request object can contain a stream flag to indicate if the
* response should be streamed.
* @param request {PullRequest} - The request object.
* @returns {Promise>} - The response object or
* an AbortableAsyncIterator that yields response messages.
*/
async pull(request) {
return this.processStreamableRequest("pull", {
name: request.model,
stream: request.stream,
insecure: request.insecure
});
}
/**
* Pushes a model to the Ollama registry. The request object can contain a stream flag to indicate if the
* response should be streamed.
* @param request {PushRequest} - The request object.
* @returns {Promise>} - The response object or
* an AbortableAsyncIterator that yields response messages.
*/
async push(request) {
return this.processStreamableRequest("push", {
name: request.model,
stream: request.stream,
insecure: request.insecure
});
}
/**
* Deletes a model from the server. The request object should contain the name of the model to
* delete.
* @param request {DeleteRequest} - The request object.
* @returns {Promise} - The response object.
*/
async delete(request) {
await del(
this.fetch,
`${this.config.host}/api/delete`,
{ name: request.model },
{ headers: this.config.headers }
);
return { status: "success" };
}
/**
* Copies a model from one name to another. The request object should contain the name of the
* model to copy and the new name.
* @param request {CopyRequest} - The request object.
* @returns {Promise} - The response object.
*/
async copy(request) {
await post(this.fetch, `${this.config.host}/api/copy`, { ...request }, {
headers: this.config.headers
});
return { status: "success" };
}
/**
* Lists the models on the server.
* @returns {Promise} - The response object.
* @throws {Error} - If the response body is missing.
*/
async list() {
const response = await get2(this.fetch, `${this.config.host}/api/tags`, {
headers: this.config.headers
});
return await response.json();
}
/**
* Shows the metadata of a model. The request object should contain the name of the model.
* @param request {ShowRequest} - The request object.
* @returns {Promise} - The response object.
*/
async show(request) {
const response = await post(this.fetch, `${this.config.host}/api/show`, {
...request
}, {
headers: this.config.headers
});
return await response.json();
}
/**
* Embeds text input into vectors.
* @param request {EmbedRequest} - The request object.
* @returns {Promise} - The response object.
*/
async embed(request) {
const response = await post(this.fetch, `${this.config.host}/api/embed`, {
...request
}, {
headers: this.config.headers
});
return await response.json();
}
/**
* Embeds a text prompt into a vector.
* @param request {EmbeddingsRequest} - The request object.
* @returns {Promise} - The response object.
*/
async embeddings(request) {
const response = await post(this.fetch, `${this.config.host}/api/embeddings`, {
...request
}, {
headers: this.config.headers
});
return await response.json();
}
/**
* Lists the running models on the server
* @returns {Promise} - The response object.
* @throws {Error} - If the response body is missing.
*/
async ps() {
const response = await get2(this.fetch, `${this.config.host}/api/ps`, {
headers: this.config.headers
});
return await response.json();
}
/**
* Returns the Ollama server version.
* @returns {Promise} - The server version object.
*/
async version() {
const response = await get2(this.fetch, `${this.config.host}/api/version`, {
headers: this.config.headers
});
return await response.json();
}
/**
* Performs web search using the Ollama web search API
* @param request {WebSearchRequest} - The search request containing query and options
* @returns {Promise} - The search results
* @throws {Error} - If the request is invalid or the server returns an error
*/
async webSearch(request) {
if (!request.query || request.query.length === 0) {
throw new Error("Query is required");
}
const response = await post(this.fetch, `https://ollama.com/api/web_search`, { ...request }, {
headers: this.config.headers
});
return await response.json();
}
/**
* Fetches a single page using the Ollama web fetch API
* @param request {WebFetchRequest} - The fetch request containing a URL
* @returns {Promise} - The fetch result
* @throws {Error} - If the request is invalid or the server returns an error
*/
async webFetch(request) {
if (!request.url || request.url.length === 0) {
throw new Error("URL is required");
}
const response = await post(this.fetch, `https://ollama.com/api/web_fetch`, { ...request }, { headers: this.config.headers });
return await response.json();
}
};
browser = new Ollama$1();
}
});
// ../pi-mono/packages/web-ui/dist/utils/model-discovery.js
async function discoverOllamaModels(baseUrl, _apiKey) {
try {
const ollama = new Ollama$1({ host: baseUrl });
const { models } = await ollama.list();
const ollamaModelPromises = models.map(async (model) => {
try {
const details = await ollama.show({
model: model.name
});
const capabilities = details.capabilities || [];
if (!capabilities.includes("tools")) {
console.debug(`Skipping model ${model.name}: does not support tools`);
return null;
}
const modelInfo = details.model_info || {};
const architecture = modelInfo["general.architecture"] || "";
const contextKey = `${architecture}.context_length`;
const contextWindow = parseInt(modelInfo[contextKey] || "8192", 10);
const maxTokens = contextWindow * 10;
const ollamaModel = {
id: model.name,
name: model.name,
api: "openai-completions",
provider: "",
// Will be set by caller
baseUrl: `${baseUrl}/v1`,
reasoning: capabilities.includes("thinking"),
input: ["text"],
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
},
contextWindow,
maxTokens
};
return ollamaModel;
} catch (err) {
console.error(`Failed to fetch details for model ${model.name}:`, err);
return null;
}
});
const results = await Promise.all(ollamaModelPromises);
return results.filter((m4) => m4 !== null);
} catch (err) {
console.error("Failed to discover Ollama models:", err);
throw new Error(`Ollama discovery failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
async function discoverLlamaCppModels(baseUrl, apiKey) {
try {
const headers = {
"Content-Type": "application/json"
};
if (apiKey) {
headers.Authorization = `Bearer ${apiKey}`;
}
const response = await fetch(`${baseUrl}/v1/models`, {
method: "GET",
headers
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data.data || !Array.isArray(data.data)) {
throw new Error("Invalid response format from llama.cpp server");
}
return data.data.map((model) => {
const contextWindow = model.context_length || 8192;
const maxTokens = model.max_tokens || 4096;
const llamaModel = {
id: model.id,
name: model.id,
api: "openai-completions",
provider: "",
// Will be set by caller
baseUrl: `${baseUrl}/v1`,
reasoning: false,
input: ["text"],
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
},
contextWindow,
maxTokens
};
return llamaModel;
});
} catch (err) {
console.error("Failed to discover llama.cpp models:", err);
throw new Error(`llama.cpp discovery failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
async function discoverVLLMModels(baseUrl, apiKey) {
try {
const headers = {
"Content-Type": "application/json"
};
if (apiKey) {
headers.Authorization = `Bearer ${apiKey}`;
}
const response = await fetch(`${baseUrl}/v1/models`, {
method: "GET",
headers
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data.data || !Array.isArray(data.data)) {
throw new Error("Invalid response format from vLLM server");
}
return data.data.map((model) => {
const contextWindow = model.max_model_len || 8192;
const maxTokens = Math.min(contextWindow, 4096);
const vllmModel = {
id: model.id,
name: model.id,
api: "openai-completions",
provider: "",
// Will be set by caller
baseUrl: `${baseUrl}/v1`,
reasoning: false,
input: ["text"],
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
},
contextWindow,
maxTokens
};
return vllmModel;
});
} catch (err) {
console.error("Failed to discover vLLM models:", err);
throw new Error(`vLLM discovery failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
async function discoverLMStudioModels(baseUrl, _apiKey) {
try {
const url = new URL(baseUrl);
const port2 = url.port ? parseInt(url.port, 10) : 1234;
const client = new LMStudioClient({ baseUrl: `ws://${url.hostname}:${port2}` });
const models = await client.system.listDownloadedModels();
return models.filter((model) => model.type === "llm").map((model) => {
const contextWindow = model.maxContextLength;
const maxTokens = contextWindow;
const lmStudioModel = {
id: model.path,
name: model.displayName || model.path,
api: "openai-completions",
provider: "",
// Will be set by caller
baseUrl: `${baseUrl}/v1`,
reasoning: model.trainedForToolUse || false,
input: model.vision ? ["text", "image"] : ["text"],
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
},
contextWindow,
maxTokens
};
return lmStudioModel;
});
} catch (err) {
console.error("Failed to discover LM Studio models:", err);
throw new Error(`LM Studio discovery failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
function isAutoDiscoveryProviderType(type) {
return type === "ollama" || type === "llama.cpp" || type === "vllm" || type === "lmstudio" || type === "openai-compatible";
}
function normalizeOpenAICompatibleBaseUrl(baseUrl) {
const trimmed = baseUrl.replace(/\/+$/, "");
return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
}
async function discoverOpenAICompatibleModels(baseUrl, apiKey) {
try {
const resolvedBaseUrl = normalizeOpenAICompatibleBaseUrl(baseUrl);
console.debug("[OpenAI-Compatible Discovery] Starting discovery", {
inputBaseUrl: baseUrl,
resolvedBaseUrl,
hasApiKey: !!apiKey
});
const headers = {
"Content-Type": "application/json"
};
if (apiKey) {
headers.Authorization = `Bearer ${apiKey}`;
}
const response = await fetch(`${resolvedBaseUrl}/models`, {
method: "GET",
headers
});
console.debug("[OpenAI-Compatible Discovery] Response received", {
resolvedBaseUrl,
status: response.status,
ok: response.ok
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
console.debug("[OpenAI-Compatible Discovery] Payload shape", {
resolvedBaseUrl,
hasDataArray: Array.isArray(data?.data),
modelCount: Array.isArray(data?.data) ? data.data.length : 0,
firstModelId: Array.isArray(data?.data) && data.data.length > 0 ? data.data[0]?.id : null
});
if (!data.data || !Array.isArray(data.data)) {
throw new Error("Invalid response format from OpenAI-compatible server");
}
return data.data.map((model) => {
const contextWindow = model.context_length || model.context_window || model.max_context_length || model.max_model_len || 8192;
const maxTokens = model.max_output_tokens || model.max_completion_tokens || Math.min(contextWindow, 4096);
const supportsVision = Array.isArray(model.input_modalities) && model.input_modalities.includes("image") || Array.isArray(model.modalities) && model.modalities.includes("image");
const reasoning = model.reasoning === true || model.supports_reasoning === true || Array.isArray(model.capabilities) && (model.capabilities.includes("reasoning") || model.capabilities.includes("thinking"));
return {
id: model.id,
name: model.name || model.id,
api: "openai-completions",
provider: "",
// Will be set by caller
baseUrl: resolvedBaseUrl,
reasoning,
input: supportsVision ? ["text", "image"] : ["text"],
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
},
contextWindow,
maxTokens
};
});
} catch (err) {
console.error("Failed to discover OpenAI-compatible models:", err);
throw new Error(`OpenAI-compatible discovery failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
async function discoverModels(type, baseUrl, apiKey) {
switch (type) {
case "ollama":
return discoverOllamaModels(baseUrl, apiKey);
case "llama.cpp":
return discoverLlamaCppModels(baseUrl, apiKey);
case "vllm":
return discoverVLLMModels(baseUrl, apiKey);
case "lmstudio":
return discoverLMStudioModels(baseUrl, apiKey);
case "openai-compatible":
return discoverOpenAICompatibleModels(baseUrl, apiKey);
}
}
function parsePositiveInteger(value) {
if (value === null || value === void 0 || value === "") {
return void 0;
}
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed <= 0) {
return void 0;
}
return Math.round(parsed);
}
function normalizeModelInputs(input) {
const normalized = Array.isArray(input) ? Array.from(new Set(input.filter((item) => typeof item === "string" && item.length > 0))) : [];
if (!normalized.includes("text")) {
normalized.unshift("text");
}
return normalized;
}
function getCustomProviderModelOverride(provider, modelId) {
if (!provider?.modelOverrides || !modelId) {
return {};
}
return provider.modelOverrides[modelId] || {};
}
function applyCustomProviderModelOverrides(provider, model) {
if (!provider || !model) {
return model;
}
const override = getCustomProviderModelOverride(provider, model.id);
const effectiveProvider = provider.name || model.provider || provider.type;
const input = normalizeModelInputs(model.input);
const overrideVision = typeof override.visionCapable === "boolean" ? override.visionCapable : void 0;
const supportsVision = overrideVision ?? input.includes("image");
const effectiveInput = supportsVision ? input.includes("image") ? input : [...input, "image"] : input.filter((item) => item !== "image");
const contextWindow = parsePositiveInteger(override.contextWindow) ?? parsePositiveInteger(model.contextWindow) ?? 8192;
let maxTokens = parsePositiveInteger(override.maxTokens) ?? parsePositiveInteger(model.maxTokens) ?? Math.min(contextWindow, 4096);
maxTokens = Math.min(maxTokens, contextWindow);
return {
...model,
provider: effectiveProvider,
input: effectiveInput,
contextWindow,
maxTokens,
customProviderId: provider.id
};
}
function applyCustomProviderModels(provider, models) {
return (models || []).map((model) => applyCustomProviderModelOverrides(provider, {
...model,
provider: provider.name || model.provider || provider.type
}));
}
function resolveCustomProviderStoredModel(model, customProviders) {
if (!model || !Array.isArray(customProviders) || customProviders.length === 0) {
return model;
}
const provider = customProviders.find((entry) => model.customProviderId ? entry.id === model.customProviderId : entry.name === model.provider);
if (!provider) {
return model;
}
const storedModel = (provider.models || []).find((entry) => entry.id === model.id);
if (!storedModel) {
return {
...model,
provider: provider.name || model.provider,
customProviderId: provider.id
};
}
return applyCustomProviderModelOverrides(provider, storedModel);
}
var init_model_discovery = __esm({
"../pi-mono/packages/web-ui/dist/utils/model-discovery.js"() {
"use strict";
init_process_shim();
init_dist3();
init_browser();
}
});
// ../pi-mono/packages/web-ui/dist/dialogs/ModelSelector.js
function subsequenceScore(query, text3) {
let qi = 0;
let ti = 0;
let gaps = 0;
let lastMatchIndex = -1;
while (qi < query.length && ti < text3.length) {
if (query[qi] === text3[ti]) {
if (lastMatchIndex >= 0) {
gaps += ti - lastMatchIndex - 1;
}
lastMatchIndex = ti;
qi++;
}
ti++;
}
if (qi < query.length)
return 0;
return query.length / (query.length + gaps);
}
var __decorate2, ModelSelector_1, ModelSelector;
var init_ModelSelector = __esm({
"../pi-mono/packages/web-ui/dist/dialogs/ModelSelector.js"() {
"use strict";
init_process_shim();
init_dist();
init_Badge();
init_Button();
init_Dialog();
init_DialogBase();
init_dist2();
init_lit();
init_decorators();
init_ref2();
init_lucide2();
init_Input2();
init_app_storage();
init_format2();
init_i18n2();
init_model_discovery();
__decorate2 = function(decorators, target, key, desc) {
var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
ModelSelector = ModelSelector_1 = class ModelSelector2 extends DialogBase {
constructor() {
super(...arguments);
this.currentModel = null;
this.searchQuery = "";
this.filterThinking = false;
this.filterVision = false;
this.customProvidersLoading = false;
this.selectedIndex = 0;
this.navigationMode = "mouse";
this.customProviderModels = [];
this.scrollContainerRef = e5();
this.searchInputRef = e5();
this.lastMousePosition = { x: 0, y: 0 };
this.modalWidth = "min(400px, 90vw)";
}
static async open(currentModel, onSelect, allowedProviders) {
const selector = new ModelSelector_1();
selector.currentModel = currentModel;
selector.onSelectCallback = onSelect;
if (allowedProviders) {
selector.allowedProviders = new Set(allowedProviders);
}
selector.open();
selector.loadCustomProviders();
}
async firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
await this.updateComplete;
this.searchInputRef.value?.focus();
this.addEventListener("mousemove", (e9) => {
if (e9.clientX !== this.lastMousePosition.x || e9.clientY !== this.lastMousePosition.y) {
this.lastMousePosition = { x: e9.clientX, y: e9.clientY };
if (this.navigationMode === "keyboard") {
this.navigationMode = "mouse";
const target = e9.target;
const modelItem = target.closest("[data-model-item]");
if (modelItem) {
const allItems = this.scrollContainerRef.value?.querySelectorAll("[data-model-item]");
if (allItems) {
const index2 = Array.from(allItems).indexOf(modelItem);
if (index2 !== -1) {
this.selectedIndex = index2;
}
}
}
}
}
});
this.addEventListener("keydown", (e9) => {
const filteredModels = this.getFilteredModels();
if (e9.key === "ArrowDown") {
e9.preventDefault();
this.navigationMode = "keyboard";
this.selectedIndex = Math.min(this.selectedIndex + 1, filteredModels.length - 1);
this.scrollToSelected();
} else if (e9.key === "ArrowUp") {
e9.preventDefault();
this.navigationMode = "keyboard";
this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
this.scrollToSelected();
} else if (e9.key === "Enter") {
e9.preventDefault();
if (filteredModels[this.selectedIndex]) {
this.handleSelect(filteredModels[this.selectedIndex].model);
}
}
});
}
async loadCustomProviders() {
this.customProvidersLoading = true;
const allCustomModels = [];
try {
const storage2 = getAppStorage();
const customProviders = await storage2.customProviders.getAll();
for (const provider of customProviders) {
const isAutoDiscovery = isAutoDiscoveryProviderType(provider.type);
if (isAutoDiscovery) {
try {
const models = await discoverModels(provider.type, provider.baseUrl, provider.apiKey);
const modelsWithProvider = applyCustomProviderModels(provider, models.map((model) => ({
...model,
provider: provider.name
})));
allCustomModels.push(...modelsWithProvider);
} catch (error) {
console.debug(`Failed to load models from ${provider.name}:`, error);
}
} else if (provider.models) {
allCustomModels.push(...applyCustomProviderModels(provider, provider.models));
}
}
} catch (error) {
console.error("Failed to load custom providers:", error);
} finally {
this.customProviderModels = allCustomModels;
this.customProvidersLoading = false;
this.requestUpdate();
}
}
formatTokens(tokens) {
if (tokens >= 1e6)
return `${(tokens / 1e6).toFixed(0)}M`;
if (tokens >= 1e3)
return `${(tokens / 1e3).toFixed(0)}`;
return String(tokens);
}
handleSelect(model) {
if (model) {
this.onSelectCallback?.(model);
this.close();
}
}
getFilteredModels() {
const allModels = [];
const knownProviders = getProviders();
for (const provider of knownProviders) {
const models = getModels(provider);
for (const model of models) {
allModels.push({ provider, id: model.id, model });
}
}
for (const model of this.customProviderModels) {
allModels.push({ provider: model.provider, id: model.id, model });
}
if (this.allowedProviders) {
const allowed = this.allowedProviders;
allModels.splice(0, allModels.length, ...allModels.filter(({ provider }) => allowed.has(provider)));
}
let filteredModels = allModels;
if (this.searchQuery) {
const query = this.searchQuery.toLowerCase().replace(/\s+/g, "");
if (query) {
const scored = [];
for (const entry of filteredModels) {
const searchText = `${entry.provider} ${entry.id} ${entry.model.name}`.toLowerCase();
const score = subsequenceScore(query, searchText);
if (score > 0) {
scored.push({ item: entry, score });
}
}
scored.sort((a3, b4) => b4.score - a3.score);
filteredModels = scored.map((s6) => s6.item);
}
}
if (this.filterThinking) {
filteredModels = filteredModels.filter(({ model }) => model.reasoning);
}
if (this.filterVision) {
filteredModels = filteredModels.filter(({ model }) => model.input.includes("image"));
}
if (!this.searchQuery) {
filteredModels.sort((a3, b4) => {
const aIsCurrent = modelsAreEqual(this.currentModel, a3.model);
const bIsCurrent = modelsAreEqual(this.currentModel, b4.model);
if (aIsCurrent && !bIsCurrent)
return -1;
if (!aIsCurrent && bIsCurrent)
return 1;
return a3.provider.localeCompare(b4.provider);
});
}
return filteredModels;
}
scrollToSelected() {
requestAnimationFrame(() => {
const scrollContainer = this.scrollContainerRef.value;
const selectedElement = scrollContainer?.querySelectorAll("[data-model-item]")[this.selectedIndex];
if (selectedElement) {
selectedElement.scrollIntoView({ block: "nearest", behavior: "smooth" });
}
});
}
renderContent() {
const filteredModels = this.getFilteredModels();
return b2`
${DialogHeader({ title: i18n("Select Model") })}
${Input2({
placeholder: i18n("Search models..."),
value: this.searchQuery,
inputRef: this.searchInputRef,
onInput: (e9) => {
this.searchQuery = e9.target.value;
this.selectedIndex = 0;
if (this.scrollContainerRef.value) {
this.scrollContainerRef.value.scrollTop = 0;
}
}
})}
${Button({
variant: this.filterThinking ? "default" : "secondary",
size: "sm",
onClick: () => {
this.filterThinking = !this.filterThinking;
this.selectedIndex = 0;
if (this.scrollContainerRef.value) {
this.scrollContainerRef.value.scrollTop = 0;
}
},
className: "rounded-full",
children: b2`${icon(Brain, "sm")} ${i18n("Thinking")}`
})}
${Button({
variant: this.filterVision ? "default" : "secondary",
size: "sm",
onClick: () => {
this.filterVision = !this.filterVision;
this.selectedIndex = 0;
if (this.scrollContainerRef.value) {
this.scrollContainerRef.value.scrollTop = 0;
}
},
className: "rounded-full",
children: b2`${icon(Image2, "sm")} ${i18n("Vision")}`
})}
${filteredModels.map(({ provider, id, model }, index2) => {
const isCurrent = modelsAreEqual(this.currentModel, model);
const isSelected = index2 === this.selectedIndex;
return b2`
`;
})}
`;
}
};
__decorate2([
r7()
], ModelSelector.prototype, "currentModel", void 0);
__decorate2([
r7()
], ModelSelector.prototype, "searchQuery", void 0);
__decorate2([
r7()
], ModelSelector.prototype, "filterThinking", void 0);
__decorate2([
r7()
], ModelSelector.prototype, "filterVision", void 0);
__decorate2([
r7()
], ModelSelector.prototype, "customProvidersLoading", void 0);
__decorate2([
r7()
], ModelSelector.prototype, "selectedIndex", void 0);
__decorate2([
r7()
], ModelSelector.prototype, "navigationMode", void 0);
__decorate2([
r7()
], ModelSelector.prototype, "customProviderModels", void 0);
ModelSelector = ModelSelector_1 = __decorate2([
t5("agent-model-selector")
], ModelSelector);
}
});
// ../mini-lit/dist/Select.js
function Select(props) {
const { value, placeholder = i18n("Select an option"), options, onChange, disabled = false, className = "", width = "180px", size = "md", variant = "default", fitContent = false } = props;
const triggerRef = e5();
const state = {
isOpen: false,
focusedIndex: -1
};
const sizeClasses2 = {
sm: "h-8 px-2 text-xs",
md: "h-9 px-3 text-sm",
lg: "h-10 px-4 text-base"
};
const variantClasses = {
default: "text-foreground border-input bg-transparent hover:bg-accent/50 shadow-xs",
ghost: "text-foreground border-transparent bg-transparent hover:bg-accent hover:text-accent-foreground",
outline: "text-foreground border-input bg-transparent hover:bg-accent hover:text-accent-foreground"
};
const flatOptions = [];
const isGrouped = options.length > 0 && "options" in options[0];
if (isGrouped) {
options.forEach((group) => {
flatOptions.push(...group.options.filter((opt) => !opt.disabled));
});
} else {
flatOptions.push(...options.filter((opt) => !opt.disabled));
}
const selectedOption = flatOptions.find((opt) => opt.value === value);
let portalContainer = null;
const ensurePortalContainer = () => {
if (!portalContainer) {
portalContainer = document.createElement("div");
portalContainer.className = "select-portal-container";
portalContainer.style.cssText = "position: fixed; z-index: 50; pointer-events: none;";
document.body.appendChild(portalContainer);
}
return portalContainer;
};
const updatePosition = () => {
if (!triggerRef.value || !portalContainer)
return;
const rect = triggerRef.value.getBoundingClientRect();
state.triggerRect = rect;
const spaceBelow = window.innerHeight - rect.bottom;
const spaceAbove = rect.top;
const dropdownHeight = 300;
const showAbove = spaceBelow < dropdownHeight && spaceAbove > spaceBelow;
portalContainer.style.cssText = `
position: fixed;
left: ${rect.left}px;
${showAbove ? `bottom: ${window.innerHeight - rect.top}px` : `top: ${rect.bottom}px`};
min-width: ${rect.width}px;
width: max-content;
z-index: 50;
pointer-events: ${state.isOpen ? "auto" : "none"};
`;
};
const open2 = () => {
if (disabled || state.isOpen)
return;
if (activeSelect && activeSelect !== api) {
activeSelect.close();
}
state.isOpen = true;
state.focusedIndex = selectedOption ? flatOptions.indexOf(selectedOption) : 0;
ensurePortalContainer();
updatePosition();
renderPortal();
setTimeout(() => {
document.addEventListener("click", handleOutsideClick);
document.addEventListener("keydown", handleKeyDown);
window.addEventListener("scroll", updatePosition, true);
window.addEventListener("resize", updatePosition);
}, 0);
activeSelect = api;
if (triggerRef.value) {
triggerRef.value.setAttribute("aria-expanded", "true");
}
};
const close2 = () => {
if (!state.isOpen)
return;
state.isOpen = false;
state.focusedIndex = -1;
document.removeEventListener("click", handleOutsideClick);
document.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("scroll", updatePosition, true);
window.removeEventListener("resize", updatePosition);
if (portalContainer) {
D(b2``, portalContainer);
}
if (activeSelect === api) {
activeSelect = null;
}
if (triggerRef.value) {
triggerRef.value.setAttribute("aria-expanded", "false");
triggerRef.value.focus();
}
};
const handleOutsideClick = (e9) => {
const target = e9.target;
if (triggerRef.value?.contains(target) || portalContainer?.contains(target)) {
return;
}
close2();
};
const handleKeyDown = (e9) => {
if (!state.isOpen)
return;
switch (e9.key) {
case "Escape":
e9.preventDefault();
close2();
break;
case "ArrowDown":
e9.preventDefault();
state.focusedIndex = Math.min(state.focusedIndex + 1, flatOptions.length - 1);
renderPortal();
break;
case "ArrowUp":
e9.preventDefault();
state.focusedIndex = Math.max(state.focusedIndex - 1, 0);
renderPortal();
break;
case "Enter":
case " ":
e9.preventDefault();
if (state.focusedIndex >= 0 && state.focusedIndex < flatOptions.length) {
selectOption(flatOptions[state.focusedIndex].value);
}
break;
case "Home":
e9.preventDefault();
state.focusedIndex = 0;
renderPortal();
break;
case "End":
e9.preventDefault();
state.focusedIndex = flatOptions.length - 1;
renderPortal();
break;
}
};
const selectOption = (optionValue) => {
onChange(optionValue);
close2();
};
const renderPortal = () => {
if (!portalContainer || !state.isOpen)
return;
const dropdownContent = b2`
${isGrouped ? options.map((group, _groupIndex) => b2`
${group.label ? b2`
${group.label}
` : ""}
${group.options.map((option, _optionIndex) => {
const globalIndex = flatOptions.indexOf(option);
const isFocused = globalIndex === state.focusedIndex;
const isSelected = option.value === value;
return b2`
selectOption(option.value)}
@mouseenter=${() => {
if (!option.disabled) {
state.focusedIndex = globalIndex;
renderPortal();
}
}}
>
${isSelected ? b2`
` : ""}
${option.icon ? b2`${option.icon}` : ""}
${option.label}
`;
})}
`) : options.map((option, index2) => {
const isFocused = index2 === state.focusedIndex;
const isSelected = option.value === value;
return b2`
selectOption(option.value)}
@mouseenter=${() => {
if (!option.disabled) {
state.focusedIndex = index2;
renderPortal();
}
}}
>
${isSelected ? b2`
` : ""}
${option.icon ? b2`${option.icon}` : ""}
${option.label}
`;
})}
`;
D(dropdownContent, portalContainer);
};
const api = { close: close2 };
const handleTriggerClick = (e9) => {
e9.preventDefault();
e9.stopPropagation();
if (state.isOpen) {
close2();
} else {
open2();
}
};
const buttonWidth = fitContent ? "auto" : width;
const minWidth = fitContent ? width || "auto" : void 0;
return b2`
`;
}
var activeSelect;
var init_Select = __esm({
"../mini-lit/dist/Select.js"() {
"use strict";
init_process_shim();
init_lit();
init_ref2();
init_i18n();
activeSelect = null;
}
});
// ../pi-mono/node_modules/jszip/dist/jszip.min.js
var require_jszip_min = __commonJS({
"../pi-mono/node_modules/jszip/dist/jszip.min.js"(exports, module) {
init_process_shim();
!(function(e9) {
if ("object" == typeof exports && "undefined" != typeof module) module.exports = e9();
else if ("function" == typeof define && define.amd) define([], e9);
else {
("undefined" != typeof window ? window : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : this).JSZip = e9();
}
})(function() {
return (function s6(a3, o9, h7) {
function u5(r8, e10) {
if (!o9[r8]) {
if (!a3[r8]) {
var t6 = "function" == typeof __require && __require;
if (!e10 && t6) return t6(r8, true);
if (l5) return l5(r8, true);
var n7 = new Error("Cannot find module '" + r8 + "'");
throw n7.code = "MODULE_NOT_FOUND", n7;
}
var i7 = o9[r8] = { exports: {} };
a3[r8][0].call(i7.exports, function(e11) {
var t7 = a3[r8][1][e11];
return u5(t7 || e11);
}, i7, i7.exports, s6, a3, o9, h7);
}
return o9[r8].exports;
}
for (var l5 = "function" == typeof __require && __require, e9 = 0; e9 < h7.length; e9++) u5(h7[e9]);
return u5;
})({ 1: [function(e9, t6, r8) {
"use strict";
var d4 = e9("./utils"), c6 = e9("./support"), p4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
r8.encode = function(e10) {
for (var t7, r9, n7, i7, s6, a3, o9, h7 = [], u5 = 0, l5 = e10.length, f4 = l5, c7 = "string" !== d4.getTypeOf(e10); u5 < e10.length; ) f4 = l5 - u5, n7 = c7 ? (t7 = e10[u5++], r9 = u5 < l5 ? e10[u5++] : 0, u5 < l5 ? e10[u5++] : 0) : (t7 = e10.charCodeAt(u5++), r9 = u5 < l5 ? e10.charCodeAt(u5++) : 0, u5 < l5 ? e10.charCodeAt(u5++) : 0), i7 = t7 >> 2, s6 = (3 & t7) << 4 | r9 >> 4, a3 = 1 < f4 ? (15 & r9) << 2 | n7 >> 6 : 64, o9 = 2 < f4 ? 63 & n7 : 64, h7.push(p4.charAt(i7) + p4.charAt(s6) + p4.charAt(a3) + p4.charAt(o9));
return h7.join("");
}, r8.decode = function(e10) {
var t7, r9, n7, i7, s6, a3, o9 = 0, h7 = 0, u5 = "data:";
if (e10.substr(0, u5.length) === u5) throw new Error("Invalid base64 input, it looks like a data url.");
var l5, f4 = 3 * (e10 = e10.replace(/[^A-Za-z0-9+/=]/g, "")).length / 4;
if (e10.charAt(e10.length - 1) === p4.charAt(64) && f4--, e10.charAt(e10.length - 2) === p4.charAt(64) && f4--, f4 % 1 != 0) throw new Error("Invalid base64 input, bad content length.");
for (l5 = c6.uint8array ? new Uint8Array(0 | f4) : new Array(0 | f4); o9 < e10.length; ) t7 = p4.indexOf(e10.charAt(o9++)) << 2 | (i7 = p4.indexOf(e10.charAt(o9++))) >> 4, r9 = (15 & i7) << 4 | (s6 = p4.indexOf(e10.charAt(o9++))) >> 2, n7 = (3 & s6) << 6 | (a3 = p4.indexOf(e10.charAt(o9++))), l5[h7++] = t7, 64 !== s6 && (l5[h7++] = r9), 64 !== a3 && (l5[h7++] = n7);
return l5;
};
}, { "./support": 30, "./utils": 32 }], 2: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./external"), i7 = e9("./stream/DataWorker"), s6 = e9("./stream/Crc32Probe"), a3 = e9("./stream/DataLengthProbe");
function o9(e10, t7, r9, n8, i8) {
this.compressedSize = e10, this.uncompressedSize = t7, this.crc32 = r9, this.compression = n8, this.compressedContent = i8;
}
o9.prototype = { getContentWorker: function() {
var e10 = new i7(n7.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a3("data_length")), t7 = this;
return e10.on("end", function() {
if (this.streamInfo.data_length !== t7.uncompressedSize) throw new Error("Bug : uncompressed data size mismatch");
}), e10;
}, getCompressedWorker: function() {
return new i7(n7.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression);
} }, o9.createWorkerFrom = function(e10, t7, r9) {
return e10.pipe(new s6()).pipe(new a3("uncompressedSize")).pipe(t7.compressWorker(r9)).pipe(new a3("compressedSize")).withStreamInfo("compression", t7);
}, t6.exports = o9;
}, { "./external": 6, "./stream/Crc32Probe": 25, "./stream/DataLengthProbe": 26, "./stream/DataWorker": 27 }], 3: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./stream/GenericWorker");
r8.STORE = { magic: "\0\0", compressWorker: function() {
return new n7("STORE compression");
}, uncompressWorker: function() {
return new n7("STORE decompression");
} }, r8.DEFLATE = e9("./flate");
}, { "./flate": 7, "./stream/GenericWorker": 28 }], 4: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./utils");
var o9 = (function() {
for (var e10, t7 = [], r9 = 0; r9 < 256; r9++) {
e10 = r9;
for (var n8 = 0; n8 < 8; n8++) e10 = 1 & e10 ? 3988292384 ^ e10 >>> 1 : e10 >>> 1;
t7[r9] = e10;
}
return t7;
})();
t6.exports = function(e10, t7) {
return void 0 !== e10 && e10.length ? "string" !== n7.getTypeOf(e10) ? (function(e11, t8, r9, n8) {
var i7 = o9, s6 = n8 + r9;
e11 ^= -1;
for (var a3 = n8; a3 < s6; a3++) e11 = e11 >>> 8 ^ i7[255 & (e11 ^ t8[a3])];
return -1 ^ e11;
})(0 | t7, e10, e10.length, 0) : (function(e11, t8, r9, n8) {
var i7 = o9, s6 = n8 + r9;
e11 ^= -1;
for (var a3 = n8; a3 < s6; a3++) e11 = e11 >>> 8 ^ i7[255 & (e11 ^ t8.charCodeAt(a3))];
return -1 ^ e11;
})(0 | t7, e10, e10.length, 0) : 0;
};
}, { "./utils": 32 }], 5: [function(e9, t6, r8) {
"use strict";
r8.base64 = false, r8.binary = false, r8.dir = false, r8.createFolders = true, r8.date = null, r8.compression = null, r8.compressionOptions = null, r8.comment = null, r8.unixPermissions = null, r8.dosPermissions = null;
}, {}], 6: [function(e9, t6, r8) {
"use strict";
var n7 = null;
n7 = "undefined" != typeof Promise ? Promise : e9("lie"), t6.exports = { Promise: n7 };
}, { lie: 37 }], 7: [function(e9, t6, r8) {
"use strict";
var n7 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Uint32Array, i7 = e9("pako"), s6 = e9("./utils"), a3 = e9("./stream/GenericWorker"), o9 = n7 ? "uint8array" : "array";
function h7(e10, t7) {
a3.call(this, "FlateWorker/" + e10), this._pako = null, this._pakoAction = e10, this._pakoOptions = t7, this.meta = {};
}
r8.magic = "\b\0", s6.inherits(h7, a3), h7.prototype.processChunk = function(e10) {
this.meta = e10.meta, null === this._pako && this._createPako(), this._pako.push(s6.transformTo(o9, e10.data), false);
}, h7.prototype.flush = function() {
a3.prototype.flush.call(this), null === this._pako && this._createPako(), this._pako.push([], true);
}, h7.prototype.cleanUp = function() {
a3.prototype.cleanUp.call(this), this._pako = null;
}, h7.prototype._createPako = function() {
this._pako = new i7[this._pakoAction]({ raw: true, level: this._pakoOptions.level || -1 });
var t7 = this;
this._pako.onData = function(e10) {
t7.push({ data: e10, meta: t7.meta });
};
}, r8.compressWorker = function(e10) {
return new h7("Deflate", e10);
}, r8.uncompressWorker = function() {
return new h7("Inflate", {});
};
}, { "./stream/GenericWorker": 28, "./utils": 32, pako: 38 }], 8: [function(e9, t6, r8) {
"use strict";
function A2(e10, t7) {
var r9, n8 = "";
for (r9 = 0; r9 < t7; r9++) n8 += String.fromCharCode(255 & e10), e10 >>>= 8;
return n8;
}
function n7(e10, t7, r9, n8, i8, s7) {
var a3, o9, h7 = e10.file, u5 = e10.compression, l5 = s7 !== O2.utf8encode, f4 = I3.transformTo("string", s7(h7.name)), c6 = I3.transformTo("string", O2.utf8encode(h7.name)), d4 = h7.comment, p4 = I3.transformTo("string", s7(d4)), m4 = I3.transformTo("string", O2.utf8encode(d4)), _3 = c6.length !== h7.name.length, g3 = m4.length !== d4.length, b4 = "", v4 = "", y4 = "", w3 = h7.dir, k2 = h7.date, x2 = { crc32: 0, compressedSize: 0, uncompressedSize: 0 };
t7 && !r9 || (x2.crc32 = e10.crc32, x2.compressedSize = e10.compressedSize, x2.uncompressedSize = e10.uncompressedSize);
var S5 = 0;
t7 && (S5 |= 8), l5 || !_3 && !g3 || (S5 |= 2048);
var z3 = 0, C3 = 0;
w3 && (z3 |= 16), "UNIX" === i8 ? (C3 = 798, z3 |= (function(e11, t8) {
var r10 = e11;
return e11 || (r10 = t8 ? 16893 : 33204), (65535 & r10) << 16;
})(h7.unixPermissions, w3)) : (C3 = 20, z3 |= (function(e11) {
return 63 & (e11 || 0);
})(h7.dosPermissions)), a3 = k2.getUTCHours(), a3 <<= 6, a3 |= k2.getUTCMinutes(), a3 <<= 5, a3 |= k2.getUTCSeconds() / 2, o9 = k2.getUTCFullYear() - 1980, o9 <<= 4, o9 |= k2.getUTCMonth() + 1, o9 <<= 5, o9 |= k2.getUTCDate(), _3 && (v4 = A2(1, 1) + A2(B3(f4), 4) + c6, b4 += "up" + A2(v4.length, 2) + v4), g3 && (y4 = A2(1, 1) + A2(B3(p4), 4) + m4, b4 += "uc" + A2(y4.length, 2) + y4);
var E3 = "";
return E3 += "\n\0", E3 += A2(S5, 2), E3 += u5.magic, E3 += A2(a3, 2), E3 += A2(o9, 2), E3 += A2(x2.crc32, 4), E3 += A2(x2.compressedSize, 4), E3 += A2(x2.uncompressedSize, 4), E3 += A2(f4.length, 2), E3 += A2(b4.length, 2), { fileRecord: R3.LOCAL_FILE_HEADER + E3 + f4 + b4, dirRecord: R3.CENTRAL_FILE_HEADER + A2(C3, 2) + E3 + A2(p4.length, 2) + "\0\0\0\0" + A2(z3, 4) + A2(n8, 4) + f4 + b4 + p4 };
}
var I3 = e9("../utils"), i7 = e9("../stream/GenericWorker"), O2 = e9("../utf8"), B3 = e9("../crc32"), R3 = e9("../signature");
function s6(e10, t7, r9, n8) {
i7.call(this, "ZipFileWorker"), this.bytesWritten = 0, this.zipComment = t7, this.zipPlatform = r9, this.encodeFileName = n8, this.streamFiles = e10, this.accumulate = false, this.contentBuffer = [], this.dirRecords = [], this.currentSourceOffset = 0, this.entriesCount = 0, this.currentFile = null, this._sources = [];
}
I3.inherits(s6, i7), s6.prototype.push = function(e10) {
var t7 = e10.meta.percent || 0, r9 = this.entriesCount, n8 = this._sources.length;
this.accumulate ? this.contentBuffer.push(e10) : (this.bytesWritten += e10.data.length, i7.prototype.push.call(this, { data: e10.data, meta: { currentFile: this.currentFile, percent: r9 ? (t7 + 100 * (r9 - n8 - 1)) / r9 : 100 } }));
}, s6.prototype.openedSource = function(e10) {
this.currentSourceOffset = this.bytesWritten, this.currentFile = e10.file.name;
var t7 = this.streamFiles && !e10.file.dir;
if (t7) {
var r9 = n7(e10, t7, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
this.push({ data: r9.fileRecord, meta: { percent: 0 } });
} else this.accumulate = true;
}, s6.prototype.closedSource = function(e10) {
this.accumulate = false;
var t7 = this.streamFiles && !e10.file.dir, r9 = n7(e10, t7, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
if (this.dirRecords.push(r9.dirRecord), t7) this.push({ data: (function(e11) {
return R3.DATA_DESCRIPTOR + A2(e11.crc32, 4) + A2(e11.compressedSize, 4) + A2(e11.uncompressedSize, 4);
})(e10), meta: { percent: 100 } });
else for (this.push({ data: r9.fileRecord, meta: { percent: 0 } }); this.contentBuffer.length; ) this.push(this.contentBuffer.shift());
this.currentFile = null;
}, s6.prototype.flush = function() {
for (var e10 = this.bytesWritten, t7 = 0; t7 < this.dirRecords.length; t7++) this.push({ data: this.dirRecords[t7], meta: { percent: 100 } });
var r9 = this.bytesWritten - e10, n8 = (function(e11, t8, r10, n9, i8) {
var s7 = I3.transformTo("string", i8(n9));
return R3.CENTRAL_DIRECTORY_END + "\0\0\0\0" + A2(e11, 2) + A2(e11, 2) + A2(t8, 4) + A2(r10, 4) + A2(s7.length, 2) + s7;
})(this.dirRecords.length, r9, e10, this.zipComment, this.encodeFileName);
this.push({ data: n8, meta: { percent: 100 } });
}, s6.prototype.prepareNextSource = function() {
this.previous = this._sources.shift(), this.openedSource(this.previous.streamInfo), this.isPaused ? this.previous.pause() : this.previous.resume();
}, s6.prototype.registerPrevious = function(e10) {
this._sources.push(e10);
var t7 = this;
return e10.on("data", function(e11) {
t7.processChunk(e11);
}), e10.on("end", function() {
t7.closedSource(t7.previous.streamInfo), t7._sources.length ? t7.prepareNextSource() : t7.end();
}), e10.on("error", function(e11) {
t7.error(e11);
}), this;
}, s6.prototype.resume = function() {
return !!i7.prototype.resume.call(this) && (!this.previous && this._sources.length ? (this.prepareNextSource(), true) : this.previous || this._sources.length || this.generatedError ? void 0 : (this.end(), true));
}, s6.prototype.error = function(e10) {
var t7 = this._sources;
if (!i7.prototype.error.call(this, e10)) return false;
for (var r9 = 0; r9 < t7.length; r9++) try {
t7[r9].error(e10);
} catch (e11) {
}
return true;
}, s6.prototype.lock = function() {
i7.prototype.lock.call(this);
for (var e10 = this._sources, t7 = 0; t7 < e10.length; t7++) e10[t7].lock();
}, t6.exports = s6;
}, { "../crc32": 4, "../signature": 23, "../stream/GenericWorker": 28, "../utf8": 31, "../utils": 32 }], 9: [function(e9, t6, r8) {
"use strict";
var u5 = e9("../compressions"), n7 = e9("./ZipFileWorker");
r8.generateWorker = function(e10, a3, t7) {
var o9 = new n7(a3.streamFiles, t7, a3.platform, a3.encodeFileName), h7 = 0;
try {
e10.forEach(function(e11, t8) {
h7++;
var r9 = (function(e12, t9) {
var r10 = e12 || t9, n9 = u5[r10];
if (!n9) throw new Error(r10 + " is not a valid compression method !");
return n9;
})(t8.options.compression, a3.compression), n8 = t8.options.compressionOptions || a3.compressionOptions || {}, i7 = t8.dir, s6 = t8.date;
t8._compressWorker(r9, n8).withStreamInfo("file", { name: e11, dir: i7, date: s6, comment: t8.comment || "", unixPermissions: t8.unixPermissions, dosPermissions: t8.dosPermissions }).pipe(o9);
}), o9.entriesCount = h7;
} catch (e11) {
o9.error(e11);
}
return o9;
};
}, { "../compressions": 3, "./ZipFileWorker": 8 }], 10: [function(e9, t6, r8) {
"use strict";
function n7() {
if (!(this instanceof n7)) return new n7();
if (arguments.length) throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
this.files = /* @__PURE__ */ Object.create(null), this.comment = null, this.root = "", this.clone = function() {
var e10 = new n7();
for (var t7 in this) "function" != typeof this[t7] && (e10[t7] = this[t7]);
return e10;
};
}
(n7.prototype = e9("./object")).loadAsync = e9("./load"), n7.support = e9("./support"), n7.defaults = e9("./defaults"), n7.version = "3.10.1", n7.loadAsync = function(e10, t7) {
return new n7().loadAsync(e10, t7);
}, n7.external = e9("./external"), t6.exports = n7;
}, { "./defaults": 5, "./external": 6, "./load": 11, "./object": 15, "./support": 30 }], 11: [function(e9, t6, r8) {
"use strict";
var u5 = e9("./utils"), i7 = e9("./external"), n7 = e9("./utf8"), s6 = e9("./zipEntries"), a3 = e9("./stream/Crc32Probe"), l5 = e9("./nodejsUtils");
function f4(n8) {
return new i7.Promise(function(e10, t7) {
var r9 = n8.decompressed.getContentWorker().pipe(new a3());
r9.on("error", function(e11) {
t7(e11);
}).on("end", function() {
r9.streamInfo.crc32 !== n8.decompressed.crc32 ? t7(new Error("Corrupted zip : CRC32 mismatch")) : e10();
}).resume();
});
}
t6.exports = function(e10, o9) {
var h7 = this;
return o9 = u5.extend(o9 || {}, { base64: false, checkCRC32: false, optimizedBinaryString: false, createFolders: false, decodeFileName: n7.utf8decode }), l5.isNode && l5.isStream(e10) ? i7.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")) : u5.prepareContent("the loaded zip file", e10, true, o9.optimizedBinaryString, o9.base64).then(function(e11) {
var t7 = new s6(o9);
return t7.load(e11), t7;
}).then(function(e11) {
var t7 = [i7.Promise.resolve(e11)], r9 = e11.files;
if (o9.checkCRC32) for (var n8 = 0; n8 < r9.length; n8++) t7.push(f4(r9[n8]));
return i7.Promise.all(t7);
}).then(function(e11) {
for (var t7 = e11.shift(), r9 = t7.files, n8 = 0; n8 < r9.length; n8++) {
var i8 = r9[n8], s7 = i8.fileNameStr, a4 = u5.resolve(i8.fileNameStr);
h7.file(a4, i8.decompressed, { binary: true, optimizedBinaryString: true, date: i8.date, dir: i8.dir, comment: i8.fileCommentStr.length ? i8.fileCommentStr : null, unixPermissions: i8.unixPermissions, dosPermissions: i8.dosPermissions, createFolders: o9.createFolders }), i8.dir || (h7.file(a4).unsafeOriginalName = s7);
}
return t7.zipComment.length && (h7.comment = t7.zipComment), h7;
});
};
}, { "./external": 6, "./nodejsUtils": 14, "./stream/Crc32Probe": 25, "./utf8": 31, "./utils": 32, "./zipEntries": 33 }], 12: [function(e9, t6, r8) {
"use strict";
var n7 = e9("../utils"), i7 = e9("../stream/GenericWorker");
function s6(e10, t7) {
i7.call(this, "Nodejs stream input adapter for " + e10), this._upstreamEnded = false, this._bindStream(t7);
}
n7.inherits(s6, i7), s6.prototype._bindStream = function(e10) {
var t7 = this;
(this._stream = e10).pause(), e10.on("data", function(e11) {
t7.push({ data: e11, meta: { percent: 0 } });
}).on("error", function(e11) {
t7.isPaused ? this.generatedError = e11 : t7.error(e11);
}).on("end", function() {
t7.isPaused ? t7._upstreamEnded = true : t7.end();
});
}, s6.prototype.pause = function() {
return !!i7.prototype.pause.call(this) && (this._stream.pause(), true);
}, s6.prototype.resume = function() {
return !!i7.prototype.resume.call(this) && (this._upstreamEnded ? this.end() : this._stream.resume(), true);
}, t6.exports = s6;
}, { "../stream/GenericWorker": 28, "../utils": 32 }], 13: [function(e9, t6, r8) {
"use strict";
var i7 = e9("readable-stream").Readable;
function n7(e10, t7, r9) {
i7.call(this, t7), this._helper = e10;
var n8 = this;
e10.on("data", function(e11, t8) {
n8.push(e11) || n8._helper.pause(), r9 && r9(t8);
}).on("error", function(e11) {
n8.emit("error", e11);
}).on("end", function() {
n8.push(null);
});
}
e9("../utils").inherits(n7, i7), n7.prototype._read = function() {
this._helper.resume();
}, t6.exports = n7;
}, { "../utils": 32, "readable-stream": 16 }], 14: [function(e9, t6, r8) {
"use strict";
t6.exports = { isNode: "undefined" != typeof Buffer, newBufferFrom: function(e10, t7) {
if (Buffer.from && Buffer.from !== Uint8Array.from) return Buffer.from(e10, t7);
if ("number" == typeof e10) throw new Error('The "data" argument must not be a number');
return new Buffer(e10, t7);
}, allocBuffer: function(e10) {
if (Buffer.alloc) return Buffer.alloc(e10);
var t7 = new Buffer(e10);
return t7.fill(0), t7;
}, isBuffer: function(e10) {
return Buffer.isBuffer(e10);
}, isStream: function(e10) {
return e10 && "function" == typeof e10.on && "function" == typeof e10.pause && "function" == typeof e10.resume;
} };
}, {}], 15: [function(e9, t6, r8) {
"use strict";
function s6(e10, t7, r9) {
var n8, i8 = u5.getTypeOf(t7), s7 = u5.extend(r9 || {}, f4);
s7.date = s7.date || /* @__PURE__ */ new Date(), null !== s7.compression && (s7.compression = s7.compression.toUpperCase()), "string" == typeof s7.unixPermissions && (s7.unixPermissions = parseInt(s7.unixPermissions, 8)), s7.unixPermissions && 16384 & s7.unixPermissions && (s7.dir = true), s7.dosPermissions && 16 & s7.dosPermissions && (s7.dir = true), s7.dir && (e10 = g3(e10)), s7.createFolders && (n8 = _3(e10)) && b4.call(this, n8, true);
var a4 = "string" === i8 && false === s7.binary && false === s7.base64;
r9 && void 0 !== r9.binary || (s7.binary = !a4), (t7 instanceof c6 && 0 === t7.uncompressedSize || s7.dir || !t7 || 0 === t7.length) && (s7.base64 = false, s7.binary = true, t7 = "", s7.compression = "STORE", i8 = "string");
var o10 = null;
o10 = t7 instanceof c6 || t7 instanceof l5 ? t7 : p4.isNode && p4.isStream(t7) ? new m4(e10, t7) : u5.prepareContent(e10, t7, s7.binary, s7.optimizedBinaryString, s7.base64);
var h8 = new d4(e10, o10, s7);
this.files[e10] = h8;
}
var i7 = e9("./utf8"), u5 = e9("./utils"), l5 = e9("./stream/GenericWorker"), a3 = e9("./stream/StreamHelper"), f4 = e9("./defaults"), c6 = e9("./compressedObject"), d4 = e9("./zipObject"), o9 = e9("./generate"), p4 = e9("./nodejsUtils"), m4 = e9("./nodejs/NodejsStreamInputAdapter"), _3 = function(e10) {
"/" === e10.slice(-1) && (e10 = e10.substring(0, e10.length - 1));
var t7 = e10.lastIndexOf("/");
return 0 < t7 ? e10.substring(0, t7) : "";
}, g3 = function(e10) {
return "/" !== e10.slice(-1) && (e10 += "/"), e10;
}, b4 = function(e10, t7) {
return t7 = void 0 !== t7 ? t7 : f4.createFolders, e10 = g3(e10), this.files[e10] || s6.call(this, e10, null, { dir: true, createFolders: t7 }), this.files[e10];
};
function h7(e10) {
return "[object RegExp]" === Object.prototype.toString.call(e10);
}
var n7 = { load: function() {
throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
}, forEach: function(e10) {
var t7, r9, n8;
for (t7 in this.files) n8 = this.files[t7], (r9 = t7.slice(this.root.length, t7.length)) && t7.slice(0, this.root.length) === this.root && e10(r9, n8);
}, filter: function(r9) {
var n8 = [];
return this.forEach(function(e10, t7) {
r9(e10, t7) && n8.push(t7);
}), n8;
}, file: function(e10, t7, r9) {
if (1 !== arguments.length) return e10 = this.root + e10, s6.call(this, e10, t7, r9), this;
if (h7(e10)) {
var n8 = e10;
return this.filter(function(e11, t8) {
return !t8.dir && n8.test(e11);
});
}
var i8 = this.files[this.root + e10];
return i8 && !i8.dir ? i8 : null;
}, folder: function(r9) {
if (!r9) return this;
if (h7(r9)) return this.filter(function(e11, t8) {
return t8.dir && r9.test(e11);
});
var e10 = this.root + r9, t7 = b4.call(this, e10), n8 = this.clone();
return n8.root = t7.name, n8;
}, remove: function(r9) {
r9 = this.root + r9;
var e10 = this.files[r9];
if (e10 || ("/" !== r9.slice(-1) && (r9 += "/"), e10 = this.files[r9]), e10 && !e10.dir) delete this.files[r9];
else for (var t7 = this.filter(function(e11, t8) {
return t8.name.slice(0, r9.length) === r9;
}), n8 = 0; n8 < t7.length; n8++) delete this.files[t7[n8].name];
return this;
}, generate: function() {
throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
}, generateInternalStream: function(e10) {
var t7, r9 = {};
try {
if ((r9 = u5.extend(e10 || {}, { streamFiles: false, compression: "STORE", compressionOptions: null, type: "", platform: "DOS", comment: null, mimeType: "application/zip", encodeFileName: i7.utf8encode })).type = r9.type.toLowerCase(), r9.compression = r9.compression.toUpperCase(), "binarystring" === r9.type && (r9.type = "string"), !r9.type) throw new Error("No output type specified.");
u5.checkSupport(r9.type), "darwin" !== r9.platform && "freebsd" !== r9.platform && "linux" !== r9.platform && "sunos" !== r9.platform || (r9.platform = "UNIX"), "win32" === r9.platform && (r9.platform = "DOS");
var n8 = r9.comment || this.comment || "";
t7 = o9.generateWorker(this, r9, n8);
} catch (e11) {
(t7 = new l5("error")).error(e11);
}
return new a3(t7, r9.type || "string", r9.mimeType);
}, generateAsync: function(e10, t7) {
return this.generateInternalStream(e10).accumulate(t7);
}, generateNodeStream: function(e10, t7) {
return (e10 = e10 || {}).type || (e10.type = "nodebuffer"), this.generateInternalStream(e10).toNodejsStream(t7);
} };
t6.exports = n7;
}, { "./compressedObject": 2, "./defaults": 5, "./generate": 9, "./nodejs/NodejsStreamInputAdapter": 12, "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31, "./utils": 32, "./zipObject": 35 }], 16: [function(e9, t6, r8) {
"use strict";
t6.exports = e9("stream");
}, { stream: void 0 }], 17: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./DataReader");
function i7(e10) {
n7.call(this, e10);
for (var t7 = 0; t7 < this.data.length; t7++) e10[t7] = 255 & e10[t7];
}
e9("../utils").inherits(i7, n7), i7.prototype.byteAt = function(e10) {
return this.data[this.zero + e10];
}, i7.prototype.lastIndexOfSignature = function(e10) {
for (var t7 = e10.charCodeAt(0), r9 = e10.charCodeAt(1), n8 = e10.charCodeAt(2), i8 = e10.charCodeAt(3), s6 = this.length - 4; 0 <= s6; --s6) if (this.data[s6] === t7 && this.data[s6 + 1] === r9 && this.data[s6 + 2] === n8 && this.data[s6 + 3] === i8) return s6 - this.zero;
return -1;
}, i7.prototype.readAndCheckSignature = function(e10) {
var t7 = e10.charCodeAt(0), r9 = e10.charCodeAt(1), n8 = e10.charCodeAt(2), i8 = e10.charCodeAt(3), s6 = this.readData(4);
return t7 === s6[0] && r9 === s6[1] && n8 === s6[2] && i8 === s6[3];
}, i7.prototype.readData = function(e10) {
if (this.checkOffset(e10), 0 === e10) return [];
var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10);
return this.index += e10, t7;
}, t6.exports = i7;
}, { "../utils": 32, "./DataReader": 18 }], 18: [function(e9, t6, r8) {
"use strict";
var n7 = e9("../utils");
function i7(e10) {
this.data = e10, this.length = e10.length, this.index = 0, this.zero = 0;
}
i7.prototype = { checkOffset: function(e10) {
this.checkIndex(this.index + e10);
}, checkIndex: function(e10) {
if (this.length < this.zero + e10 || e10 < 0) throw new Error("End of data reached (data length = " + this.length + ", asked index = " + e10 + "). Corrupted zip ?");
}, setIndex: function(e10) {
this.checkIndex(e10), this.index = e10;
}, skip: function(e10) {
this.setIndex(this.index + e10);
}, byteAt: function() {
}, readInt: function(e10) {
var t7, r9 = 0;
for (this.checkOffset(e10), t7 = this.index + e10 - 1; t7 >= this.index; t7--) r9 = (r9 << 8) + this.byteAt(t7);
return this.index += e10, r9;
}, readString: function(e10) {
return n7.transformTo("string", this.readData(e10));
}, readData: function() {
}, lastIndexOfSignature: function() {
}, readAndCheckSignature: function() {
}, readDate: function() {
var e10 = this.readInt(4);
return new Date(Date.UTC(1980 + (e10 >> 25 & 127), (e10 >> 21 & 15) - 1, e10 >> 16 & 31, e10 >> 11 & 31, e10 >> 5 & 63, (31 & e10) << 1));
} }, t6.exports = i7;
}, { "../utils": 32 }], 19: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./Uint8ArrayReader");
function i7(e10) {
n7.call(this, e10);
}
e9("../utils").inherits(i7, n7), i7.prototype.readData = function(e10) {
this.checkOffset(e10);
var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10);
return this.index += e10, t7;
}, t6.exports = i7;
}, { "../utils": 32, "./Uint8ArrayReader": 21 }], 20: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./DataReader");
function i7(e10) {
n7.call(this, e10);
}
e9("../utils").inherits(i7, n7), i7.prototype.byteAt = function(e10) {
return this.data.charCodeAt(this.zero + e10);
}, i7.prototype.lastIndexOfSignature = function(e10) {
return this.data.lastIndexOf(e10) - this.zero;
}, i7.prototype.readAndCheckSignature = function(e10) {
return e10 === this.readData(4);
}, i7.prototype.readData = function(e10) {
this.checkOffset(e10);
var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10);
return this.index += e10, t7;
}, t6.exports = i7;
}, { "../utils": 32, "./DataReader": 18 }], 21: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./ArrayReader");
function i7(e10) {
n7.call(this, e10);
}
e9("../utils").inherits(i7, n7), i7.prototype.readData = function(e10) {
if (this.checkOffset(e10), 0 === e10) return new Uint8Array(0);
var t7 = this.data.subarray(this.zero + this.index, this.zero + this.index + e10);
return this.index += e10, t7;
}, t6.exports = i7;
}, { "../utils": 32, "./ArrayReader": 17 }], 22: [function(e9, t6, r8) {
"use strict";
var n7 = e9("../utils"), i7 = e9("../support"), s6 = e9("./ArrayReader"), a3 = e9("./StringReader"), o9 = e9("./NodeBufferReader"), h7 = e9("./Uint8ArrayReader");
t6.exports = function(e10) {
var t7 = n7.getTypeOf(e10);
return n7.checkSupport(t7), "string" !== t7 || i7.uint8array ? "nodebuffer" === t7 ? new o9(e10) : i7.uint8array ? new h7(n7.transformTo("uint8array", e10)) : new s6(n7.transformTo("array", e10)) : new a3(e10);
};
}, { "../support": 30, "../utils": 32, "./ArrayReader": 17, "./NodeBufferReader": 19, "./StringReader": 20, "./Uint8ArrayReader": 21 }], 23: [function(e9, t6, r8) {
"use strict";
r8.LOCAL_FILE_HEADER = "PK", r8.CENTRAL_FILE_HEADER = "PK", r8.CENTRAL_DIRECTORY_END = "PK", r8.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x07", r8.ZIP64_CENTRAL_DIRECTORY_END = "PK", r8.DATA_DESCRIPTOR = "PK\x07\b";
}, {}], 24: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./GenericWorker"), i7 = e9("../utils");
function s6(e10) {
n7.call(this, "ConvertWorker to " + e10), this.destType = e10;
}
i7.inherits(s6, n7), s6.prototype.processChunk = function(e10) {
this.push({ data: i7.transformTo(this.destType, e10.data), meta: e10.meta });
}, t6.exports = s6;
}, { "../utils": 32, "./GenericWorker": 28 }], 25: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./GenericWorker"), i7 = e9("../crc32");
function s6() {
n7.call(this, "Crc32Probe"), this.withStreamInfo("crc32", 0);
}
e9("../utils").inherits(s6, n7), s6.prototype.processChunk = function(e10) {
this.streamInfo.crc32 = i7(e10.data, this.streamInfo.crc32 || 0), this.push(e10);
}, t6.exports = s6;
}, { "../crc32": 4, "../utils": 32, "./GenericWorker": 28 }], 26: [function(e9, t6, r8) {
"use strict";
var n7 = e9("../utils"), i7 = e9("./GenericWorker");
function s6(e10) {
i7.call(this, "DataLengthProbe for " + e10), this.propName = e10, this.withStreamInfo(e10, 0);
}
n7.inherits(s6, i7), s6.prototype.processChunk = function(e10) {
if (e10) {
var t7 = this.streamInfo[this.propName] || 0;
this.streamInfo[this.propName] = t7 + e10.data.length;
}
i7.prototype.processChunk.call(this, e10);
}, t6.exports = s6;
}, { "../utils": 32, "./GenericWorker": 28 }], 27: [function(e9, t6, r8) {
"use strict";
var n7 = e9("../utils"), i7 = e9("./GenericWorker");
function s6(e10) {
i7.call(this, "DataWorker");
var t7 = this;
this.dataIsReady = false, this.index = 0, this.max = 0, this.data = null, this.type = "", this._tickScheduled = false, e10.then(function(e11) {
t7.dataIsReady = true, t7.data = e11, t7.max = e11 && e11.length || 0, t7.type = n7.getTypeOf(e11), t7.isPaused || t7._tickAndRepeat();
}, function(e11) {
t7.error(e11);
});
}
n7.inherits(s6, i7), s6.prototype.cleanUp = function() {
i7.prototype.cleanUp.call(this), this.data = null;
}, s6.prototype.resume = function() {
return !!i7.prototype.resume.call(this) && (!this._tickScheduled && this.dataIsReady && (this._tickScheduled = true, n7.delay(this._tickAndRepeat, [], this)), true);
}, s6.prototype._tickAndRepeat = function() {
this._tickScheduled = false, this.isPaused || this.isFinished || (this._tick(), this.isFinished || (n7.delay(this._tickAndRepeat, [], this), this._tickScheduled = true));
}, s6.prototype._tick = function() {
if (this.isPaused || this.isFinished) return false;
var e10 = null, t7 = Math.min(this.max, this.index + 16384);
if (this.index >= this.max) return this.end();
switch (this.type) {
case "string":
e10 = this.data.substring(this.index, t7);
break;
case "uint8array":
e10 = this.data.subarray(this.index, t7);
break;
case "array":
case "nodebuffer":
e10 = this.data.slice(this.index, t7);
}
return this.index = t7, this.push({ data: e10, meta: { percent: this.max ? this.index / this.max * 100 : 0 } });
}, t6.exports = s6;
}, { "../utils": 32, "./GenericWorker": 28 }], 28: [function(e9, t6, r8) {
"use strict";
function n7(e10) {
this.name = e10 || "default", this.streamInfo = {}, this.generatedError = null, this.extraStreamInfo = {}, this.isPaused = true, this.isFinished = false, this.isLocked = false, this._listeners = { data: [], end: [], error: [] }, this.previous = null;
}
n7.prototype = { push: function(e10) {
this.emit("data", e10);
}, end: function() {
if (this.isFinished) return false;
this.flush();
try {
this.emit("end"), this.cleanUp(), this.isFinished = true;
} catch (e10) {
this.emit("error", e10);
}
return true;
}, error: function(e10) {
return !this.isFinished && (this.isPaused ? this.generatedError = e10 : (this.isFinished = true, this.emit("error", e10), this.previous && this.previous.error(e10), this.cleanUp()), true);
}, on: function(e10, t7) {
return this._listeners[e10].push(t7), this;
}, cleanUp: function() {
this.streamInfo = this.generatedError = this.extraStreamInfo = null, this._listeners = [];
}, emit: function(e10, t7) {
if (this._listeners[e10]) for (var r9 = 0; r9 < this._listeners[e10].length; r9++) this._listeners[e10][r9].call(this, t7);
}, pipe: function(e10) {
return e10.registerPrevious(this);
}, registerPrevious: function(e10) {
if (this.isLocked) throw new Error("The stream '" + this + "' has already been used.");
this.streamInfo = e10.streamInfo, this.mergeStreamInfo(), this.previous = e10;
var t7 = this;
return e10.on("data", function(e11) {
t7.processChunk(e11);
}), e10.on("end", function() {
t7.end();
}), e10.on("error", function(e11) {
t7.error(e11);
}), this;
}, pause: function() {
return !this.isPaused && !this.isFinished && (this.isPaused = true, this.previous && this.previous.pause(), true);
}, resume: function() {
if (!this.isPaused || this.isFinished) return false;
var e10 = this.isPaused = false;
return this.generatedError && (this.error(this.generatedError), e10 = true), this.previous && this.previous.resume(), !e10;
}, flush: function() {
}, processChunk: function(e10) {
this.push(e10);
}, withStreamInfo: function(e10, t7) {
return this.extraStreamInfo[e10] = t7, this.mergeStreamInfo(), this;
}, mergeStreamInfo: function() {
for (var e10 in this.extraStreamInfo) Object.prototype.hasOwnProperty.call(this.extraStreamInfo, e10) && (this.streamInfo[e10] = this.extraStreamInfo[e10]);
}, lock: function() {
if (this.isLocked) throw new Error("The stream '" + this + "' has already been used.");
this.isLocked = true, this.previous && this.previous.lock();
}, toString: function() {
var e10 = "Worker " + this.name;
return this.previous ? this.previous + " -> " + e10 : e10;
} }, t6.exports = n7;
}, {}], 29: [function(e9, t6, r8) {
"use strict";
var h7 = e9("../utils"), i7 = e9("./ConvertWorker"), s6 = e9("./GenericWorker"), u5 = e9("../base64"), n7 = e9("../support"), a3 = e9("../external"), o9 = null;
if (n7.nodestream) try {
o9 = e9("../nodejs/NodejsStreamOutputAdapter");
} catch (e10) {
}
function l5(e10, o10) {
return new a3.Promise(function(t7, r9) {
var n8 = [], i8 = e10._internalType, s7 = e10._outputType, a4 = e10._mimeType;
e10.on("data", function(e11, t8) {
n8.push(e11), o10 && o10(t8);
}).on("error", function(e11) {
n8 = [], r9(e11);
}).on("end", function() {
try {
var e11 = (function(e12, t8, r10) {
switch (e12) {
case "blob":
return h7.newBlob(h7.transformTo("arraybuffer", t8), r10);
case "base64":
return u5.encode(t8);
default:
return h7.transformTo(e12, t8);
}
})(s7, (function(e12, t8) {
var r10, n9 = 0, i9 = null, s8 = 0;
for (r10 = 0; r10 < t8.length; r10++) s8 += t8[r10].length;
switch (e12) {
case "string":
return t8.join("");
case "array":
return Array.prototype.concat.apply([], t8);
case "uint8array":
for (i9 = new Uint8Array(s8), r10 = 0; r10 < t8.length; r10++) i9.set(t8[r10], n9), n9 += t8[r10].length;
return i9;
case "nodebuffer":
return Buffer.concat(t8);
default:
throw new Error("concat : unsupported type '" + e12 + "'");
}
})(i8, n8), a4);
t7(e11);
} catch (e12) {
r9(e12);
}
n8 = [];
}).resume();
});
}
function f4(e10, t7, r9) {
var n8 = t7;
switch (t7) {
case "blob":
case "arraybuffer":
n8 = "uint8array";
break;
case "base64":
n8 = "string";
}
try {
this._internalType = n8, this._outputType = t7, this._mimeType = r9, h7.checkSupport(n8), this._worker = e10.pipe(new i7(n8)), e10.lock();
} catch (e11) {
this._worker = new s6("error"), this._worker.error(e11);
}
}
f4.prototype = { accumulate: function(e10) {
return l5(this, e10);
}, on: function(e10, t7) {
var r9 = this;
return "data" === e10 ? this._worker.on(e10, function(e11) {
t7.call(r9, e11.data, e11.meta);
}) : this._worker.on(e10, function() {
h7.delay(t7, arguments, r9);
}), this;
}, resume: function() {
return h7.delay(this._worker.resume, [], this._worker), this;
}, pause: function() {
return this._worker.pause(), this;
}, toNodejsStream: function(e10) {
if (h7.checkSupport("nodestream"), "nodebuffer" !== this._outputType) throw new Error(this._outputType + " is not supported by this method");
return new o9(this, { objectMode: "nodebuffer" !== this._outputType }, e10);
} }, t6.exports = f4;
}, { "../base64": 1, "../external": 6, "../nodejs/NodejsStreamOutputAdapter": 13, "../support": 30, "../utils": 32, "./ConvertWorker": 24, "./GenericWorker": 28 }], 30: [function(e9, t6, r8) {
"use strict";
if (r8.base64 = true, r8.array = true, r8.string = true, r8.arraybuffer = "undefined" != typeof ArrayBuffer && "undefined" != typeof Uint8Array, r8.nodebuffer = "undefined" != typeof Buffer, r8.uint8array = "undefined" != typeof Uint8Array, "undefined" == typeof ArrayBuffer) r8.blob = false;
else {
var n7 = new ArrayBuffer(0);
try {
r8.blob = 0 === new Blob([n7], { type: "application/zip" }).size;
} catch (e10) {
try {
var i7 = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)();
i7.append(n7), r8.blob = 0 === i7.getBlob("application/zip").size;
} catch (e11) {
r8.blob = false;
}
}
}
try {
r8.nodestream = !!e9("readable-stream").Readable;
} catch (e10) {
r8.nodestream = false;
}
}, { "readable-stream": 16 }], 31: [function(e9, t6, s6) {
"use strict";
for (var o9 = e9("./utils"), h7 = e9("./support"), r8 = e9("./nodejsUtils"), n7 = e9("./stream/GenericWorker"), u5 = new Array(256), i7 = 0; i7 < 256; i7++) u5[i7] = 252 <= i7 ? 6 : 248 <= i7 ? 5 : 240 <= i7 ? 4 : 224 <= i7 ? 3 : 192 <= i7 ? 2 : 1;
u5[254] = u5[254] = 1;
function a3() {
n7.call(this, "utf-8 decode"), this.leftOver = null;
}
function l5() {
n7.call(this, "utf-8 encode");
}
s6.utf8encode = function(e10) {
return h7.nodebuffer ? r8.newBufferFrom(e10, "utf-8") : (function(e11) {
var t7, r9, n8, i8, s7, a4 = e11.length, o10 = 0;
for (i8 = 0; i8 < a4; i8++) 55296 == (64512 & (r9 = e11.charCodeAt(i8))) && i8 + 1 < a4 && 56320 == (64512 & (n8 = e11.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), o10 += r9 < 128 ? 1 : r9 < 2048 ? 2 : r9 < 65536 ? 3 : 4;
for (t7 = h7.uint8array ? new Uint8Array(o10) : new Array(o10), i8 = s7 = 0; s7 < o10; i8++) 55296 == (64512 & (r9 = e11.charCodeAt(i8))) && i8 + 1 < a4 && 56320 == (64512 & (n8 = e11.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), r9 < 128 ? t7[s7++] = r9 : (r9 < 2048 ? t7[s7++] = 192 | r9 >>> 6 : (r9 < 65536 ? t7[s7++] = 224 | r9 >>> 12 : (t7[s7++] = 240 | r9 >>> 18, t7[s7++] = 128 | r9 >>> 12 & 63), t7[s7++] = 128 | r9 >>> 6 & 63), t7[s7++] = 128 | 63 & r9);
return t7;
})(e10);
}, s6.utf8decode = function(e10) {
return h7.nodebuffer ? o9.transformTo("nodebuffer", e10).toString("utf-8") : (function(e11) {
var t7, r9, n8, i8, s7 = e11.length, a4 = new Array(2 * s7);
for (t7 = r9 = 0; t7 < s7; ) if ((n8 = e11[t7++]) < 128) a4[r9++] = n8;
else if (4 < (i8 = u5[n8])) a4[r9++] = 65533, t7 += i8 - 1;
else {
for (n8 &= 2 === i8 ? 31 : 3 === i8 ? 15 : 7; 1 < i8 && t7 < s7; ) n8 = n8 << 6 | 63 & e11[t7++], i8--;
1 < i8 ? a4[r9++] = 65533 : n8 < 65536 ? a4[r9++] = n8 : (n8 -= 65536, a4[r9++] = 55296 | n8 >> 10 & 1023, a4[r9++] = 56320 | 1023 & n8);
}
return a4.length !== r9 && (a4.subarray ? a4 = a4.subarray(0, r9) : a4.length = r9), o9.applyFromCharCode(a4);
})(e10 = o9.transformTo(h7.uint8array ? "uint8array" : "array", e10));
}, o9.inherits(a3, n7), a3.prototype.processChunk = function(e10) {
var t7 = o9.transformTo(h7.uint8array ? "uint8array" : "array", e10.data);
if (this.leftOver && this.leftOver.length) {
if (h7.uint8array) {
var r9 = t7;
(t7 = new Uint8Array(r9.length + this.leftOver.length)).set(this.leftOver, 0), t7.set(r9, this.leftOver.length);
} else t7 = this.leftOver.concat(t7);
this.leftOver = null;
}
var n8 = (function(e11, t8) {
var r10;
for ((t8 = t8 || e11.length) > e11.length && (t8 = e11.length), r10 = t8 - 1; 0 <= r10 && 128 == (192 & e11[r10]); ) r10--;
return r10 < 0 ? t8 : 0 === r10 ? t8 : r10 + u5[e11[r10]] > t8 ? r10 : t8;
})(t7), i8 = t7;
n8 !== t7.length && (h7.uint8array ? (i8 = t7.subarray(0, n8), this.leftOver = t7.subarray(n8, t7.length)) : (i8 = t7.slice(0, n8), this.leftOver = t7.slice(n8, t7.length))), this.push({ data: s6.utf8decode(i8), meta: e10.meta });
}, a3.prototype.flush = function() {
this.leftOver && this.leftOver.length && (this.push({ data: s6.utf8decode(this.leftOver), meta: {} }), this.leftOver = null);
}, s6.Utf8DecodeWorker = a3, o9.inherits(l5, n7), l5.prototype.processChunk = function(e10) {
this.push({ data: s6.utf8encode(e10.data), meta: e10.meta });
}, s6.Utf8EncodeWorker = l5;
}, { "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./support": 30, "./utils": 32 }], 32: [function(e9, t6, a3) {
"use strict";
var o9 = e9("./support"), h7 = e9("./base64"), r8 = e9("./nodejsUtils"), u5 = e9("./external");
function n7(e10) {
return e10;
}
function l5(e10, t7) {
for (var r9 = 0; r9 < e10.length; ++r9) t7[r9] = 255 & e10.charCodeAt(r9);
return t7;
}
e9("setimmediate"), a3.newBlob = function(t7, r9) {
a3.checkSupport("blob");
try {
return new Blob([t7], { type: r9 });
} catch (e10) {
try {
var n8 = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)();
return n8.append(t7), n8.getBlob(r9);
} catch (e11) {
throw new Error("Bug : can't construct the Blob.");
}
}
};
var i7 = { stringifyByChunk: function(e10, t7, r9) {
var n8 = [], i8 = 0, s7 = e10.length;
if (s7 <= r9) return String.fromCharCode.apply(null, e10);
for (; i8 < s7; ) "array" === t7 || "nodebuffer" === t7 ? n8.push(String.fromCharCode.apply(null, e10.slice(i8, Math.min(i8 + r9, s7)))) : n8.push(String.fromCharCode.apply(null, e10.subarray(i8, Math.min(i8 + r9, s7)))), i8 += r9;
return n8.join("");
}, stringifyByChar: function(e10) {
for (var t7 = "", r9 = 0; r9 < e10.length; r9++) t7 += String.fromCharCode(e10[r9]);
return t7;
}, applyCanBeUsed: { uint8array: (function() {
try {
return o9.uint8array && 1 === String.fromCharCode.apply(null, new Uint8Array(1)).length;
} catch (e10) {
return false;
}
})(), nodebuffer: (function() {
try {
return o9.nodebuffer && 1 === String.fromCharCode.apply(null, r8.allocBuffer(1)).length;
} catch (e10) {
return false;
}
})() } };
function s6(e10) {
var t7 = 65536, r9 = a3.getTypeOf(e10), n8 = true;
if ("uint8array" === r9 ? n8 = i7.applyCanBeUsed.uint8array : "nodebuffer" === r9 && (n8 = i7.applyCanBeUsed.nodebuffer), n8) for (; 1 < t7; ) try {
return i7.stringifyByChunk(e10, r9, t7);
} catch (e11) {
t7 = Math.floor(t7 / 2);
}
return i7.stringifyByChar(e10);
}
function f4(e10, t7) {
for (var r9 = 0; r9 < e10.length; r9++) t7[r9] = e10[r9];
return t7;
}
a3.applyFromCharCode = s6;
var c6 = {};
c6.string = { string: n7, array: function(e10) {
return l5(e10, new Array(e10.length));
}, arraybuffer: function(e10) {
return c6.string.uint8array(e10).buffer;
}, uint8array: function(e10) {
return l5(e10, new Uint8Array(e10.length));
}, nodebuffer: function(e10) {
return l5(e10, r8.allocBuffer(e10.length));
} }, c6.array = { string: s6, array: n7, arraybuffer: function(e10) {
return new Uint8Array(e10).buffer;
}, uint8array: function(e10) {
return new Uint8Array(e10);
}, nodebuffer: function(e10) {
return r8.newBufferFrom(e10);
} }, c6.arraybuffer = { string: function(e10) {
return s6(new Uint8Array(e10));
}, array: function(e10) {
return f4(new Uint8Array(e10), new Array(e10.byteLength));
}, arraybuffer: n7, uint8array: function(e10) {
return new Uint8Array(e10);
}, nodebuffer: function(e10) {
return r8.newBufferFrom(new Uint8Array(e10));
} }, c6.uint8array = { string: s6, array: function(e10) {
return f4(e10, new Array(e10.length));
}, arraybuffer: function(e10) {
return e10.buffer;
}, uint8array: n7, nodebuffer: function(e10) {
return r8.newBufferFrom(e10);
} }, c6.nodebuffer = { string: s6, array: function(e10) {
return f4(e10, new Array(e10.length));
}, arraybuffer: function(e10) {
return c6.nodebuffer.uint8array(e10).buffer;
}, uint8array: function(e10) {
return f4(e10, new Uint8Array(e10.length));
}, nodebuffer: n7 }, a3.transformTo = function(e10, t7) {
if (t7 = t7 || "", !e10) return t7;
a3.checkSupport(e10);
var r9 = a3.getTypeOf(t7);
return c6[r9][e10](t7);
}, a3.resolve = function(e10) {
for (var t7 = e10.split("/"), r9 = [], n8 = 0; n8 < t7.length; n8++) {
var i8 = t7[n8];
"." === i8 || "" === i8 && 0 !== n8 && n8 !== t7.length - 1 || (".." === i8 ? r9.pop() : r9.push(i8));
}
return r9.join("/");
}, a3.getTypeOf = function(e10) {
return "string" == typeof e10 ? "string" : "[object Array]" === Object.prototype.toString.call(e10) ? "array" : o9.nodebuffer && r8.isBuffer(e10) ? "nodebuffer" : o9.uint8array && e10 instanceof Uint8Array ? "uint8array" : o9.arraybuffer && e10 instanceof ArrayBuffer ? "arraybuffer" : void 0;
}, a3.checkSupport = function(e10) {
if (!o9[e10.toLowerCase()]) throw new Error(e10 + " is not supported by this platform");
}, a3.MAX_VALUE_16BITS = 65535, a3.MAX_VALUE_32BITS = -1, a3.pretty = function(e10) {
var t7, r9, n8 = "";
for (r9 = 0; r9 < (e10 || "").length; r9++) n8 += "\\x" + ((t7 = e10.charCodeAt(r9)) < 16 ? "0" : "") + t7.toString(16).toUpperCase();
return n8;
}, a3.delay = function(e10, t7, r9) {
setImmediate(function() {
e10.apply(r9 || null, t7 || []);
});
}, a3.inherits = function(e10, t7) {
function r9() {
}
r9.prototype = t7.prototype, e10.prototype = new r9();
}, a3.extend = function() {
var e10, t7, r9 = {};
for (e10 = 0; e10 < arguments.length; e10++) for (t7 in arguments[e10]) Object.prototype.hasOwnProperty.call(arguments[e10], t7) && void 0 === r9[t7] && (r9[t7] = arguments[e10][t7]);
return r9;
}, a3.prepareContent = function(r9, e10, n8, i8, s7) {
return u5.Promise.resolve(e10).then(function(n9) {
return o9.blob && (n9 instanceof Blob || -1 !== ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(n9))) && "undefined" != typeof FileReader ? new u5.Promise(function(t7, r10) {
var e11 = new FileReader();
e11.onload = function(e12) {
t7(e12.target.result);
}, e11.onerror = function(e12) {
r10(e12.target.error);
}, e11.readAsArrayBuffer(n9);
}) : n9;
}).then(function(e11) {
var t7 = a3.getTypeOf(e11);
return t7 ? ("arraybuffer" === t7 ? e11 = a3.transformTo("uint8array", e11) : "string" === t7 && (s7 ? e11 = h7.decode(e11) : n8 && true !== i8 && (e11 = (function(e12) {
return l5(e12, o9.uint8array ? new Uint8Array(e12.length) : new Array(e12.length));
})(e11))), e11) : u5.Promise.reject(new Error("Can't read the data of '" + r9 + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"));
});
};
}, { "./base64": 1, "./external": 6, "./nodejsUtils": 14, "./support": 30, setimmediate: 54 }], 33: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./reader/readerFor"), i7 = e9("./utils"), s6 = e9("./signature"), a3 = e9("./zipEntry"), o9 = e9("./support");
function h7(e10) {
this.files = [], this.loadOptions = e10;
}
h7.prototype = { checkSignature: function(e10) {
if (!this.reader.readAndCheckSignature(e10)) {
this.reader.index -= 4;
var t7 = this.reader.readString(4);
throw new Error("Corrupted zip or bug: unexpected signature (" + i7.pretty(t7) + ", expected " + i7.pretty(e10) + ")");
}
}, isSignature: function(e10, t7) {
var r9 = this.reader.index;
this.reader.setIndex(e10);
var n8 = this.reader.readString(4) === t7;
return this.reader.setIndex(r9), n8;
}, readBlockEndOfCentral: function() {
this.diskNumber = this.reader.readInt(2), this.diskWithCentralDirStart = this.reader.readInt(2), this.centralDirRecordsOnThisDisk = this.reader.readInt(2), this.centralDirRecords = this.reader.readInt(2), this.centralDirSize = this.reader.readInt(4), this.centralDirOffset = this.reader.readInt(4), this.zipCommentLength = this.reader.readInt(2);
var e10 = this.reader.readData(this.zipCommentLength), t7 = o9.uint8array ? "uint8array" : "array", r9 = i7.transformTo(t7, e10);
this.zipComment = this.loadOptions.decodeFileName(r9);
}, readBlockZip64EndOfCentral: function() {
this.zip64EndOfCentralSize = this.reader.readInt(8), this.reader.skip(4), this.diskNumber = this.reader.readInt(4), this.diskWithCentralDirStart = this.reader.readInt(4), this.centralDirRecordsOnThisDisk = this.reader.readInt(8), this.centralDirRecords = this.reader.readInt(8), this.centralDirSize = this.reader.readInt(8), this.centralDirOffset = this.reader.readInt(8), this.zip64ExtensibleData = {};
for (var e10, t7, r9, n8 = this.zip64EndOfCentralSize - 44; 0 < n8; ) e10 = this.reader.readInt(2), t7 = this.reader.readInt(4), r9 = this.reader.readData(t7), this.zip64ExtensibleData[e10] = { id: e10, length: t7, value: r9 };
}, readBlockZip64EndOfCentralLocator: function() {
if (this.diskWithZip64CentralDirStart = this.reader.readInt(4), this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8), this.disksCount = this.reader.readInt(4), 1 < this.disksCount) throw new Error("Multi-volumes zip are not supported");
}, readLocalFiles: function() {
var e10, t7;
for (e10 = 0; e10 < this.files.length; e10++) t7 = this.files[e10], this.reader.setIndex(t7.localHeaderOffset), this.checkSignature(s6.LOCAL_FILE_HEADER), t7.readLocalPart(this.reader), t7.handleUTF8(), t7.processAttributes();
}, readCentralDir: function() {
var e10;
for (this.reader.setIndex(this.centralDirOffset); this.reader.readAndCheckSignature(s6.CENTRAL_FILE_HEADER); ) (e10 = new a3({ zip64: this.zip64 }, this.loadOptions)).readCentralPart(this.reader), this.files.push(e10);
if (this.centralDirRecords !== this.files.length && 0 !== this.centralDirRecords && 0 === this.files.length) throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
}, readEndOfCentral: function() {
var e10 = this.reader.lastIndexOfSignature(s6.CENTRAL_DIRECTORY_END);
if (e10 < 0) throw !this.isSignature(0, s6.LOCAL_FILE_HEADER) ? new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html") : new Error("Corrupted zip: can't find end of central directory");
this.reader.setIndex(e10);
var t7 = e10;
if (this.checkSignature(s6.CENTRAL_DIRECTORY_END), this.readBlockEndOfCentral(), this.diskNumber === i7.MAX_VALUE_16BITS || this.diskWithCentralDirStart === i7.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === i7.MAX_VALUE_16BITS || this.centralDirRecords === i7.MAX_VALUE_16BITS || this.centralDirSize === i7.MAX_VALUE_32BITS || this.centralDirOffset === i7.MAX_VALUE_32BITS) {
if (this.zip64 = true, (e10 = this.reader.lastIndexOfSignature(s6.ZIP64_CENTRAL_DIRECTORY_LOCATOR)) < 0) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
if (this.reader.setIndex(e10), this.checkSignature(s6.ZIP64_CENTRAL_DIRECTORY_LOCATOR), this.readBlockZip64EndOfCentralLocator(), !this.isSignature(this.relativeOffsetEndOfZip64CentralDir, s6.ZIP64_CENTRAL_DIRECTORY_END) && (this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(s6.ZIP64_CENTRAL_DIRECTORY_END), this.relativeOffsetEndOfZip64CentralDir < 0)) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir), this.checkSignature(s6.ZIP64_CENTRAL_DIRECTORY_END), this.readBlockZip64EndOfCentral();
}
var r9 = this.centralDirOffset + this.centralDirSize;
this.zip64 && (r9 += 20, r9 += 12 + this.zip64EndOfCentralSize);
var n8 = t7 - r9;
if (0 < n8) this.isSignature(t7, s6.CENTRAL_FILE_HEADER) || (this.reader.zero = n8);
else if (n8 < 0) throw new Error("Corrupted zip: missing " + Math.abs(n8) + " bytes.");
}, prepareReader: function(e10) {
this.reader = n7(e10);
}, load: function(e10) {
this.prepareReader(e10), this.readEndOfCentral(), this.readCentralDir(), this.readLocalFiles();
} }, t6.exports = h7;
}, { "./reader/readerFor": 22, "./signature": 23, "./support": 30, "./utils": 32, "./zipEntry": 34 }], 34: [function(e9, t6, r8) {
"use strict";
var n7 = e9("./reader/readerFor"), s6 = e9("./utils"), i7 = e9("./compressedObject"), a3 = e9("./crc32"), o9 = e9("./utf8"), h7 = e9("./compressions"), u5 = e9("./support");
function l5(e10, t7) {
this.options = e10, this.loadOptions = t7;
}
l5.prototype = { isEncrypted: function() {
return 1 == (1 & this.bitFlag);
}, useUTF8: function() {
return 2048 == (2048 & this.bitFlag);
}, readLocalPart: function(e10) {
var t7, r9;
if (e10.skip(22), this.fileNameLength = e10.readInt(2), r9 = e10.readInt(2), this.fileName = e10.readData(this.fileNameLength), e10.skip(r9), -1 === this.compressedSize || -1 === this.uncompressedSize) throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");
if (null === (t7 = (function(e11) {
for (var t8 in h7) if (Object.prototype.hasOwnProperty.call(h7, t8) && h7[t8].magic === e11) return h7[t8];
return null;
})(this.compressionMethod))) throw new Error("Corrupted zip : compression " + s6.pretty(this.compressionMethod) + " unknown (inner file : " + s6.transformTo("string", this.fileName) + ")");
this.decompressed = new i7(this.compressedSize, this.uncompressedSize, this.crc32, t7, e10.readData(this.compressedSize));
}, readCentralPart: function(e10) {
this.versionMadeBy = e10.readInt(2), e10.skip(2), this.bitFlag = e10.readInt(2), this.compressionMethod = e10.readString(2), this.date = e10.readDate(), this.crc32 = e10.readInt(4), this.compressedSize = e10.readInt(4), this.uncompressedSize = e10.readInt(4);
var t7 = e10.readInt(2);
if (this.extraFieldsLength = e10.readInt(2), this.fileCommentLength = e10.readInt(2), this.diskNumberStart = e10.readInt(2), this.internalFileAttributes = e10.readInt(2), this.externalFileAttributes = e10.readInt(4), this.localHeaderOffset = e10.readInt(4), this.isEncrypted()) throw new Error("Encrypted zip are not supported");
e10.skip(t7), this.readExtraFields(e10), this.parseZIP64ExtraField(e10), this.fileComment = e10.readData(this.fileCommentLength);
}, processAttributes: function() {
this.unixPermissions = null, this.dosPermissions = null;
var e10 = this.versionMadeBy >> 8;
this.dir = !!(16 & this.externalFileAttributes), 0 == e10 && (this.dosPermissions = 63 & this.externalFileAttributes), 3 == e10 && (this.unixPermissions = this.externalFileAttributes >> 16 & 65535), this.dir || "/" !== this.fileNameStr.slice(-1) || (this.dir = true);
}, parseZIP64ExtraField: function() {
if (this.extraFields[1]) {
var e10 = n7(this.extraFields[1].value);
this.uncompressedSize === s6.MAX_VALUE_32BITS && (this.uncompressedSize = e10.readInt(8)), this.compressedSize === s6.MAX_VALUE_32BITS && (this.compressedSize = e10.readInt(8)), this.localHeaderOffset === s6.MAX_VALUE_32BITS && (this.localHeaderOffset = e10.readInt(8)), this.diskNumberStart === s6.MAX_VALUE_32BITS && (this.diskNumberStart = e10.readInt(4));
}
}, readExtraFields: function(e10) {
var t7, r9, n8, i8 = e10.index + this.extraFieldsLength;
for (this.extraFields || (this.extraFields = {}); e10.index + 4 < i8; ) t7 = e10.readInt(2), r9 = e10.readInt(2), n8 = e10.readData(r9), this.extraFields[t7] = { id: t7, length: r9, value: n8 };
e10.setIndex(i8);
}, handleUTF8: function() {
var e10 = u5.uint8array ? "uint8array" : "array";
if (this.useUTF8()) this.fileNameStr = o9.utf8decode(this.fileName), this.fileCommentStr = o9.utf8decode(this.fileComment);
else {
var t7 = this.findExtraFieldUnicodePath();
if (null !== t7) this.fileNameStr = t7;
else {
var r9 = s6.transformTo(e10, this.fileName);
this.fileNameStr = this.loadOptions.decodeFileName(r9);
}
var n8 = this.findExtraFieldUnicodeComment();
if (null !== n8) this.fileCommentStr = n8;
else {
var i8 = s6.transformTo(e10, this.fileComment);
this.fileCommentStr = this.loadOptions.decodeFileName(i8);
}
}
}, findExtraFieldUnicodePath: function() {
var e10 = this.extraFields[28789];
if (e10) {
var t7 = n7(e10.value);
return 1 !== t7.readInt(1) ? null : a3(this.fileName) !== t7.readInt(4) ? null : o9.utf8decode(t7.readData(e10.length - 5));
}
return null;
}, findExtraFieldUnicodeComment: function() {
var e10 = this.extraFields[25461];
if (e10) {
var t7 = n7(e10.value);
return 1 !== t7.readInt(1) ? null : a3(this.fileComment) !== t7.readInt(4) ? null : o9.utf8decode(t7.readData(e10.length - 5));
}
return null;
} }, t6.exports = l5;
}, { "./compressedObject": 2, "./compressions": 3, "./crc32": 4, "./reader/readerFor": 22, "./support": 30, "./utf8": 31, "./utils": 32 }], 35: [function(e9, t6, r8) {
"use strict";
function n7(e10, t7, r9) {
this.name = e10, this.dir = r9.dir, this.date = r9.date, this.comment = r9.comment, this.unixPermissions = r9.unixPermissions, this.dosPermissions = r9.dosPermissions, this._data = t7, this._dataBinary = r9.binary, this.options = { compression: r9.compression, compressionOptions: r9.compressionOptions };
}
var s6 = e9("./stream/StreamHelper"), i7 = e9("./stream/DataWorker"), a3 = e9("./utf8"), o9 = e9("./compressedObject"), h7 = e9("./stream/GenericWorker");
n7.prototype = { internalStream: function(e10) {
var t7 = null, r9 = "string";
try {
if (!e10) throw new Error("No output type specified.");
var n8 = "string" === (r9 = e10.toLowerCase()) || "text" === r9;
"binarystring" !== r9 && "text" !== r9 || (r9 = "string"), t7 = this._decompressWorker();
var i8 = !this._dataBinary;
i8 && !n8 && (t7 = t7.pipe(new a3.Utf8EncodeWorker())), !i8 && n8 && (t7 = t7.pipe(new a3.Utf8DecodeWorker()));
} catch (e11) {
(t7 = new h7("error")).error(e11);
}
return new s6(t7, r9, "");
}, async: function(e10, t7) {
return this.internalStream(e10).accumulate(t7);
}, nodeStream: function(e10, t7) {
return this.internalStream(e10 || "nodebuffer").toNodejsStream(t7);
}, _compressWorker: function(e10, t7) {
if (this._data instanceof o9 && this._data.compression.magic === e10.magic) return this._data.getCompressedWorker();
var r9 = this._decompressWorker();
return this._dataBinary || (r9 = r9.pipe(new a3.Utf8EncodeWorker())), o9.createWorkerFrom(r9, e10, t7);
}, _decompressWorker: function() {
return this._data instanceof o9 ? this._data.getContentWorker() : this._data instanceof h7 ? this._data : new i7(this._data);
} };
for (var u5 = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"], l5 = function() {
throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
}, f4 = 0; f4 < u5.length; f4++) n7.prototype[u5[f4]] = l5;
t6.exports = n7;
}, { "./compressedObject": 2, "./stream/DataWorker": 27, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31 }], 36: [function(e9, l5, t6) {
(function(t7) {
"use strict";
var r8, n7, e10 = t7.MutationObserver || t7.WebKitMutationObserver;
if (e10) {
var i7 = 0, s6 = new e10(u5), a3 = t7.document.createTextNode("");
s6.observe(a3, { characterData: true }), r8 = function() {
a3.data = i7 = ++i7 % 2;
};
} else if (t7.setImmediate || void 0 === t7.MessageChannel) r8 = "document" in t7 && "onreadystatechange" in t7.document.createElement("script") ? function() {
var e11 = t7.document.createElement("script");
e11.onreadystatechange = function() {
u5(), e11.onreadystatechange = null, e11.parentNode.removeChild(e11), e11 = null;
}, t7.document.documentElement.appendChild(e11);
} : function() {
setTimeout(u5, 0);
};
else {
var o9 = new t7.MessageChannel();
o9.port1.onmessage = u5, r8 = function() {
o9.port2.postMessage(0);
};
}
var h7 = [];
function u5() {
var e11, t8;
n7 = true;
for (var r9 = h7.length; r9; ) {
for (t8 = h7, h7 = [], e11 = -1; ++e11 < r9; ) t8[e11]();
r9 = h7.length;
}
n7 = false;
}
l5.exports = function(e11) {
1 !== h7.push(e11) || n7 || r8();
};
}).call(this, "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {}], 37: [function(e9, t6, r8) {
"use strict";
var i7 = e9("immediate");
function u5() {
}
var l5 = {}, s6 = ["REJECTED"], a3 = ["FULFILLED"], n7 = ["PENDING"];
function o9(e10) {
if ("function" != typeof e10) throw new TypeError("resolver must be a function");
this.state = n7, this.queue = [], this.outcome = void 0, e10 !== u5 && d4(this, e10);
}
function h7(e10, t7, r9) {
this.promise = e10, "function" == typeof t7 && (this.onFulfilled = t7, this.callFulfilled = this.otherCallFulfilled), "function" == typeof r9 && (this.onRejected = r9, this.callRejected = this.otherCallRejected);
}
function f4(t7, r9, n8) {
i7(function() {
var e10;
try {
e10 = r9(n8);
} catch (e11) {
return l5.reject(t7, e11);
}
e10 === t7 ? l5.reject(t7, new TypeError("Cannot resolve promise with itself")) : l5.resolve(t7, e10);
});
}
function c6(e10) {
var t7 = e10 && e10.then;
if (e10 && ("object" == typeof e10 || "function" == typeof e10) && "function" == typeof t7) return function() {
t7.apply(e10, arguments);
};
}
function d4(t7, e10) {
var r9 = false;
function n8(e11) {
r9 || (r9 = true, l5.reject(t7, e11));
}
function i8(e11) {
r9 || (r9 = true, l5.resolve(t7, e11));
}
var s7 = p4(function() {
e10(i8, n8);
});
"error" === s7.status && n8(s7.value);
}
function p4(e10, t7) {
var r9 = {};
try {
r9.value = e10(t7), r9.status = "success";
} catch (e11) {
r9.status = "error", r9.value = e11;
}
return r9;
}
(t6.exports = o9).prototype.finally = function(t7) {
if ("function" != typeof t7) return this;
var r9 = this.constructor;
return this.then(function(e10) {
return r9.resolve(t7()).then(function() {
return e10;
});
}, function(e10) {
return r9.resolve(t7()).then(function() {
throw e10;
});
});
}, o9.prototype.catch = function(e10) {
return this.then(null, e10);
}, o9.prototype.then = function(e10, t7) {
if ("function" != typeof e10 && this.state === a3 || "function" != typeof t7 && this.state === s6) return this;
var r9 = new this.constructor(u5);
this.state !== n7 ? f4(r9, this.state === a3 ? e10 : t7, this.outcome) : this.queue.push(new h7(r9, e10, t7));
return r9;
}, h7.prototype.callFulfilled = function(e10) {
l5.resolve(this.promise, e10);
}, h7.prototype.otherCallFulfilled = function(e10) {
f4(this.promise, this.onFulfilled, e10);
}, h7.prototype.callRejected = function(e10) {
l5.reject(this.promise, e10);
}, h7.prototype.otherCallRejected = function(e10) {
f4(this.promise, this.onRejected, e10);
}, l5.resolve = function(e10, t7) {
var r9 = p4(c6, t7);
if ("error" === r9.status) return l5.reject(e10, r9.value);
var n8 = r9.value;
if (n8) d4(e10, n8);
else {
e10.state = a3, e10.outcome = t7;
for (var i8 = -1, s7 = e10.queue.length; ++i8 < s7; ) e10.queue[i8].callFulfilled(t7);
}
return e10;
}, l5.reject = function(e10, t7) {
e10.state = s6, e10.outcome = t7;
for (var r9 = -1, n8 = e10.queue.length; ++r9 < n8; ) e10.queue[r9].callRejected(t7);
return e10;
}, o9.resolve = function(e10) {
if (e10 instanceof this) return e10;
return l5.resolve(new this(u5), e10);
}, o9.reject = function(e10) {
var t7 = new this(u5);
return l5.reject(t7, e10);
}, o9.all = function(e10) {
var r9 = this;
if ("[object Array]" !== Object.prototype.toString.call(e10)) return this.reject(new TypeError("must be an array"));
var n8 = e10.length, i8 = false;
if (!n8) return this.resolve([]);
var s7 = new Array(n8), a4 = 0, t7 = -1, o10 = new this(u5);
for (; ++t7 < n8; ) h8(e10[t7], t7);
return o10;
function h8(e11, t8) {
r9.resolve(e11).then(function(e12) {
s7[t8] = e12, ++a4 !== n8 || i8 || (i8 = true, l5.resolve(o10, s7));
}, function(e12) {
i8 || (i8 = true, l5.reject(o10, e12));
});
}
}, o9.race = function(e10) {
var t7 = this;
if ("[object Array]" !== Object.prototype.toString.call(e10)) return this.reject(new TypeError("must be an array"));
var r9 = e10.length, n8 = false;
if (!r9) return this.resolve([]);
var i8 = -1, s7 = new this(u5);
for (; ++i8 < r9; ) a4 = e10[i8], t7.resolve(a4).then(function(e11) {
n8 || (n8 = true, l5.resolve(s7, e11));
}, function(e11) {
n8 || (n8 = true, l5.reject(s7, e11));
});
var a4;
return s7;
};
}, { immediate: 36 }], 38: [function(e9, t6, r8) {
"use strict";
var n7 = {};
(0, e9("./lib/utils/common").assign)(n7, e9("./lib/deflate"), e9("./lib/inflate"), e9("./lib/zlib/constants")), t6.exports = n7;
}, { "./lib/deflate": 39, "./lib/inflate": 40, "./lib/utils/common": 41, "./lib/zlib/constants": 44 }], 39: [function(e9, t6, r8) {
"use strict";
var a3 = e9("./zlib/deflate"), o9 = e9("./utils/common"), h7 = e9("./utils/strings"), i7 = e9("./zlib/messages"), s6 = e9("./zlib/zstream"), u5 = Object.prototype.toString, l5 = 0, f4 = -1, c6 = 0, d4 = 8;
function p4(e10) {
if (!(this instanceof p4)) return new p4(e10);
this.options = o9.assign({ level: f4, method: d4, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: c6, to: "" }, e10 || {});
var t7 = this.options;
t7.raw && 0 < t7.windowBits ? t7.windowBits = -t7.windowBits : t7.gzip && 0 < t7.windowBits && t7.windowBits < 16 && (t7.windowBits += 16), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new s6(), this.strm.avail_out = 0;
var r9 = a3.deflateInit2(this.strm, t7.level, t7.method, t7.windowBits, t7.memLevel, t7.strategy);
if (r9 !== l5) throw new Error(i7[r9]);
if (t7.header && a3.deflateSetHeader(this.strm, t7.header), t7.dictionary) {
var n8;
if (n8 = "string" == typeof t7.dictionary ? h7.string2buf(t7.dictionary) : "[object ArrayBuffer]" === u5.call(t7.dictionary) ? new Uint8Array(t7.dictionary) : t7.dictionary, (r9 = a3.deflateSetDictionary(this.strm, n8)) !== l5) throw new Error(i7[r9]);
this._dict_set = true;
}
}
function n7(e10, t7) {
var r9 = new p4(t7);
if (r9.push(e10, true), r9.err) throw r9.msg || i7[r9.err];
return r9.result;
}
p4.prototype.push = function(e10, t7) {
var r9, n8, i8 = this.strm, s7 = this.options.chunkSize;
if (this.ended) return false;
n8 = t7 === ~~t7 ? t7 : true === t7 ? 4 : 0, "string" == typeof e10 ? i8.input = h7.string2buf(e10) : "[object ArrayBuffer]" === u5.call(e10) ? i8.input = new Uint8Array(e10) : i8.input = e10, i8.next_in = 0, i8.avail_in = i8.input.length;
do {
if (0 === i8.avail_out && (i8.output = new o9.Buf8(s7), i8.next_out = 0, i8.avail_out = s7), 1 !== (r9 = a3.deflate(i8, n8)) && r9 !== l5) return this.onEnd(r9), !(this.ended = true);
0 !== i8.avail_out && (0 !== i8.avail_in || 4 !== n8 && 2 !== n8) || ("string" === this.options.to ? this.onData(h7.buf2binstring(o9.shrinkBuf(i8.output, i8.next_out))) : this.onData(o9.shrinkBuf(i8.output, i8.next_out)));
} while ((0 < i8.avail_in || 0 === i8.avail_out) && 1 !== r9);
return 4 === n8 ? (r9 = a3.deflateEnd(this.strm), this.onEnd(r9), this.ended = true, r9 === l5) : 2 !== n8 || (this.onEnd(l5), !(i8.avail_out = 0));
}, p4.prototype.onData = function(e10) {
this.chunks.push(e10);
}, p4.prototype.onEnd = function(e10) {
e10 === l5 && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = o9.flattenChunks(this.chunks)), this.chunks = [], this.err = e10, this.msg = this.strm.msg;
}, r8.Deflate = p4, r8.deflate = n7, r8.deflateRaw = function(e10, t7) {
return (t7 = t7 || {}).raw = true, n7(e10, t7);
}, r8.gzip = function(e10, t7) {
return (t7 = t7 || {}).gzip = true, n7(e10, t7);
};
}, { "./utils/common": 41, "./utils/strings": 42, "./zlib/deflate": 46, "./zlib/messages": 51, "./zlib/zstream": 53 }], 40: [function(e9, t6, r8) {
"use strict";
var c6 = e9("./zlib/inflate"), d4 = e9("./utils/common"), p4 = e9("./utils/strings"), m4 = e9("./zlib/constants"), n7 = e9("./zlib/messages"), i7 = e9("./zlib/zstream"), s6 = e9("./zlib/gzheader"), _3 = Object.prototype.toString;
function a3(e10) {
if (!(this instanceof a3)) return new a3(e10);
this.options = d4.assign({ chunkSize: 16384, windowBits: 0, to: "" }, e10 || {});
var t7 = this.options;
t7.raw && 0 <= t7.windowBits && t7.windowBits < 16 && (t7.windowBits = -t7.windowBits, 0 === t7.windowBits && (t7.windowBits = -15)), !(0 <= t7.windowBits && t7.windowBits < 16) || e10 && e10.windowBits || (t7.windowBits += 32), 15 < t7.windowBits && t7.windowBits < 48 && 0 == (15 & t7.windowBits) && (t7.windowBits |= 15), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new i7(), this.strm.avail_out = 0;
var r9 = c6.inflateInit2(this.strm, t7.windowBits);
if (r9 !== m4.Z_OK) throw new Error(n7[r9]);
this.header = new s6(), c6.inflateGetHeader(this.strm, this.header);
}
function o9(e10, t7) {
var r9 = new a3(t7);
if (r9.push(e10, true), r9.err) throw r9.msg || n7[r9.err];
return r9.result;
}
a3.prototype.push = function(e10, t7) {
var r9, n8, i8, s7, a4, o10, h7 = this.strm, u5 = this.options.chunkSize, l5 = this.options.dictionary, f4 = false;
if (this.ended) return false;
n8 = t7 === ~~t7 ? t7 : true === t7 ? m4.Z_FINISH : m4.Z_NO_FLUSH, "string" == typeof e10 ? h7.input = p4.binstring2buf(e10) : "[object ArrayBuffer]" === _3.call(e10) ? h7.input = new Uint8Array(e10) : h7.input = e10, h7.next_in = 0, h7.avail_in = h7.input.length;
do {
if (0 === h7.avail_out && (h7.output = new d4.Buf8(u5), h7.next_out = 0, h7.avail_out = u5), (r9 = c6.inflate(h7, m4.Z_NO_FLUSH)) === m4.Z_NEED_DICT && l5 && (o10 = "string" == typeof l5 ? p4.string2buf(l5) : "[object ArrayBuffer]" === _3.call(l5) ? new Uint8Array(l5) : l5, r9 = c6.inflateSetDictionary(this.strm, o10)), r9 === m4.Z_BUF_ERROR && true === f4 && (r9 = m4.Z_OK, f4 = false), r9 !== m4.Z_STREAM_END && r9 !== m4.Z_OK) return this.onEnd(r9), !(this.ended = true);
h7.next_out && (0 !== h7.avail_out && r9 !== m4.Z_STREAM_END && (0 !== h7.avail_in || n8 !== m4.Z_FINISH && n8 !== m4.Z_SYNC_FLUSH) || ("string" === this.options.to ? (i8 = p4.utf8border(h7.output, h7.next_out), s7 = h7.next_out - i8, a4 = p4.buf2string(h7.output, i8), h7.next_out = s7, h7.avail_out = u5 - s7, s7 && d4.arraySet(h7.output, h7.output, i8, s7, 0), this.onData(a4)) : this.onData(d4.shrinkBuf(h7.output, h7.next_out)))), 0 === h7.avail_in && 0 === h7.avail_out && (f4 = true);
} while ((0 < h7.avail_in || 0 === h7.avail_out) && r9 !== m4.Z_STREAM_END);
return r9 === m4.Z_STREAM_END && (n8 = m4.Z_FINISH), n8 === m4.Z_FINISH ? (r9 = c6.inflateEnd(this.strm), this.onEnd(r9), this.ended = true, r9 === m4.Z_OK) : n8 !== m4.Z_SYNC_FLUSH || (this.onEnd(m4.Z_OK), !(h7.avail_out = 0));
}, a3.prototype.onData = function(e10) {
this.chunks.push(e10);
}, a3.prototype.onEnd = function(e10) {
e10 === m4.Z_OK && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = d4.flattenChunks(this.chunks)), this.chunks = [], this.err = e10, this.msg = this.strm.msg;
}, r8.Inflate = a3, r8.inflate = o9, r8.inflateRaw = function(e10, t7) {
return (t7 = t7 || {}).raw = true, o9(e10, t7);
}, r8.ungzip = o9;
}, { "./utils/common": 41, "./utils/strings": 42, "./zlib/constants": 44, "./zlib/gzheader": 47, "./zlib/inflate": 49, "./zlib/messages": 51, "./zlib/zstream": 53 }], 41: [function(e9, t6, r8) {
"use strict";
var n7 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Int32Array;
r8.assign = function(e10) {
for (var t7 = Array.prototype.slice.call(arguments, 1); t7.length; ) {
var r9 = t7.shift();
if (r9) {
if ("object" != typeof r9) throw new TypeError(r9 + "must be non-object");
for (var n8 in r9) r9.hasOwnProperty(n8) && (e10[n8] = r9[n8]);
}
}
return e10;
}, r8.shrinkBuf = function(e10, t7) {
return e10.length === t7 ? e10 : e10.subarray ? e10.subarray(0, t7) : (e10.length = t7, e10);
};
var i7 = { arraySet: function(e10, t7, r9, n8, i8) {
if (t7.subarray && e10.subarray) e10.set(t7.subarray(r9, r9 + n8), i8);
else for (var s7 = 0; s7 < n8; s7++) e10[i8 + s7] = t7[r9 + s7];
}, flattenChunks: function(e10) {
var t7, r9, n8, i8, s7, a3;
for (t7 = n8 = 0, r9 = e10.length; t7 < r9; t7++) n8 += e10[t7].length;
for (a3 = new Uint8Array(n8), t7 = i8 = 0, r9 = e10.length; t7 < r9; t7++) s7 = e10[t7], a3.set(s7, i8), i8 += s7.length;
return a3;
} }, s6 = { arraySet: function(e10, t7, r9, n8, i8) {
for (var s7 = 0; s7 < n8; s7++) e10[i8 + s7] = t7[r9 + s7];
}, flattenChunks: function(e10) {
return [].concat.apply([], e10);
} };
r8.setTyped = function(e10) {
e10 ? (r8.Buf8 = Uint8Array, r8.Buf16 = Uint16Array, r8.Buf32 = Int32Array, r8.assign(r8, i7)) : (r8.Buf8 = Array, r8.Buf16 = Array, r8.Buf32 = Array, r8.assign(r8, s6));
}, r8.setTyped(n7);
}, {}], 42: [function(e9, t6, r8) {
"use strict";
var h7 = e9("./common"), i7 = true, s6 = true;
try {
String.fromCharCode.apply(null, [0]);
} catch (e10) {
i7 = false;
}
try {
String.fromCharCode.apply(null, new Uint8Array(1));
} catch (e10) {
s6 = false;
}
for (var u5 = new h7.Buf8(256), n7 = 0; n7 < 256; n7++) u5[n7] = 252 <= n7 ? 6 : 248 <= n7 ? 5 : 240 <= n7 ? 4 : 224 <= n7 ? 3 : 192 <= n7 ? 2 : 1;
function l5(e10, t7) {
if (t7 < 65537 && (e10.subarray && s6 || !e10.subarray && i7)) return String.fromCharCode.apply(null, h7.shrinkBuf(e10, t7));
for (var r9 = "", n8 = 0; n8 < t7; n8++) r9 += String.fromCharCode(e10[n8]);
return r9;
}
u5[254] = u5[254] = 1, r8.string2buf = function(e10) {
var t7, r9, n8, i8, s7, a3 = e10.length, o9 = 0;
for (i8 = 0; i8 < a3; i8++) 55296 == (64512 & (r9 = e10.charCodeAt(i8))) && i8 + 1 < a3 && 56320 == (64512 & (n8 = e10.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), o9 += r9 < 128 ? 1 : r9 < 2048 ? 2 : r9 < 65536 ? 3 : 4;
for (t7 = new h7.Buf8(o9), i8 = s7 = 0; s7 < o9; i8++) 55296 == (64512 & (r9 = e10.charCodeAt(i8))) && i8 + 1 < a3 && 56320 == (64512 & (n8 = e10.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), r9 < 128 ? t7[s7++] = r9 : (r9 < 2048 ? t7[s7++] = 192 | r9 >>> 6 : (r9 < 65536 ? t7[s7++] = 224 | r9 >>> 12 : (t7[s7++] = 240 | r9 >>> 18, t7[s7++] = 128 | r9 >>> 12 & 63), t7[s7++] = 128 | r9 >>> 6 & 63), t7[s7++] = 128 | 63 & r9);
return t7;
}, r8.buf2binstring = function(e10) {
return l5(e10, e10.length);
}, r8.binstring2buf = function(e10) {
for (var t7 = new h7.Buf8(e10.length), r9 = 0, n8 = t7.length; r9 < n8; r9++) t7[r9] = e10.charCodeAt(r9);
return t7;
}, r8.buf2string = function(e10, t7) {
var r9, n8, i8, s7, a3 = t7 || e10.length, o9 = new Array(2 * a3);
for (r9 = n8 = 0; r9 < a3; ) if ((i8 = e10[r9++]) < 128) o9[n8++] = i8;
else if (4 < (s7 = u5[i8])) o9[n8++] = 65533, r9 += s7 - 1;
else {
for (i8 &= 2 === s7 ? 31 : 3 === s7 ? 15 : 7; 1 < s7 && r9 < a3; ) i8 = i8 << 6 | 63 & e10[r9++], s7--;
1 < s7 ? o9[n8++] = 65533 : i8 < 65536 ? o9[n8++] = i8 : (i8 -= 65536, o9[n8++] = 55296 | i8 >> 10 & 1023, o9[n8++] = 56320 | 1023 & i8);
}
return l5(o9, n8);
}, r8.utf8border = function(e10, t7) {
var r9;
for ((t7 = t7 || e10.length) > e10.length && (t7 = e10.length), r9 = t7 - 1; 0 <= r9 && 128 == (192 & e10[r9]); ) r9--;
return r9 < 0 ? t7 : 0 === r9 ? t7 : r9 + u5[e10[r9]] > t7 ? r9 : t7;
};
}, { "./common": 41 }], 43: [function(e9, t6, r8) {
"use strict";
t6.exports = function(e10, t7, r9, n7) {
for (var i7 = 65535 & e10 | 0, s6 = e10 >>> 16 & 65535 | 0, a3 = 0; 0 !== r9; ) {
for (r9 -= a3 = 2e3 < r9 ? 2e3 : r9; s6 = s6 + (i7 = i7 + t7[n7++] | 0) | 0, --a3; ) ;
i7 %= 65521, s6 %= 65521;
}
return i7 | s6 << 16 | 0;
};
}, {}], 44: [function(e9, t6, r8) {
"use strict";
t6.exports = { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_BUF_ERROR: -5, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, Z_BINARY: 0, Z_TEXT: 1, Z_UNKNOWN: 2, Z_DEFLATED: 8 };
}, {}], 45: [function(e9, t6, r8) {
"use strict";
var o9 = (function() {
for (var e10, t7 = [], r9 = 0; r9 < 256; r9++) {
e10 = r9;
for (var n7 = 0; n7 < 8; n7++) e10 = 1 & e10 ? 3988292384 ^ e10 >>> 1 : e10 >>> 1;
t7[r9] = e10;
}
return t7;
})();
t6.exports = function(e10, t7, r9, n7) {
var i7 = o9, s6 = n7 + r9;
e10 ^= -1;
for (var a3 = n7; a3 < s6; a3++) e10 = e10 >>> 8 ^ i7[255 & (e10 ^ t7[a3])];
return -1 ^ e10;
};
}, {}], 46: [function(e9, t6, r8) {
"use strict";
var h7, c6 = e9("../utils/common"), u5 = e9("./trees"), d4 = e9("./adler32"), p4 = e9("./crc32"), n7 = e9("./messages"), l5 = 0, f4 = 4, m4 = 0, _3 = -2, g3 = -1, b4 = 4, i7 = 2, v4 = 8, y4 = 9, s6 = 286, a3 = 30, o9 = 19, w3 = 2 * s6 + 1, k2 = 15, x2 = 3, S5 = 258, z3 = S5 + x2 + 1, C3 = 42, E3 = 113, A2 = 1, I3 = 2, O2 = 3, B3 = 4;
function R3(e10, t7) {
return e10.msg = n7[t7], t7;
}
function T3(e10) {
return (e10 << 1) - (4 < e10 ? 9 : 0);
}
function D4(e10) {
for (var t7 = e10.length; 0 <= --t7; ) e10[t7] = 0;
}
function F2(e10) {
var t7 = e10.state, r9 = t7.pending;
r9 > e10.avail_out && (r9 = e10.avail_out), 0 !== r9 && (c6.arraySet(e10.output, t7.pending_buf, t7.pending_out, r9, e10.next_out), e10.next_out += r9, t7.pending_out += r9, e10.total_out += r9, e10.avail_out -= r9, t7.pending -= r9, 0 === t7.pending && (t7.pending_out = 0));
}
function N3(e10, t7) {
u5._tr_flush_block(e10, 0 <= e10.block_start ? e10.block_start : -1, e10.strstart - e10.block_start, t7), e10.block_start = e10.strstart, F2(e10.strm);
}
function U2(e10, t7) {
e10.pending_buf[e10.pending++] = t7;
}
function P3(e10, t7) {
e10.pending_buf[e10.pending++] = t7 >>> 8 & 255, e10.pending_buf[e10.pending++] = 255 & t7;
}
function L3(e10, t7) {
var r9, n8, i8 = e10.max_chain_length, s7 = e10.strstart, a4 = e10.prev_length, o10 = e10.nice_match, h8 = e10.strstart > e10.w_size - z3 ? e10.strstart - (e10.w_size - z3) : 0, u6 = e10.window, l6 = e10.w_mask, f5 = e10.prev, c7 = e10.strstart + S5, d5 = u6[s7 + a4 - 1], p5 = u6[s7 + a4];
e10.prev_length >= e10.good_match && (i8 >>= 2), o10 > e10.lookahead && (o10 = e10.lookahead);
do {
if (u6[(r9 = t7) + a4] === p5 && u6[r9 + a4 - 1] === d5 && u6[r9] === u6[s7] && u6[++r9] === u6[s7 + 1]) {
s7 += 2, r9++;
do {
} while (u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && s7 < c7);
if (n8 = S5 - (c7 - s7), s7 = c7 - S5, a4 < n8) {
if (e10.match_start = t7, o10 <= (a4 = n8)) break;
d5 = u6[s7 + a4 - 1], p5 = u6[s7 + a4];
}
}
} while ((t7 = f5[t7 & l6]) > h8 && 0 != --i8);
return a4 <= e10.lookahead ? a4 : e10.lookahead;
}
function j3(e10) {
var t7, r9, n8, i8, s7, a4, o10, h8, u6, l6, f5 = e10.w_size;
do {
if (i8 = e10.window_size - e10.lookahead - e10.strstart, e10.strstart >= f5 + (f5 - z3)) {
for (c6.arraySet(e10.window, e10.window, f5, f5, 0), e10.match_start -= f5, e10.strstart -= f5, e10.block_start -= f5, t7 = r9 = e10.hash_size; n8 = e10.head[--t7], e10.head[t7] = f5 <= n8 ? n8 - f5 : 0, --r9; ) ;
for (t7 = r9 = f5; n8 = e10.prev[--t7], e10.prev[t7] = f5 <= n8 ? n8 - f5 : 0, --r9; ) ;
i8 += f5;
}
if (0 === e10.strm.avail_in) break;
if (a4 = e10.strm, o10 = e10.window, h8 = e10.strstart + e10.lookahead, u6 = i8, l6 = void 0, l6 = a4.avail_in, u6 < l6 && (l6 = u6), r9 = 0 === l6 ? 0 : (a4.avail_in -= l6, c6.arraySet(o10, a4.input, a4.next_in, l6, h8), 1 === a4.state.wrap ? a4.adler = d4(a4.adler, o10, l6, h8) : 2 === a4.state.wrap && (a4.adler = p4(a4.adler, o10, l6, h8)), a4.next_in += l6, a4.total_in += l6, l6), e10.lookahead += r9, e10.lookahead + e10.insert >= x2) for (s7 = e10.strstart - e10.insert, e10.ins_h = e10.window[s7], e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[s7 + 1]) & e10.hash_mask; e10.insert && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[s7 + x2 - 1]) & e10.hash_mask, e10.prev[s7 & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = s7, s7++, e10.insert--, !(e10.lookahead + e10.insert < x2)); ) ;
} while (e10.lookahead < z3 && 0 !== e10.strm.avail_in);
}
function Z2(e10, t7) {
for (var r9, n8; ; ) {
if (e10.lookahead < z3) {
if (j3(e10), e10.lookahead < z3 && t7 === l5) return A2;
if (0 === e10.lookahead) break;
}
if (r9 = 0, e10.lookahead >= x2 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), 0 !== r9 && e10.strstart - r9 <= e10.w_size - z3 && (e10.match_length = L3(e10, r9)), e10.match_length >= x2) if (n8 = u5._tr_tally(e10, e10.strstart - e10.match_start, e10.match_length - x2), e10.lookahead -= e10.match_length, e10.match_length <= e10.max_lazy_match && e10.lookahead >= x2) {
for (e10.match_length--; e10.strstart++, e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart, 0 != --e10.match_length; ) ;
e10.strstart++;
} else e10.strstart += e10.match_length, e10.match_length = 0, e10.ins_h = e10.window[e10.strstart], e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + 1]) & e10.hash_mask;
else n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart]), e10.lookahead--, e10.strstart++;
if (n8 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2;
}
return e10.insert = e10.strstart < x2 - 1 ? e10.strstart : x2 - 1, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : e10.last_lit && (N3(e10, false), 0 === e10.strm.avail_out) ? A2 : I3;
}
function W2(e10, t7) {
for (var r9, n8, i8; ; ) {
if (e10.lookahead < z3) {
if (j3(e10), e10.lookahead < z3 && t7 === l5) return A2;
if (0 === e10.lookahead) break;
}
if (r9 = 0, e10.lookahead >= x2 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), e10.prev_length = e10.match_length, e10.prev_match = e10.match_start, e10.match_length = x2 - 1, 0 !== r9 && e10.prev_length < e10.max_lazy_match && e10.strstart - r9 <= e10.w_size - z3 && (e10.match_length = L3(e10, r9), e10.match_length <= 5 && (1 === e10.strategy || e10.match_length === x2 && 4096 < e10.strstart - e10.match_start) && (e10.match_length = x2 - 1)), e10.prev_length >= x2 && e10.match_length <= e10.prev_length) {
for (i8 = e10.strstart + e10.lookahead - x2, n8 = u5._tr_tally(e10, e10.strstart - 1 - e10.prev_match, e10.prev_length - x2), e10.lookahead -= e10.prev_length - 1, e10.prev_length -= 2; ++e10.strstart <= i8 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), 0 != --e10.prev_length; ) ;
if (e10.match_available = 0, e10.match_length = x2 - 1, e10.strstart++, n8 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2;
} else if (e10.match_available) {
if ((n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart - 1])) && N3(e10, false), e10.strstart++, e10.lookahead--, 0 === e10.strm.avail_out) return A2;
} else e10.match_available = 1, e10.strstart++, e10.lookahead--;
}
return e10.match_available && (n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart - 1]), e10.match_available = 0), e10.insert = e10.strstart < x2 - 1 ? e10.strstart : x2 - 1, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : e10.last_lit && (N3(e10, false), 0 === e10.strm.avail_out) ? A2 : I3;
}
function M4(e10, t7, r9, n8, i8) {
this.good_length = e10, this.max_lazy = t7, this.nice_length = r9, this.max_chain = n8, this.func = i8;
}
function H2() {
this.strm = null, this.status = 0, this.pending_buf = null, this.pending_buf_size = 0, this.pending_out = 0, this.pending = 0, this.wrap = 0, this.gzhead = null, this.gzindex = 0, this.method = v4, this.last_flush = -1, this.w_size = 0, this.w_bits = 0, this.w_mask = 0, this.window = null, this.window_size = 0, this.prev = null, this.head = null, this.ins_h = 0, this.hash_size = 0, this.hash_bits = 0, this.hash_mask = 0, this.hash_shift = 0, this.block_start = 0, this.match_length = 0, this.prev_match = 0, this.match_available = 0, this.strstart = 0, this.match_start = 0, this.lookahead = 0, this.prev_length = 0, this.max_chain_length = 0, this.max_lazy_match = 0, this.level = 0, this.strategy = 0, this.good_match = 0, this.nice_match = 0, this.dyn_ltree = new c6.Buf16(2 * w3), this.dyn_dtree = new c6.Buf16(2 * (2 * a3 + 1)), this.bl_tree = new c6.Buf16(2 * (2 * o9 + 1)), D4(this.dyn_ltree), D4(this.dyn_dtree), D4(this.bl_tree), this.l_desc = null, this.d_desc = null, this.bl_desc = null, this.bl_count = new c6.Buf16(k2 + 1), this.heap = new c6.Buf16(2 * s6 + 1), D4(this.heap), this.heap_len = 0, this.heap_max = 0, this.depth = new c6.Buf16(2 * s6 + 1), D4(this.depth), this.l_buf = 0, this.lit_bufsize = 0, this.last_lit = 0, this.d_buf = 0, this.opt_len = 0, this.static_len = 0, this.matches = 0, this.insert = 0, this.bi_buf = 0, this.bi_valid = 0;
}
function G2(e10) {
var t7;
return e10 && e10.state ? (e10.total_in = e10.total_out = 0, e10.data_type = i7, (t7 = e10.state).pending = 0, t7.pending_out = 0, t7.wrap < 0 && (t7.wrap = -t7.wrap), t7.status = t7.wrap ? C3 : E3, e10.adler = 2 === t7.wrap ? 0 : 1, t7.last_flush = l5, u5._tr_init(t7), m4) : R3(e10, _3);
}
function K2(e10) {
var t7 = G2(e10);
return t7 === m4 && (function(e11) {
e11.window_size = 2 * e11.w_size, D4(e11.head), e11.max_lazy_match = h7[e11.level].max_lazy, e11.good_match = h7[e11.level].good_length, e11.nice_match = h7[e11.level].nice_length, e11.max_chain_length = h7[e11.level].max_chain, e11.strstart = 0, e11.block_start = 0, e11.lookahead = 0, e11.insert = 0, e11.match_length = e11.prev_length = x2 - 1, e11.match_available = 0, e11.ins_h = 0;
})(e10.state), t7;
}
function Y(e10, t7, r9, n8, i8, s7) {
if (!e10) return _3;
var a4 = 1;
if (t7 === g3 && (t7 = 6), n8 < 0 ? (a4 = 0, n8 = -n8) : 15 < n8 && (a4 = 2, n8 -= 16), i8 < 1 || y4 < i8 || r9 !== v4 || n8 < 8 || 15 < n8 || t7 < 0 || 9 < t7 || s7 < 0 || b4 < s7) return R3(e10, _3);
8 === n8 && (n8 = 9);
var o10 = new H2();
return (e10.state = o10).strm = e10, o10.wrap = a4, o10.gzhead = null, o10.w_bits = n8, o10.w_size = 1 << o10.w_bits, o10.w_mask = o10.w_size - 1, o10.hash_bits = i8 + 7, o10.hash_size = 1 << o10.hash_bits, o10.hash_mask = o10.hash_size - 1, o10.hash_shift = ~~((o10.hash_bits + x2 - 1) / x2), o10.window = new c6.Buf8(2 * o10.w_size), o10.head = new c6.Buf16(o10.hash_size), o10.prev = new c6.Buf16(o10.w_size), o10.lit_bufsize = 1 << i8 + 6, o10.pending_buf_size = 4 * o10.lit_bufsize, o10.pending_buf = new c6.Buf8(o10.pending_buf_size), o10.d_buf = 1 * o10.lit_bufsize, o10.l_buf = 3 * o10.lit_bufsize, o10.level = t7, o10.strategy = s7, o10.method = r9, K2(e10);
}
h7 = [new M4(0, 0, 0, 0, function(e10, t7) {
var r9 = 65535;
for (r9 > e10.pending_buf_size - 5 && (r9 = e10.pending_buf_size - 5); ; ) {
if (e10.lookahead <= 1) {
if (j3(e10), 0 === e10.lookahead && t7 === l5) return A2;
if (0 === e10.lookahead) break;
}
e10.strstart += e10.lookahead, e10.lookahead = 0;
var n8 = e10.block_start + r9;
if ((0 === e10.strstart || e10.strstart >= n8) && (e10.lookahead = e10.strstart - n8, e10.strstart = n8, N3(e10, false), 0 === e10.strm.avail_out)) return A2;
if (e10.strstart - e10.block_start >= e10.w_size - z3 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2;
}
return e10.insert = 0, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : (e10.strstart > e10.block_start && (N3(e10, false), e10.strm.avail_out), A2);
}), new M4(4, 4, 8, 4, Z2), new M4(4, 5, 16, 8, Z2), new M4(4, 6, 32, 32, Z2), new M4(4, 4, 16, 16, W2), new M4(8, 16, 32, 32, W2), new M4(8, 16, 128, 128, W2), new M4(8, 32, 128, 256, W2), new M4(32, 128, 258, 1024, W2), new M4(32, 258, 258, 4096, W2)], r8.deflateInit = function(e10, t7) {
return Y(e10, t7, v4, 15, 8, 0);
}, r8.deflateInit2 = Y, r8.deflateReset = K2, r8.deflateResetKeep = G2, r8.deflateSetHeader = function(e10, t7) {
return e10 && e10.state ? 2 !== e10.state.wrap ? _3 : (e10.state.gzhead = t7, m4) : _3;
}, r8.deflate = function(e10, t7) {
var r9, n8, i8, s7;
if (!e10 || !e10.state || 5 < t7 || t7 < 0) return e10 ? R3(e10, _3) : _3;
if (n8 = e10.state, !e10.output || !e10.input && 0 !== e10.avail_in || 666 === n8.status && t7 !== f4) return R3(e10, 0 === e10.avail_out ? -5 : _3);
if (n8.strm = e10, r9 = n8.last_flush, n8.last_flush = t7, n8.status === C3) if (2 === n8.wrap) e10.adler = 0, U2(n8, 31), U2(n8, 139), U2(n8, 8), n8.gzhead ? (U2(n8, (n8.gzhead.text ? 1 : 0) + (n8.gzhead.hcrc ? 2 : 0) + (n8.gzhead.extra ? 4 : 0) + (n8.gzhead.name ? 8 : 0) + (n8.gzhead.comment ? 16 : 0)), U2(n8, 255 & n8.gzhead.time), U2(n8, n8.gzhead.time >> 8 & 255), U2(n8, n8.gzhead.time >> 16 & 255), U2(n8, n8.gzhead.time >> 24 & 255), U2(n8, 9 === n8.level ? 2 : 2 <= n8.strategy || n8.level < 2 ? 4 : 0), U2(n8, 255 & n8.gzhead.os), n8.gzhead.extra && n8.gzhead.extra.length && (U2(n8, 255 & n8.gzhead.extra.length), U2(n8, n8.gzhead.extra.length >> 8 & 255)), n8.gzhead.hcrc && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending, 0)), n8.gzindex = 0, n8.status = 69) : (U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 9 === n8.level ? 2 : 2 <= n8.strategy || n8.level < 2 ? 4 : 0), U2(n8, 3), n8.status = E3);
else {
var a4 = v4 + (n8.w_bits - 8 << 4) << 8;
a4 |= (2 <= n8.strategy || n8.level < 2 ? 0 : n8.level < 6 ? 1 : 6 === n8.level ? 2 : 3) << 6, 0 !== n8.strstart && (a4 |= 32), a4 += 31 - a4 % 31, n8.status = E3, P3(n8, a4), 0 !== n8.strstart && (P3(n8, e10.adler >>> 16), P3(n8, 65535 & e10.adler)), e10.adler = 1;
}
if (69 === n8.status) if (n8.gzhead.extra) {
for (i8 = n8.pending; n8.gzindex < (65535 & n8.gzhead.extra.length) && (n8.pending !== n8.pending_buf_size || (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending !== n8.pending_buf_size)); ) U2(n8, 255 & n8.gzhead.extra[n8.gzindex]), n8.gzindex++;
n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), n8.gzindex === n8.gzhead.extra.length && (n8.gzindex = 0, n8.status = 73);
} else n8.status = 73;
if (73 === n8.status) if (n8.gzhead.name) {
i8 = n8.pending;
do {
if (n8.pending === n8.pending_buf_size && (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending === n8.pending_buf_size)) {
s7 = 1;
break;
}
s7 = n8.gzindex < n8.gzhead.name.length ? 255 & n8.gzhead.name.charCodeAt(n8.gzindex++) : 0, U2(n8, s7);
} while (0 !== s7);
n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), 0 === s7 && (n8.gzindex = 0, n8.status = 91);
} else n8.status = 91;
if (91 === n8.status) if (n8.gzhead.comment) {
i8 = n8.pending;
do {
if (n8.pending === n8.pending_buf_size && (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending === n8.pending_buf_size)) {
s7 = 1;
break;
}
s7 = n8.gzindex < n8.gzhead.comment.length ? 255 & n8.gzhead.comment.charCodeAt(n8.gzindex++) : 0, U2(n8, s7);
} while (0 !== s7);
n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), 0 === s7 && (n8.status = 103);
} else n8.status = 103;
if (103 === n8.status && (n8.gzhead.hcrc ? (n8.pending + 2 > n8.pending_buf_size && F2(e10), n8.pending + 2 <= n8.pending_buf_size && (U2(n8, 255 & e10.adler), U2(n8, e10.adler >> 8 & 255), e10.adler = 0, n8.status = E3)) : n8.status = E3), 0 !== n8.pending) {
if (F2(e10), 0 === e10.avail_out) return n8.last_flush = -1, m4;
} else if (0 === e10.avail_in && T3(t7) <= T3(r9) && t7 !== f4) return R3(e10, -5);
if (666 === n8.status && 0 !== e10.avail_in) return R3(e10, -5);
if (0 !== e10.avail_in || 0 !== n8.lookahead || t7 !== l5 && 666 !== n8.status) {
var o10 = 2 === n8.strategy ? (function(e11, t8) {
for (var r10; ; ) {
if (0 === e11.lookahead && (j3(e11), 0 === e11.lookahead)) {
if (t8 === l5) return A2;
break;
}
if (e11.match_length = 0, r10 = u5._tr_tally(e11, 0, e11.window[e11.strstart]), e11.lookahead--, e11.strstart++, r10 && (N3(e11, false), 0 === e11.strm.avail_out)) return A2;
}
return e11.insert = 0, t8 === f4 ? (N3(e11, true), 0 === e11.strm.avail_out ? O2 : B3) : e11.last_lit && (N3(e11, false), 0 === e11.strm.avail_out) ? A2 : I3;
})(n8, t7) : 3 === n8.strategy ? (function(e11, t8) {
for (var r10, n9, i9, s8, a5 = e11.window; ; ) {
if (e11.lookahead <= S5) {
if (j3(e11), e11.lookahead <= S5 && t8 === l5) return A2;
if (0 === e11.lookahead) break;
}
if (e11.match_length = 0, e11.lookahead >= x2 && 0 < e11.strstart && (n9 = a5[i9 = e11.strstart - 1]) === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9]) {
s8 = e11.strstart + S5;
do {
} while (n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && i9 < s8);
e11.match_length = S5 - (s8 - i9), e11.match_length > e11.lookahead && (e11.match_length = e11.lookahead);
}
if (e11.match_length >= x2 ? (r10 = u5._tr_tally(e11, 1, e11.match_length - x2), e11.lookahead -= e11.match_length, e11.strstart += e11.match_length, e11.match_length = 0) : (r10 = u5._tr_tally(e11, 0, e11.window[e11.strstart]), e11.lookahead--, e11.strstart++), r10 && (N3(e11, false), 0 === e11.strm.avail_out)) return A2;
}
return e11.insert = 0, t8 === f4 ? (N3(e11, true), 0 === e11.strm.avail_out ? O2 : B3) : e11.last_lit && (N3(e11, false), 0 === e11.strm.avail_out) ? A2 : I3;
})(n8, t7) : h7[n8.level].func(n8, t7);
if (o10 !== O2 && o10 !== B3 || (n8.status = 666), o10 === A2 || o10 === O2) return 0 === e10.avail_out && (n8.last_flush = -1), m4;
if (o10 === I3 && (1 === t7 ? u5._tr_align(n8) : 5 !== t7 && (u5._tr_stored_block(n8, 0, 0, false), 3 === t7 && (D4(n8.head), 0 === n8.lookahead && (n8.strstart = 0, n8.block_start = 0, n8.insert = 0))), F2(e10), 0 === e10.avail_out)) return n8.last_flush = -1, m4;
}
return t7 !== f4 ? m4 : n8.wrap <= 0 ? 1 : (2 === n8.wrap ? (U2(n8, 255 & e10.adler), U2(n8, e10.adler >> 8 & 255), U2(n8, e10.adler >> 16 & 255), U2(n8, e10.adler >> 24 & 255), U2(n8, 255 & e10.total_in), U2(n8, e10.total_in >> 8 & 255), U2(n8, e10.total_in >> 16 & 255), U2(n8, e10.total_in >> 24 & 255)) : (P3(n8, e10.adler >>> 16), P3(n8, 65535 & e10.adler)), F2(e10), 0 < n8.wrap && (n8.wrap = -n8.wrap), 0 !== n8.pending ? m4 : 1);
}, r8.deflateEnd = function(e10) {
var t7;
return e10 && e10.state ? (t7 = e10.state.status) !== C3 && 69 !== t7 && 73 !== t7 && 91 !== t7 && 103 !== t7 && t7 !== E3 && 666 !== t7 ? R3(e10, _3) : (e10.state = null, t7 === E3 ? R3(e10, -3) : m4) : _3;
}, r8.deflateSetDictionary = function(e10, t7) {
var r9, n8, i8, s7, a4, o10, h8, u6, l6 = t7.length;
if (!e10 || !e10.state) return _3;
if (2 === (s7 = (r9 = e10.state).wrap) || 1 === s7 && r9.status !== C3 || r9.lookahead) return _3;
for (1 === s7 && (e10.adler = d4(e10.adler, t7, l6, 0)), r9.wrap = 0, l6 >= r9.w_size && (0 === s7 && (D4(r9.head), r9.strstart = 0, r9.block_start = 0, r9.insert = 0), u6 = new c6.Buf8(r9.w_size), c6.arraySet(u6, t7, l6 - r9.w_size, r9.w_size, 0), t7 = u6, l6 = r9.w_size), a4 = e10.avail_in, o10 = e10.next_in, h8 = e10.input, e10.avail_in = l6, e10.next_in = 0, e10.input = t7, j3(r9); r9.lookahead >= x2; ) {
for (n8 = r9.strstart, i8 = r9.lookahead - (x2 - 1); r9.ins_h = (r9.ins_h << r9.hash_shift ^ r9.window[n8 + x2 - 1]) & r9.hash_mask, r9.prev[n8 & r9.w_mask] = r9.head[r9.ins_h], r9.head[r9.ins_h] = n8, n8++, --i8; ) ;
r9.strstart = n8, r9.lookahead = x2 - 1, j3(r9);
}
return r9.strstart += r9.lookahead, r9.block_start = r9.strstart, r9.insert = r9.lookahead, r9.lookahead = 0, r9.match_length = r9.prev_length = x2 - 1, r9.match_available = 0, e10.next_in = o10, e10.input = h8, e10.avail_in = a4, r9.wrap = s7, m4;
}, r8.deflateInfo = "pako deflate (from Nodeca project)";
}, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./messages": 51, "./trees": 52 }], 47: [function(e9, t6, r8) {
"use strict";
t6.exports = function() {
this.text = 0, this.time = 0, this.xflags = 0, this.os = 0, this.extra = null, this.extra_len = 0, this.name = "", this.comment = "", this.hcrc = 0, this.done = false;
};
}, {}], 48: [function(e9, t6, r8) {
"use strict";
t6.exports = function(e10, t7) {
var r9, n7, i7, s6, a3, o9, h7, u5, l5, f4, c6, d4, p4, m4, _3, g3, b4, v4, y4, w3, k2, x2, S5, z3, C3;
r9 = e10.state, n7 = e10.next_in, z3 = e10.input, i7 = n7 + (e10.avail_in - 5), s6 = e10.next_out, C3 = e10.output, a3 = s6 - (t7 - e10.avail_out), o9 = s6 + (e10.avail_out - 257), h7 = r9.dmax, u5 = r9.wsize, l5 = r9.whave, f4 = r9.wnext, c6 = r9.window, d4 = r9.hold, p4 = r9.bits, m4 = r9.lencode, _3 = r9.distcode, g3 = (1 << r9.lenbits) - 1, b4 = (1 << r9.distbits) - 1;
e: do {
p4 < 15 && (d4 += z3[n7++] << p4, p4 += 8, d4 += z3[n7++] << p4, p4 += 8), v4 = m4[d4 & g3];
t: for (; ; ) {
if (d4 >>>= y4 = v4 >>> 24, p4 -= y4, 0 === (y4 = v4 >>> 16 & 255)) C3[s6++] = 65535 & v4;
else {
if (!(16 & y4)) {
if (0 == (64 & y4)) {
v4 = m4[(65535 & v4) + (d4 & (1 << y4) - 1)];
continue t;
}
if (32 & y4) {
r9.mode = 12;
break e;
}
e10.msg = "invalid literal/length code", r9.mode = 30;
break e;
}
w3 = 65535 & v4, (y4 &= 15) && (p4 < y4 && (d4 += z3[n7++] << p4, p4 += 8), w3 += d4 & (1 << y4) - 1, d4 >>>= y4, p4 -= y4), p4 < 15 && (d4 += z3[n7++] << p4, p4 += 8, d4 += z3[n7++] << p4, p4 += 8), v4 = _3[d4 & b4];
r: for (; ; ) {
if (d4 >>>= y4 = v4 >>> 24, p4 -= y4, !(16 & (y4 = v4 >>> 16 & 255))) {
if (0 == (64 & y4)) {
v4 = _3[(65535 & v4) + (d4 & (1 << y4) - 1)];
continue r;
}
e10.msg = "invalid distance code", r9.mode = 30;
break e;
}
if (k2 = 65535 & v4, p4 < (y4 &= 15) && (d4 += z3[n7++] << p4, (p4 += 8) < y4 && (d4 += z3[n7++] << p4, p4 += 8)), h7 < (k2 += d4 & (1 << y4) - 1)) {
e10.msg = "invalid distance too far back", r9.mode = 30;
break e;
}
if (d4 >>>= y4, p4 -= y4, (y4 = s6 - a3) < k2) {
if (l5 < (y4 = k2 - y4) && r9.sane) {
e10.msg = "invalid distance too far back", r9.mode = 30;
break e;
}
if (S5 = c6, (x2 = 0) === f4) {
if (x2 += u5 - y4, y4 < w3) {
for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ;
x2 = s6 - k2, S5 = C3;
}
} else if (f4 < y4) {
if (x2 += u5 + f4 - y4, (y4 -= f4) < w3) {
for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ;
if (x2 = 0, f4 < w3) {
for (w3 -= y4 = f4; C3[s6++] = c6[x2++], --y4; ) ;
x2 = s6 - k2, S5 = C3;
}
}
} else if (x2 += f4 - y4, y4 < w3) {
for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ;
x2 = s6 - k2, S5 = C3;
}
for (; 2 < w3; ) C3[s6++] = S5[x2++], C3[s6++] = S5[x2++], C3[s6++] = S5[x2++], w3 -= 3;
w3 && (C3[s6++] = S5[x2++], 1 < w3 && (C3[s6++] = S5[x2++]));
} else {
for (x2 = s6 - k2; C3[s6++] = C3[x2++], C3[s6++] = C3[x2++], C3[s6++] = C3[x2++], 2 < (w3 -= 3); ) ;
w3 && (C3[s6++] = C3[x2++], 1 < w3 && (C3[s6++] = C3[x2++]));
}
break;
}
}
break;
}
} while (n7 < i7 && s6 < o9);
n7 -= w3 = p4 >> 3, d4 &= (1 << (p4 -= w3 << 3)) - 1, e10.next_in = n7, e10.next_out = s6, e10.avail_in = n7 < i7 ? i7 - n7 + 5 : 5 - (n7 - i7), e10.avail_out = s6 < o9 ? o9 - s6 + 257 : 257 - (s6 - o9), r9.hold = d4, r9.bits = p4;
};
}, {}], 49: [function(e9, t6, r8) {
"use strict";
var I3 = e9("../utils/common"), O2 = e9("./adler32"), B3 = e9("./crc32"), R3 = e9("./inffast"), T3 = e9("./inftrees"), D4 = 1, F2 = 2, N3 = 0, U2 = -2, P3 = 1, n7 = 852, i7 = 592;
function L3(e10) {
return (e10 >>> 24 & 255) + (e10 >>> 8 & 65280) + ((65280 & e10) << 8) + ((255 & e10) << 24);
}
function s6() {
this.mode = 0, this.last = false, this.wrap = 0, this.havedict = false, this.flags = 0, this.dmax = 0, this.check = 0, this.total = 0, this.head = null, this.wbits = 0, this.wsize = 0, this.whave = 0, this.wnext = 0, this.window = null, this.hold = 0, this.bits = 0, this.length = 0, this.offset = 0, this.extra = 0, this.lencode = null, this.distcode = null, this.lenbits = 0, this.distbits = 0, this.ncode = 0, this.nlen = 0, this.ndist = 0, this.have = 0, this.next = null, this.lens = new I3.Buf16(320), this.work = new I3.Buf16(288), this.lendyn = null, this.distdyn = null, this.sane = 0, this.back = 0, this.was = 0;
}
function a3(e10) {
var t7;
return e10 && e10.state ? (t7 = e10.state, e10.total_in = e10.total_out = t7.total = 0, e10.msg = "", t7.wrap && (e10.adler = 1 & t7.wrap), t7.mode = P3, t7.last = 0, t7.havedict = 0, t7.dmax = 32768, t7.head = null, t7.hold = 0, t7.bits = 0, t7.lencode = t7.lendyn = new I3.Buf32(n7), t7.distcode = t7.distdyn = new I3.Buf32(i7), t7.sane = 1, t7.back = -1, N3) : U2;
}
function o9(e10) {
var t7;
return e10 && e10.state ? ((t7 = e10.state).wsize = 0, t7.whave = 0, t7.wnext = 0, a3(e10)) : U2;
}
function h7(e10, t7) {
var r9, n8;
return e10 && e10.state ? (n8 = e10.state, t7 < 0 ? (r9 = 0, t7 = -t7) : (r9 = 1 + (t7 >> 4), t7 < 48 && (t7 &= 15)), t7 && (t7 < 8 || 15 < t7) ? U2 : (null !== n8.window && n8.wbits !== t7 && (n8.window = null), n8.wrap = r9, n8.wbits = t7, o9(e10))) : U2;
}
function u5(e10, t7) {
var r9, n8;
return e10 ? (n8 = new s6(), (e10.state = n8).window = null, (r9 = h7(e10, t7)) !== N3 && (e10.state = null), r9) : U2;
}
var l5, f4, c6 = true;
function j3(e10) {
if (c6) {
var t7;
for (l5 = new I3.Buf32(512), f4 = new I3.Buf32(32), t7 = 0; t7 < 144; ) e10.lens[t7++] = 8;
for (; t7 < 256; ) e10.lens[t7++] = 9;
for (; t7 < 280; ) e10.lens[t7++] = 7;
for (; t7 < 288; ) e10.lens[t7++] = 8;
for (T3(D4, e10.lens, 0, 288, l5, 0, e10.work, { bits: 9 }), t7 = 0; t7 < 32; ) e10.lens[t7++] = 5;
T3(F2, e10.lens, 0, 32, f4, 0, e10.work, { bits: 5 }), c6 = false;
}
e10.lencode = l5, e10.lenbits = 9, e10.distcode = f4, e10.distbits = 5;
}
function Z2(e10, t7, r9, n8) {
var i8, s7 = e10.state;
return null === s7.window && (s7.wsize = 1 << s7.wbits, s7.wnext = 0, s7.whave = 0, s7.window = new I3.Buf8(s7.wsize)), n8 >= s7.wsize ? (I3.arraySet(s7.window, t7, r9 - s7.wsize, s7.wsize, 0), s7.wnext = 0, s7.whave = s7.wsize) : (n8 < (i8 = s7.wsize - s7.wnext) && (i8 = n8), I3.arraySet(s7.window, t7, r9 - n8, i8, s7.wnext), (n8 -= i8) ? (I3.arraySet(s7.window, t7, r9 - n8, n8, 0), s7.wnext = n8, s7.whave = s7.wsize) : (s7.wnext += i8, s7.wnext === s7.wsize && (s7.wnext = 0), s7.whave < s7.wsize && (s7.whave += i8))), 0;
}
r8.inflateReset = o9, r8.inflateReset2 = h7, r8.inflateResetKeep = a3, r8.inflateInit = function(e10) {
return u5(e10, 15);
}, r8.inflateInit2 = u5, r8.inflate = function(e10, t7) {
var r9, n8, i8, s7, a4, o10, h8, u6, l6, f5, c7, d4, p4, m4, _3, g3, b4, v4, y4, w3, k2, x2, S5, z3, C3 = 0, E3 = new I3.Buf8(4), A2 = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!e10 || !e10.state || !e10.output || !e10.input && 0 !== e10.avail_in) return U2;
12 === (r9 = e10.state).mode && (r9.mode = 13), a4 = e10.next_out, i8 = e10.output, h8 = e10.avail_out, s7 = e10.next_in, n8 = e10.input, o10 = e10.avail_in, u6 = r9.hold, l6 = r9.bits, f5 = o10, c7 = h8, x2 = N3;
e: for (; ; ) switch (r9.mode) {
case P3:
if (0 === r9.wrap) {
r9.mode = 13;
break;
}
for (; l6 < 16; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
if (2 & r9.wrap && 35615 === u6) {
E3[r9.check = 0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0), l6 = u6 = 0, r9.mode = 2;
break;
}
if (r9.flags = 0, r9.head && (r9.head.done = false), !(1 & r9.wrap) || (((255 & u6) << 8) + (u6 >> 8)) % 31) {
e10.msg = "incorrect header check", r9.mode = 30;
break;
}
if (8 != (15 & u6)) {
e10.msg = "unknown compression method", r9.mode = 30;
break;
}
if (l6 -= 4, k2 = 8 + (15 & (u6 >>>= 4)), 0 === r9.wbits) r9.wbits = k2;
else if (k2 > r9.wbits) {
e10.msg = "invalid window size", r9.mode = 30;
break;
}
r9.dmax = 1 << k2, e10.adler = r9.check = 1, r9.mode = 512 & u6 ? 10 : 12, l6 = u6 = 0;
break;
case 2:
for (; l6 < 16; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
if (r9.flags = u6, 8 != (255 & r9.flags)) {
e10.msg = "unknown compression method", r9.mode = 30;
break;
}
if (57344 & r9.flags) {
e10.msg = "unknown header flags set", r9.mode = 30;
break;
}
r9.head && (r9.head.text = u6 >> 8 & 1), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0, r9.mode = 3;
case 3:
for (; l6 < 32; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
r9.head && (r9.head.time = u6), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, E3[2] = u6 >>> 16 & 255, E3[3] = u6 >>> 24 & 255, r9.check = B3(r9.check, E3, 4, 0)), l6 = u6 = 0, r9.mode = 4;
case 4:
for (; l6 < 16; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
r9.head && (r9.head.xflags = 255 & u6, r9.head.os = u6 >> 8), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0, r9.mode = 5;
case 5:
if (1024 & r9.flags) {
for (; l6 < 16; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
r9.length = u6, r9.head && (r9.head.extra_len = u6), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0;
} else r9.head && (r9.head.extra = null);
r9.mode = 6;
case 6:
if (1024 & r9.flags && (o10 < (d4 = r9.length) && (d4 = o10), d4 && (r9.head && (k2 = r9.head.extra_len - r9.length, r9.head.extra || (r9.head.extra = new Array(r9.head.extra_len)), I3.arraySet(r9.head.extra, n8, s7, d4, k2)), 512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, r9.length -= d4), r9.length)) break e;
r9.length = 0, r9.mode = 7;
case 7:
if (2048 & r9.flags) {
if (0 === o10) break e;
for (d4 = 0; k2 = n8[s7 + d4++], r9.head && k2 && r9.length < 65536 && (r9.head.name += String.fromCharCode(k2)), k2 && d4 < o10; ) ;
if (512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, k2) break e;
} else r9.head && (r9.head.name = null);
r9.length = 0, r9.mode = 8;
case 8:
if (4096 & r9.flags) {
if (0 === o10) break e;
for (d4 = 0; k2 = n8[s7 + d4++], r9.head && k2 && r9.length < 65536 && (r9.head.comment += String.fromCharCode(k2)), k2 && d4 < o10; ) ;
if (512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, k2) break e;
} else r9.head && (r9.head.comment = null);
r9.mode = 9;
case 9:
if (512 & r9.flags) {
for (; l6 < 16; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
if (u6 !== (65535 & r9.check)) {
e10.msg = "header crc mismatch", r9.mode = 30;
break;
}
l6 = u6 = 0;
}
r9.head && (r9.head.hcrc = r9.flags >> 9 & 1, r9.head.done = true), e10.adler = r9.check = 0, r9.mode = 12;
break;
case 10:
for (; l6 < 32; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
e10.adler = r9.check = L3(u6), l6 = u6 = 0, r9.mode = 11;
case 11:
if (0 === r9.havedict) return e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, 2;
e10.adler = r9.check = 1, r9.mode = 12;
case 12:
if (5 === t7 || 6 === t7) break e;
case 13:
if (r9.last) {
u6 >>>= 7 & l6, l6 -= 7 & l6, r9.mode = 27;
break;
}
for (; l6 < 3; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
switch (r9.last = 1 & u6, l6 -= 1, 3 & (u6 >>>= 1)) {
case 0:
r9.mode = 14;
break;
case 1:
if (j3(r9), r9.mode = 20, 6 !== t7) break;
u6 >>>= 2, l6 -= 2;
break e;
case 2:
r9.mode = 17;
break;
case 3:
e10.msg = "invalid block type", r9.mode = 30;
}
u6 >>>= 2, l6 -= 2;
break;
case 14:
for (u6 >>>= 7 & l6, l6 -= 7 & l6; l6 < 32; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
if ((65535 & u6) != (u6 >>> 16 ^ 65535)) {
e10.msg = "invalid stored block lengths", r9.mode = 30;
break;
}
if (r9.length = 65535 & u6, l6 = u6 = 0, r9.mode = 15, 6 === t7) break e;
case 15:
r9.mode = 16;
case 16:
if (d4 = r9.length) {
if (o10 < d4 && (d4 = o10), h8 < d4 && (d4 = h8), 0 === d4) break e;
I3.arraySet(i8, n8, s7, d4, a4), o10 -= d4, s7 += d4, h8 -= d4, a4 += d4, r9.length -= d4;
break;
}
r9.mode = 12;
break;
case 17:
for (; l6 < 14; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
if (r9.nlen = 257 + (31 & u6), u6 >>>= 5, l6 -= 5, r9.ndist = 1 + (31 & u6), u6 >>>= 5, l6 -= 5, r9.ncode = 4 + (15 & u6), u6 >>>= 4, l6 -= 4, 286 < r9.nlen || 30 < r9.ndist) {
e10.msg = "too many length or distance symbols", r9.mode = 30;
break;
}
r9.have = 0, r9.mode = 18;
case 18:
for (; r9.have < r9.ncode; ) {
for (; l6 < 3; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
r9.lens[A2[r9.have++]] = 7 & u6, u6 >>>= 3, l6 -= 3;
}
for (; r9.have < 19; ) r9.lens[A2[r9.have++]] = 0;
if (r9.lencode = r9.lendyn, r9.lenbits = 7, S5 = { bits: r9.lenbits }, x2 = T3(0, r9.lens, 0, 19, r9.lencode, 0, r9.work, S5), r9.lenbits = S5.bits, x2) {
e10.msg = "invalid code lengths set", r9.mode = 30;
break;
}
r9.have = 0, r9.mode = 19;
case 19:
for (; r9.have < r9.nlen + r9.ndist; ) {
for (; g3 = (C3 = r9.lencode[u6 & (1 << r9.lenbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
if (b4 < 16) u6 >>>= _3, l6 -= _3, r9.lens[r9.have++] = b4;
else {
if (16 === b4) {
for (z3 = _3 + 2; l6 < z3; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
if (u6 >>>= _3, l6 -= _3, 0 === r9.have) {
e10.msg = "invalid bit length repeat", r9.mode = 30;
break;
}
k2 = r9.lens[r9.have - 1], d4 = 3 + (3 & u6), u6 >>>= 2, l6 -= 2;
} else if (17 === b4) {
for (z3 = _3 + 3; l6 < z3; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
l6 -= _3, k2 = 0, d4 = 3 + (7 & (u6 >>>= _3)), u6 >>>= 3, l6 -= 3;
} else {
for (z3 = _3 + 7; l6 < z3; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
l6 -= _3, k2 = 0, d4 = 11 + (127 & (u6 >>>= _3)), u6 >>>= 7, l6 -= 7;
}
if (r9.have + d4 > r9.nlen + r9.ndist) {
e10.msg = "invalid bit length repeat", r9.mode = 30;
break;
}
for (; d4--; ) r9.lens[r9.have++] = k2;
}
}
if (30 === r9.mode) break;
if (0 === r9.lens[256]) {
e10.msg = "invalid code -- missing end-of-block", r9.mode = 30;
break;
}
if (r9.lenbits = 9, S5 = { bits: r9.lenbits }, x2 = T3(D4, r9.lens, 0, r9.nlen, r9.lencode, 0, r9.work, S5), r9.lenbits = S5.bits, x2) {
e10.msg = "invalid literal/lengths set", r9.mode = 30;
break;
}
if (r9.distbits = 6, r9.distcode = r9.distdyn, S5 = { bits: r9.distbits }, x2 = T3(F2, r9.lens, r9.nlen, r9.ndist, r9.distcode, 0, r9.work, S5), r9.distbits = S5.bits, x2) {
e10.msg = "invalid distances set", r9.mode = 30;
break;
}
if (r9.mode = 20, 6 === t7) break e;
case 20:
r9.mode = 21;
case 21:
if (6 <= o10 && 258 <= h8) {
e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, R3(e10, c7), a4 = e10.next_out, i8 = e10.output, h8 = e10.avail_out, s7 = e10.next_in, n8 = e10.input, o10 = e10.avail_in, u6 = r9.hold, l6 = r9.bits, 12 === r9.mode && (r9.back = -1);
break;
}
for (r9.back = 0; g3 = (C3 = r9.lencode[u6 & (1 << r9.lenbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
if (g3 && 0 == (240 & g3)) {
for (v4 = _3, y4 = g3, w3 = b4; g3 = (C3 = r9.lencode[w3 + ((u6 & (1 << v4 + y4) - 1) >> v4)]) >>> 16 & 255, b4 = 65535 & C3, !(v4 + (_3 = C3 >>> 24) <= l6); ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
u6 >>>= v4, l6 -= v4, r9.back += v4;
}
if (u6 >>>= _3, l6 -= _3, r9.back += _3, r9.length = b4, 0 === g3) {
r9.mode = 26;
break;
}
if (32 & g3) {
r9.back = -1, r9.mode = 12;
break;
}
if (64 & g3) {
e10.msg = "invalid literal/length code", r9.mode = 30;
break;
}
r9.extra = 15 & g3, r9.mode = 22;
case 22:
if (r9.extra) {
for (z3 = r9.extra; l6 < z3; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
r9.length += u6 & (1 << r9.extra) - 1, u6 >>>= r9.extra, l6 -= r9.extra, r9.back += r9.extra;
}
r9.was = r9.length, r9.mode = 23;
case 23:
for (; g3 = (C3 = r9.distcode[u6 & (1 << r9.distbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
if (0 == (240 & g3)) {
for (v4 = _3, y4 = g3, w3 = b4; g3 = (C3 = r9.distcode[w3 + ((u6 & (1 << v4 + y4) - 1) >> v4)]) >>> 16 & 255, b4 = 65535 & C3, !(v4 + (_3 = C3 >>> 24) <= l6); ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
u6 >>>= v4, l6 -= v4, r9.back += v4;
}
if (u6 >>>= _3, l6 -= _3, r9.back += _3, 64 & g3) {
e10.msg = "invalid distance code", r9.mode = 30;
break;
}
r9.offset = b4, r9.extra = 15 & g3, r9.mode = 24;
case 24:
if (r9.extra) {
for (z3 = r9.extra; l6 < z3; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
r9.offset += u6 & (1 << r9.extra) - 1, u6 >>>= r9.extra, l6 -= r9.extra, r9.back += r9.extra;
}
if (r9.offset > r9.dmax) {
e10.msg = "invalid distance too far back", r9.mode = 30;
break;
}
r9.mode = 25;
case 25:
if (0 === h8) break e;
if (d4 = c7 - h8, r9.offset > d4) {
if ((d4 = r9.offset - d4) > r9.whave && r9.sane) {
e10.msg = "invalid distance too far back", r9.mode = 30;
break;
}
p4 = d4 > r9.wnext ? (d4 -= r9.wnext, r9.wsize - d4) : r9.wnext - d4, d4 > r9.length && (d4 = r9.length), m4 = r9.window;
} else m4 = i8, p4 = a4 - r9.offset, d4 = r9.length;
for (h8 < d4 && (d4 = h8), h8 -= d4, r9.length -= d4; i8[a4++] = m4[p4++], --d4; ) ;
0 === r9.length && (r9.mode = 21);
break;
case 26:
if (0 === h8) break e;
i8[a4++] = r9.length, h8--, r9.mode = 21;
break;
case 27:
if (r9.wrap) {
for (; l6 < 32; ) {
if (0 === o10) break e;
o10--, u6 |= n8[s7++] << l6, l6 += 8;
}
if (c7 -= h8, e10.total_out += c7, r9.total += c7, c7 && (e10.adler = r9.check = r9.flags ? B3(r9.check, i8, c7, a4 - c7) : O2(r9.check, i8, c7, a4 - c7)), c7 = h8, (r9.flags ? u6 : L3(u6)) !== r9.check) {
e10.msg = "incorrect data check", r9.mode = 30;
break;
}
l6 = u6 = 0;
}
r9.mode = 28;
case 28:
if (r9.wrap && r9.flags) {
for (; l6 < 32; ) {
if (0 === o10) break e;
o10--, u6 += n8[s7++] << l6, l6 += 8;
}
if (u6 !== (4294967295 & r9.total)) {
e10.msg = "incorrect length check", r9.mode = 30;
break;
}
l6 = u6 = 0;
}
r9.mode = 29;
case 29:
x2 = 1;
break e;
case 30:
x2 = -3;
break e;
case 31:
return -4;
case 32:
default:
return U2;
}
return e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, (r9.wsize || c7 !== e10.avail_out && r9.mode < 30 && (r9.mode < 27 || 4 !== t7)) && Z2(e10, e10.output, e10.next_out, c7 - e10.avail_out) ? (r9.mode = 31, -4) : (f5 -= e10.avail_in, c7 -= e10.avail_out, e10.total_in += f5, e10.total_out += c7, r9.total += c7, r9.wrap && c7 && (e10.adler = r9.check = r9.flags ? B3(r9.check, i8, c7, e10.next_out - c7) : O2(r9.check, i8, c7, e10.next_out - c7)), e10.data_type = r9.bits + (r9.last ? 64 : 0) + (12 === r9.mode ? 128 : 0) + (20 === r9.mode || 15 === r9.mode ? 256 : 0), (0 == f5 && 0 === c7 || 4 === t7) && x2 === N3 && (x2 = -5), x2);
}, r8.inflateEnd = function(e10) {
if (!e10 || !e10.state) return U2;
var t7 = e10.state;
return t7.window && (t7.window = null), e10.state = null, N3;
}, r8.inflateGetHeader = function(e10, t7) {
var r9;
return e10 && e10.state ? 0 == (2 & (r9 = e10.state).wrap) ? U2 : ((r9.head = t7).done = false, N3) : U2;
}, r8.inflateSetDictionary = function(e10, t7) {
var r9, n8 = t7.length;
return e10 && e10.state ? 0 !== (r9 = e10.state).wrap && 11 !== r9.mode ? U2 : 11 === r9.mode && O2(1, t7, n8, 0) !== r9.check ? -3 : Z2(e10, t7, n8, n8) ? (r9.mode = 31, -4) : (r9.havedict = 1, N3) : U2;
}, r8.inflateInfo = "pako inflate (from Nodeca project)";
}, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./inffast": 48, "./inftrees": 50 }], 50: [function(e9, t6, r8) {
"use strict";
var D4 = e9("../utils/common"), F2 = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0], N3 = [16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78], U2 = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0], P3 = [16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64];
t6.exports = function(e10, t7, r9, n7, i7, s6, a3, o9) {
var h7, u5, l5, f4, c6, d4, p4, m4, _3, g3 = o9.bits, b4 = 0, v4 = 0, y4 = 0, w3 = 0, k2 = 0, x2 = 0, S5 = 0, z3 = 0, C3 = 0, E3 = 0, A2 = null, I3 = 0, O2 = new D4.Buf16(16), B3 = new D4.Buf16(16), R3 = null, T3 = 0;
for (b4 = 0; b4 <= 15; b4++) O2[b4] = 0;
for (v4 = 0; v4 < n7; v4++) O2[t7[r9 + v4]]++;
for (k2 = g3, w3 = 15; 1 <= w3 && 0 === O2[w3]; w3--) ;
if (w3 < k2 && (k2 = w3), 0 === w3) return i7[s6++] = 20971520, i7[s6++] = 20971520, o9.bits = 1, 0;
for (y4 = 1; y4 < w3 && 0 === O2[y4]; y4++) ;
for (k2 < y4 && (k2 = y4), b4 = z3 = 1; b4 <= 15; b4++) if (z3 <<= 1, (z3 -= O2[b4]) < 0) return -1;
if (0 < z3 && (0 === e10 || 1 !== w3)) return -1;
for (B3[1] = 0, b4 = 1; b4 < 15; b4++) B3[b4 + 1] = B3[b4] + O2[b4];
for (v4 = 0; v4 < n7; v4++) 0 !== t7[r9 + v4] && (a3[B3[t7[r9 + v4]]++] = v4);
if (d4 = 0 === e10 ? (A2 = R3 = a3, 19) : 1 === e10 ? (A2 = F2, I3 -= 257, R3 = N3, T3 -= 257, 256) : (A2 = U2, R3 = P3, -1), b4 = y4, c6 = s6, S5 = v4 = E3 = 0, l5 = -1, f4 = (C3 = 1 << (x2 = k2)) - 1, 1 === e10 && 852 < C3 || 2 === e10 && 592 < C3) return 1;
for (; ; ) {
for (p4 = b4 - S5, _3 = a3[v4] < d4 ? (m4 = 0, a3[v4]) : a3[v4] > d4 ? (m4 = R3[T3 + a3[v4]], A2[I3 + a3[v4]]) : (m4 = 96, 0), h7 = 1 << b4 - S5, y4 = u5 = 1 << x2; i7[c6 + (E3 >> S5) + (u5 -= h7)] = p4 << 24 | m4 << 16 | _3 | 0, 0 !== u5; ) ;
for (h7 = 1 << b4 - 1; E3 & h7; ) h7 >>= 1;
if (0 !== h7 ? (E3 &= h7 - 1, E3 += h7) : E3 = 0, v4++, 0 == --O2[b4]) {
if (b4 === w3) break;
b4 = t7[r9 + a3[v4]];
}
if (k2 < b4 && (E3 & f4) !== l5) {
for (0 === S5 && (S5 = k2), c6 += y4, z3 = 1 << (x2 = b4 - S5); x2 + S5 < w3 && !((z3 -= O2[x2 + S5]) <= 0); ) x2++, z3 <<= 1;
if (C3 += 1 << x2, 1 === e10 && 852 < C3 || 2 === e10 && 592 < C3) return 1;
i7[l5 = E3 & f4] = k2 << 24 | x2 << 16 | c6 - s6 | 0;
}
}
return 0 !== E3 && (i7[c6 + E3] = b4 - S5 << 24 | 64 << 16 | 0), o9.bits = k2, 0;
};
}, { "../utils/common": 41 }], 51: [function(e9, t6, r8) {
"use strict";
t6.exports = { 2: "need dictionary", 1: "stream end", 0: "", "-1": "file error", "-2": "stream error", "-3": "data error", "-4": "insufficient memory", "-5": "buffer error", "-6": "incompatible version" };
}, {}], 52: [function(e9, t6, r8) {
"use strict";
var i7 = e9("../utils/common"), o9 = 0, h7 = 1;
function n7(e10) {
for (var t7 = e10.length; 0 <= --t7; ) e10[t7] = 0;
}
var s6 = 0, a3 = 29, u5 = 256, l5 = u5 + 1 + a3, f4 = 30, c6 = 19, _3 = 2 * l5 + 1, g3 = 15, d4 = 16, p4 = 7, m4 = 256, b4 = 16, v4 = 17, y4 = 18, w3 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0], k2 = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], x2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7], S5 = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], z3 = new Array(2 * (l5 + 2));
n7(z3);
var C3 = new Array(2 * f4);
n7(C3);
var E3 = new Array(512);
n7(E3);
var A2 = new Array(256);
n7(A2);
var I3 = new Array(a3);
n7(I3);
var O2, B3, R3, T3 = new Array(f4);
function D4(e10, t7, r9, n8, i8) {
this.static_tree = e10, this.extra_bits = t7, this.extra_base = r9, this.elems = n8, this.max_length = i8, this.has_stree = e10 && e10.length;
}
function F2(e10, t7) {
this.dyn_tree = e10, this.max_code = 0, this.stat_desc = t7;
}
function N3(e10) {
return e10 < 256 ? E3[e10] : E3[256 + (e10 >>> 7)];
}
function U2(e10, t7) {
e10.pending_buf[e10.pending++] = 255 & t7, e10.pending_buf[e10.pending++] = t7 >>> 8 & 255;
}
function P3(e10, t7, r9) {
e10.bi_valid > d4 - r9 ? (e10.bi_buf |= t7 << e10.bi_valid & 65535, U2(e10, e10.bi_buf), e10.bi_buf = t7 >> d4 - e10.bi_valid, e10.bi_valid += r9 - d4) : (e10.bi_buf |= t7 << e10.bi_valid & 65535, e10.bi_valid += r9);
}
function L3(e10, t7, r9) {
P3(e10, r9[2 * t7], r9[2 * t7 + 1]);
}
function j3(e10, t7) {
for (var r9 = 0; r9 |= 1 & e10, e10 >>>= 1, r9 <<= 1, 0 < --t7; ) ;
return r9 >>> 1;
}
function Z2(e10, t7, r9) {
var n8, i8, s7 = new Array(g3 + 1), a4 = 0;
for (n8 = 1; n8 <= g3; n8++) s7[n8] = a4 = a4 + r9[n8 - 1] << 1;
for (i8 = 0; i8 <= t7; i8++) {
var o10 = e10[2 * i8 + 1];
0 !== o10 && (e10[2 * i8] = j3(s7[o10]++, o10));
}
}
function W2(e10) {
var t7;
for (t7 = 0; t7 < l5; t7++) e10.dyn_ltree[2 * t7] = 0;
for (t7 = 0; t7 < f4; t7++) e10.dyn_dtree[2 * t7] = 0;
for (t7 = 0; t7 < c6; t7++) e10.bl_tree[2 * t7] = 0;
e10.dyn_ltree[2 * m4] = 1, e10.opt_len = e10.static_len = 0, e10.last_lit = e10.matches = 0;
}
function M4(e10) {
8 < e10.bi_valid ? U2(e10, e10.bi_buf) : 0 < e10.bi_valid && (e10.pending_buf[e10.pending++] = e10.bi_buf), e10.bi_buf = 0, e10.bi_valid = 0;
}
function H2(e10, t7, r9, n8) {
var i8 = 2 * t7, s7 = 2 * r9;
return e10[i8] < e10[s7] || e10[i8] === e10[s7] && n8[t7] <= n8[r9];
}
function G2(e10, t7, r9) {
for (var n8 = e10.heap[r9], i8 = r9 << 1; i8 <= e10.heap_len && (i8 < e10.heap_len && H2(t7, e10.heap[i8 + 1], e10.heap[i8], e10.depth) && i8++, !H2(t7, n8, e10.heap[i8], e10.depth)); ) e10.heap[r9] = e10.heap[i8], r9 = i8, i8 <<= 1;
e10.heap[r9] = n8;
}
function K2(e10, t7, r9) {
var n8, i8, s7, a4, o10 = 0;
if (0 !== e10.last_lit) for (; n8 = e10.pending_buf[e10.d_buf + 2 * o10] << 8 | e10.pending_buf[e10.d_buf + 2 * o10 + 1], i8 = e10.pending_buf[e10.l_buf + o10], o10++, 0 === n8 ? L3(e10, i8, t7) : (L3(e10, (s7 = A2[i8]) + u5 + 1, t7), 0 !== (a4 = w3[s7]) && P3(e10, i8 -= I3[s7], a4), L3(e10, s7 = N3(--n8), r9), 0 !== (a4 = k2[s7]) && P3(e10, n8 -= T3[s7], a4)), o10 < e10.last_lit; ) ;
L3(e10, m4, t7);
}
function Y(e10, t7) {
var r9, n8, i8, s7 = t7.dyn_tree, a4 = t7.stat_desc.static_tree, o10 = t7.stat_desc.has_stree, h8 = t7.stat_desc.elems, u6 = -1;
for (e10.heap_len = 0, e10.heap_max = _3, r9 = 0; r9 < h8; r9++) 0 !== s7[2 * r9] ? (e10.heap[++e10.heap_len] = u6 = r9, e10.depth[r9] = 0) : s7[2 * r9 + 1] = 0;
for (; e10.heap_len < 2; ) s7[2 * (i8 = e10.heap[++e10.heap_len] = u6 < 2 ? ++u6 : 0)] = 1, e10.depth[i8] = 0, e10.opt_len--, o10 && (e10.static_len -= a4[2 * i8 + 1]);
for (t7.max_code = u6, r9 = e10.heap_len >> 1; 1 <= r9; r9--) G2(e10, s7, r9);
for (i8 = h8; r9 = e10.heap[1], e10.heap[1] = e10.heap[e10.heap_len--], G2(e10, s7, 1), n8 = e10.heap[1], e10.heap[--e10.heap_max] = r9, e10.heap[--e10.heap_max] = n8, s7[2 * i8] = s7[2 * r9] + s7[2 * n8], e10.depth[i8] = (e10.depth[r9] >= e10.depth[n8] ? e10.depth[r9] : e10.depth[n8]) + 1, s7[2 * r9 + 1] = s7[2 * n8 + 1] = i8, e10.heap[1] = i8++, G2(e10, s7, 1), 2 <= e10.heap_len; ) ;
e10.heap[--e10.heap_max] = e10.heap[1], (function(e11, t8) {
var r10, n9, i9, s8, a5, o11, h9 = t8.dyn_tree, u7 = t8.max_code, l6 = t8.stat_desc.static_tree, f5 = t8.stat_desc.has_stree, c7 = t8.stat_desc.extra_bits, d5 = t8.stat_desc.extra_base, p5 = t8.stat_desc.max_length, m5 = 0;
for (s8 = 0; s8 <= g3; s8++) e11.bl_count[s8] = 0;
for (h9[2 * e11.heap[e11.heap_max] + 1] = 0, r10 = e11.heap_max + 1; r10 < _3; r10++) p5 < (s8 = h9[2 * h9[2 * (n9 = e11.heap[r10]) + 1] + 1] + 1) && (s8 = p5, m5++), h9[2 * n9 + 1] = s8, u7 < n9 || (e11.bl_count[s8]++, a5 = 0, d5 <= n9 && (a5 = c7[n9 - d5]), o11 = h9[2 * n9], e11.opt_len += o11 * (s8 + a5), f5 && (e11.static_len += o11 * (l6[2 * n9 + 1] + a5)));
if (0 !== m5) {
do {
for (s8 = p5 - 1; 0 === e11.bl_count[s8]; ) s8--;
e11.bl_count[s8]--, e11.bl_count[s8 + 1] += 2, e11.bl_count[p5]--, m5 -= 2;
} while (0 < m5);
for (s8 = p5; 0 !== s8; s8--) for (n9 = e11.bl_count[s8]; 0 !== n9; ) u7 < (i9 = e11.heap[--r10]) || (h9[2 * i9 + 1] !== s8 && (e11.opt_len += (s8 - h9[2 * i9 + 1]) * h9[2 * i9], h9[2 * i9 + 1] = s8), n9--);
}
})(e10, t7), Z2(s7, u6, e10.bl_count);
}
function X4(e10, t7, r9) {
var n8, i8, s7 = -1, a4 = t7[1], o10 = 0, h8 = 7, u6 = 4;
for (0 === a4 && (h8 = 138, u6 = 3), t7[2 * (r9 + 1) + 1] = 65535, n8 = 0; n8 <= r9; n8++) i8 = a4, a4 = t7[2 * (n8 + 1) + 1], ++o10 < h8 && i8 === a4 || (o10 < u6 ? e10.bl_tree[2 * i8] += o10 : 0 !== i8 ? (i8 !== s7 && e10.bl_tree[2 * i8]++, e10.bl_tree[2 * b4]++) : o10 <= 10 ? e10.bl_tree[2 * v4]++ : e10.bl_tree[2 * y4]++, s7 = i8, u6 = (o10 = 0) === a4 ? (h8 = 138, 3) : i8 === a4 ? (h8 = 6, 3) : (h8 = 7, 4));
}
function V3(e10, t7, r9) {
var n8, i8, s7 = -1, a4 = t7[1], o10 = 0, h8 = 7, u6 = 4;
for (0 === a4 && (h8 = 138, u6 = 3), n8 = 0; n8 <= r9; n8++) if (i8 = a4, a4 = t7[2 * (n8 + 1) + 1], !(++o10 < h8 && i8 === a4)) {
if (o10 < u6) for (; L3(e10, i8, e10.bl_tree), 0 != --o10; ) ;
else 0 !== i8 ? (i8 !== s7 && (L3(e10, i8, e10.bl_tree), o10--), L3(e10, b4, e10.bl_tree), P3(e10, o10 - 3, 2)) : o10 <= 10 ? (L3(e10, v4, e10.bl_tree), P3(e10, o10 - 3, 3)) : (L3(e10, y4, e10.bl_tree), P3(e10, o10 - 11, 7));
s7 = i8, u6 = (o10 = 0) === a4 ? (h8 = 138, 3) : i8 === a4 ? (h8 = 6, 3) : (h8 = 7, 4);
}
}
n7(T3);
var q2 = false;
function J2(e10, t7, r9, n8) {
P3(e10, (s6 << 1) + (n8 ? 1 : 0), 3), (function(e11, t8, r10, n9) {
M4(e11), n9 && (U2(e11, r10), U2(e11, ~r10)), i7.arraySet(e11.pending_buf, e11.window, t8, r10, e11.pending), e11.pending += r10;
})(e10, t7, r9, true);
}
r8._tr_init = function(e10) {
q2 || ((function() {
var e11, t7, r9, n8, i8, s7 = new Array(g3 + 1);
for (n8 = r9 = 0; n8 < a3 - 1; n8++) for (I3[n8] = r9, e11 = 0; e11 < 1 << w3[n8]; e11++) A2[r9++] = n8;
for (A2[r9 - 1] = n8, n8 = i8 = 0; n8 < 16; n8++) for (T3[n8] = i8, e11 = 0; e11 < 1 << k2[n8]; e11++) E3[i8++] = n8;
for (i8 >>= 7; n8 < f4; n8++) for (T3[n8] = i8 << 7, e11 = 0; e11 < 1 << k2[n8] - 7; e11++) E3[256 + i8++] = n8;
for (t7 = 0; t7 <= g3; t7++) s7[t7] = 0;
for (e11 = 0; e11 <= 143; ) z3[2 * e11 + 1] = 8, e11++, s7[8]++;
for (; e11 <= 255; ) z3[2 * e11 + 1] = 9, e11++, s7[9]++;
for (; e11 <= 279; ) z3[2 * e11 + 1] = 7, e11++, s7[7]++;
for (; e11 <= 287; ) z3[2 * e11 + 1] = 8, e11++, s7[8]++;
for (Z2(z3, l5 + 1, s7), e11 = 0; e11 < f4; e11++) C3[2 * e11 + 1] = 5, C3[2 * e11] = j3(e11, 5);
O2 = new D4(z3, w3, u5 + 1, l5, g3), B3 = new D4(C3, k2, 0, f4, g3), R3 = new D4(new Array(0), x2, 0, c6, p4);
})(), q2 = true), e10.l_desc = new F2(e10.dyn_ltree, O2), e10.d_desc = new F2(e10.dyn_dtree, B3), e10.bl_desc = new F2(e10.bl_tree, R3), e10.bi_buf = 0, e10.bi_valid = 0, W2(e10);
}, r8._tr_stored_block = J2, r8._tr_flush_block = function(e10, t7, r9, n8) {
var i8, s7, a4 = 0;
0 < e10.level ? (2 === e10.strm.data_type && (e10.strm.data_type = (function(e11) {
var t8, r10 = 4093624447;
for (t8 = 0; t8 <= 31; t8++, r10 >>>= 1) if (1 & r10 && 0 !== e11.dyn_ltree[2 * t8]) return o9;
if (0 !== e11.dyn_ltree[18] || 0 !== e11.dyn_ltree[20] || 0 !== e11.dyn_ltree[26]) return h7;
for (t8 = 32; t8 < u5; t8++) if (0 !== e11.dyn_ltree[2 * t8]) return h7;
return o9;
})(e10)), Y(e10, e10.l_desc), Y(e10, e10.d_desc), a4 = (function(e11) {
var t8;
for (X4(e11, e11.dyn_ltree, e11.l_desc.max_code), X4(e11, e11.dyn_dtree, e11.d_desc.max_code), Y(e11, e11.bl_desc), t8 = c6 - 1; 3 <= t8 && 0 === e11.bl_tree[2 * S5[t8] + 1]; t8--) ;
return e11.opt_len += 3 * (t8 + 1) + 5 + 5 + 4, t8;
})(e10), i8 = e10.opt_len + 3 + 7 >>> 3, (s7 = e10.static_len + 3 + 7 >>> 3) <= i8 && (i8 = s7)) : i8 = s7 = r9 + 5, r9 + 4 <= i8 && -1 !== t7 ? J2(e10, t7, r9, n8) : 4 === e10.strategy || s7 === i8 ? (P3(e10, 2 + (n8 ? 1 : 0), 3), K2(e10, z3, C3)) : (P3(e10, 4 + (n8 ? 1 : 0), 3), (function(e11, t8, r10, n9) {
var i9;
for (P3(e11, t8 - 257, 5), P3(e11, r10 - 1, 5), P3(e11, n9 - 4, 4), i9 = 0; i9 < n9; i9++) P3(e11, e11.bl_tree[2 * S5[i9] + 1], 3);
V3(e11, e11.dyn_ltree, t8 - 1), V3(e11, e11.dyn_dtree, r10 - 1);
})(e10, e10.l_desc.max_code + 1, e10.d_desc.max_code + 1, a4 + 1), K2(e10, e10.dyn_ltree, e10.dyn_dtree)), W2(e10), n8 && M4(e10);
}, r8._tr_tally = function(e10, t7, r9) {
return e10.pending_buf[e10.d_buf + 2 * e10.last_lit] = t7 >>> 8 & 255, e10.pending_buf[e10.d_buf + 2 * e10.last_lit + 1] = 255 & t7, e10.pending_buf[e10.l_buf + e10.last_lit] = 255 & r9, e10.last_lit++, 0 === t7 ? e10.dyn_ltree[2 * r9]++ : (e10.matches++, t7--, e10.dyn_ltree[2 * (A2[r9] + u5 + 1)]++, e10.dyn_dtree[2 * N3(t7)]++), e10.last_lit === e10.lit_bufsize - 1;
}, r8._tr_align = function(e10) {
P3(e10, 2, 3), L3(e10, m4, z3), (function(e11) {
16 === e11.bi_valid ? (U2(e11, e11.bi_buf), e11.bi_buf = 0, e11.bi_valid = 0) : 8 <= e11.bi_valid && (e11.pending_buf[e11.pending++] = 255 & e11.bi_buf, e11.bi_buf >>= 8, e11.bi_valid -= 8);
})(e10);
};
}, { "../utils/common": 41 }], 53: [function(e9, t6, r8) {
"use strict";
t6.exports = function() {
this.input = null, this.next_in = 0, this.avail_in = 0, this.total_in = 0, this.output = null, this.next_out = 0, this.avail_out = 0, this.total_out = 0, this.msg = "", this.state = null, this.data_type = 2, this.adler = 0;
};
}, {}], 54: [function(e9, t6, r8) {
(function(e10) {
!(function(r9, n7) {
"use strict";
if (!r9.setImmediate) {
var i7, s6, t7, a3, o9 = 1, h7 = {}, u5 = false, l5 = r9.document, e11 = Object.getPrototypeOf && Object.getPrototypeOf(r9);
e11 = e11 && e11.setTimeout ? e11 : r9, i7 = "[object process]" === {}.toString.call(r9.process) ? function(e12) {
process.nextTick(function() {
c6(e12);
});
} : (function() {
if (r9.postMessage && !r9.importScripts) {
var e12 = true, t8 = r9.onmessage;
return r9.onmessage = function() {
e12 = false;
}, r9.postMessage("", "*"), r9.onmessage = t8, e12;
}
})() ? (a3 = "setImmediate$" + Math.random() + "$", r9.addEventListener ? r9.addEventListener("message", d4, false) : r9.attachEvent("onmessage", d4), function(e12) {
r9.postMessage(a3 + e12, "*");
}) : r9.MessageChannel ? ((t7 = new MessageChannel()).port1.onmessage = function(e12) {
c6(e12.data);
}, function(e12) {
t7.port2.postMessage(e12);
}) : l5 && "onreadystatechange" in l5.createElement("script") ? (s6 = l5.documentElement, function(e12) {
var t8 = l5.createElement("script");
t8.onreadystatechange = function() {
c6(e12), t8.onreadystatechange = null, s6.removeChild(t8), t8 = null;
}, s6.appendChild(t8);
}) : function(e12) {
setTimeout(c6, 0, e12);
}, e11.setImmediate = function(e12) {
"function" != typeof e12 && (e12 = new Function("" + e12));
for (var t8 = new Array(arguments.length - 1), r10 = 0; r10 < t8.length; r10++) t8[r10] = arguments[r10 + 1];
var n8 = { callback: e12, args: t8 };
return h7[o9] = n8, i7(o9), o9++;
}, e11.clearImmediate = f4;
}
function f4(e12) {
delete h7[e12];
}
function c6(e12) {
if (u5) setTimeout(c6, 0, e12);
else {
var t8 = h7[e12];
if (t8) {
u5 = true;
try {
!(function(e13) {
var t9 = e13.callback, r10 = e13.args;
switch (r10.length) {
case 0:
t9();
break;
case 1:
t9(r10[0]);
break;
case 2:
t9(r10[0], r10[1]);
break;
case 3:
t9(r10[0], r10[1], r10[2]);
break;
default:
t9.apply(n7, r10);
}
})(t8);
} finally {
f4(e12), u5 = false;
}
}
}
}
function d4(e12) {
e12.source === r9 && "string" == typeof e12.data && 0 === e12.data.indexOf(a3) && c6(+e12.data.slice(a3.length));
}
})("undefined" == typeof self ? void 0 === e10 ? this : e10 : self);
}).call(this, "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {}] }, {}, [10])(10);
});
}
});
// ../pi-mono/node_modules/docx-preview/dist/docx-preview.mjs
function parseRelationships(root, xml2) {
return xml2.elements(root).map((e9) => ({
id: xml2.attr(e9, "Id"),
type: xml2.attr(e9, "Type"),
target: xml2.attr(e9, "Target"),
targetMode: xml2.attr(e9, "TargetMode")
}));
}
function escapeClassName(className) {
return className?.replace(/[ .]+/g, "-").replace(/[&]+/g, "and").toLowerCase();
}
function encloseFontFamily(fontFamily) {
return /^[^"'].*\s.*[^"']$/.test(fontFamily) ? `'${fontFamily}'` : fontFamily;
}
function splitPath(path6) {
let si = path6.lastIndexOf("/") + 1;
let folder = si == 0 ? "" : path6.substring(0, si);
let fileName = si == 0 ? path6 : path6.substring(si);
return [folder, fileName];
}
function resolvePath(path6, base) {
try {
const prefix = "http://docx/";
const url = new URL(path6, prefix + base).toString();
return url.substring(prefix.length);
} catch {
return `${base}${path6}`;
}
}
function keyBy(array, by) {
return array.reduce((a3, x2) => {
a3[by(x2)] = x2;
return a3;
}, {});
}
function blobToBase64(blob) {
return new Promise((resolve2, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve2(reader.result);
reader.onerror = () => reject();
reader.readAsDataURL(blob);
});
}
function isObject(item) {
return item && typeof item === "object" && !Array.isArray(item);
}
function isString2(item) {
return typeof item === "string" || item instanceof String;
}
function mergeDeep(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
const val2 = target[key] ?? (target[key] = {});
mergeDeep(val2, source[key]);
} else {
target[key] = source[key];
}
}
}
return mergeDeep(target, ...sources);
}
function asArray(val2) {
return Array.isArray(val2) ? val2 : [val2];
}
function clamp(val2, min, max) {
return min > val2 ? min : max < val2 ? max : val2;
}
function convertLength(val2, usage = LengthUsage.Dxa) {
if (val2 == null || /.+(p[xt]|[%])$/.test(val2)) {
return val2;
}
var num = parseInt(val2) * usage.mul;
if (usage.min && usage.max)
num = clamp(num, usage.min, usage.max);
return `${num.toFixed(2)}${usage.unit}`;
}
function convertBoolean(v4, defaultValue = false) {
switch (v4) {
case "1":
return true;
case "0":
return false;
case "on":
return true;
case "off":
return false;
case "true":
return true;
case "false":
return false;
default:
return defaultValue;
}
}
function parseCommonProperty(elem, props, xml2) {
if (elem.namespaceURI != ns$1.wordml)
return false;
switch (elem.localName) {
case "color":
props.color = xml2.attr(elem, "val");
break;
case "sz":
props.fontSize = xml2.lengthAttr(elem, "val", LengthUsage.FontSize);
break;
default:
return false;
}
return true;
}
function parseXmlString(xmlString, trimXmlDeclaration = false) {
if (trimXmlDeclaration)
xmlString = xmlString.replace(/<[?].*[?]>/, "");
xmlString = removeUTF8BOM(xmlString);
const result = new DOMParser().parseFromString(xmlString, "application/xml");
const errorText = hasXmlParserError(result);
if (errorText)
throw new Error(errorText);
return result;
}
function hasXmlParserError(doc) {
return doc.getElementsByTagName("parsererror")[0]?.textContent;
}
function removeUTF8BOM(data) {
return data.charCodeAt(0) === 65279 ? data.substring(1) : data;
}
function serializeXmlString(elem) {
return new XMLSerializer().serializeToString(elem);
}
function parseFonts(root, xml2) {
return xml2.elements(root).map((el) => parseFont(el, xml2));
}
function parseFont(elem, xml2) {
let result = {
name: xml2.attr(elem, "name"),
embedFontRefs: []
};
for (let el of xml2.elements(elem)) {
switch (el.localName) {
case "family":
result.family = xml2.attr(el, "val");
break;
case "altName":
result.altName = xml2.attr(el, "val");
break;
case "embedRegular":
case "embedBold":
case "embedItalic":
case "embedBoldItalic":
result.embedFontRefs.push(parseEmbedFontRef(el, xml2));
break;
}
}
return result;
}
function parseEmbedFontRef(elem, xml2) {
return {
id: xml2.attr(elem, "id"),
key: xml2.attr(elem, "fontKey"),
type: embedFontTypeMap[elem.localName]
};
}
function normalizePath(path6) {
return path6.startsWith("/") ? path6.substr(1) : path6;
}
function parseBorder(elem, xml2) {
return {
type: xml2.attr(elem, "val"),
color: xml2.attr(elem, "color"),
size: xml2.lengthAttr(elem, "sz", LengthUsage.Border),
offset: xml2.lengthAttr(elem, "space", LengthUsage.Point),
frame: xml2.boolAttr(elem, "frame"),
shadow: xml2.boolAttr(elem, "shadow")
};
}
function parseBorders(elem, xml2) {
var result = {};
for (let e9 of xml2.elements(elem)) {
switch (e9.localName) {
case "left":
result.left = parseBorder(e9, xml2);
break;
case "top":
result.top = parseBorder(e9, xml2);
break;
case "right":
result.right = parseBorder(e9, xml2);
break;
case "bottom":
result.bottom = parseBorder(e9, xml2);
break;
}
}
return result;
}
function parseSectionProperties(elem, xml2 = globalXmlParser) {
var section = {};
for (let e9 of xml2.elements(elem)) {
switch (e9.localName) {
case "pgSz":
section.pageSize = {
width: xml2.lengthAttr(e9, "w"),
height: xml2.lengthAttr(e9, "h"),
orientation: xml2.attr(e9, "orient")
};
break;
case "type":
section.type = xml2.attr(e9, "val");
break;
case "pgMar":
section.pageMargins = {
left: xml2.lengthAttr(e9, "left"),
right: xml2.lengthAttr(e9, "right"),
top: xml2.lengthAttr(e9, "top"),
bottom: xml2.lengthAttr(e9, "bottom"),
header: xml2.lengthAttr(e9, "header"),
footer: xml2.lengthAttr(e9, "footer"),
gutter: xml2.lengthAttr(e9, "gutter")
};
break;
case "cols":
section.columns = parseColumns(e9, xml2);
break;
case "headerReference":
(section.headerRefs ?? (section.headerRefs = [])).push(parseFooterHeaderReference(e9, xml2));
break;
case "footerReference":
(section.footerRefs ?? (section.footerRefs = [])).push(parseFooterHeaderReference(e9, xml2));
break;
case "titlePg":
section.titlePage = xml2.boolAttr(e9, "val", true);
break;
case "pgBorders":
section.pageBorders = parseBorders(e9, xml2);
break;
case "pgNumType":
section.pageNumber = parsePageNumber(e9, xml2);
break;
}
}
return section;
}
function parseColumns(elem, xml2) {
return {
numberOfColumns: xml2.intAttr(elem, "num"),
space: xml2.lengthAttr(elem, "space"),
separator: xml2.boolAttr(elem, "sep"),
equalWidth: xml2.boolAttr(elem, "equalWidth", true),
columns: xml2.elements(elem, "col").map((e9) => ({
width: xml2.lengthAttr(e9, "w"),
space: xml2.lengthAttr(e9, "space")
}))
};
}
function parsePageNumber(elem, xml2) {
return {
chapSep: xml2.attr(elem, "chapSep"),
chapStyle: xml2.attr(elem, "chapStyle"),
format: xml2.attr(elem, "fmt"),
start: xml2.intAttr(elem, "start")
};
}
function parseFooterHeaderReference(elem, xml2) {
return {
id: xml2.attr(elem, "id"),
type: xml2.attr(elem, "type")
};
}
function parseLineSpacing(elem, xml2) {
return {
before: xml2.lengthAttr(elem, "before"),
after: xml2.lengthAttr(elem, "after"),
line: xml2.intAttr(elem, "line"),
lineRule: xml2.attr(elem, "lineRule")
};
}
function parseRunProperties(elem, xml2) {
let result = {};
for (let el of xml2.elements(elem)) {
parseRunProperty(el, result, xml2);
}
return result;
}
function parseRunProperty(elem, props, xml2) {
if (parseCommonProperty(elem, props, xml2))
return true;
return false;
}
function parseParagraphProperties(elem, xml2) {
let result = {};
for (let el of xml2.elements(elem)) {
parseParagraphProperty(el, result, xml2);
}
return result;
}
function parseParagraphProperty(elem, props, xml2) {
if (elem.namespaceURI != ns$1.wordml)
return false;
if (parseCommonProperty(elem, props, xml2))
return true;
switch (elem.localName) {
case "tabs":
props.tabs = parseTabs(elem, xml2);
break;
case "sectPr":
props.sectionProps = parseSectionProperties(elem, xml2);
break;
case "numPr":
props.numbering = parseNumbering$1(elem, xml2);
break;
case "spacing":
props.lineSpacing = parseLineSpacing(elem, xml2);
return false;
case "textAlignment":
props.textAlignment = xml2.attr(elem, "val");
return false;
case "keepLines":
props.keepLines = xml2.boolAttr(elem, "val", true);
break;
case "keepNext":
props.keepNext = xml2.boolAttr(elem, "val", true);
break;
case "pageBreakBefore":
props.pageBreakBefore = xml2.boolAttr(elem, "val", true);
break;
case "outlineLvl":
props.outlineLevel = xml2.intAttr(elem, "val");
break;
case "pStyle":
props.styleName = xml2.attr(elem, "val");
break;
case "rPr":
props.runProps = parseRunProperties(elem, xml2);
break;
default:
return false;
}
return true;
}
function parseTabs(elem, xml2) {
return xml2.elements(elem, "tab").map((e9) => ({
position: xml2.lengthAttr(e9, "pos"),
leader: xml2.attr(e9, "leader"),
style: xml2.attr(e9, "val")
}));
}
function parseNumbering$1(elem, xml2) {
var result = {};
for (let e9 of xml2.elements(elem)) {
switch (e9.localName) {
case "numId":
result.id = xml2.attr(e9, "val");
break;
case "ilvl":
result.level = xml2.intAttr(e9, "val");
break;
}
}
return result;
}
function parseNumberingPart(elem, xml2) {
let result = {
numberings: [],
abstractNumberings: [],
bulletPictures: []
};
for (let e9 of xml2.elements(elem)) {
switch (e9.localName) {
case "num":
result.numberings.push(parseNumbering(e9, xml2));
break;
case "abstractNum":
result.abstractNumberings.push(parseAbstractNumbering(e9, xml2));
break;
case "numPicBullet":
result.bulletPictures.push(parseNumberingBulletPicture(e9, xml2));
break;
}
}
return result;
}
function parseNumbering(elem, xml2) {
let result = {
id: xml2.attr(elem, "numId"),
overrides: []
};
for (let e9 of xml2.elements(elem)) {
switch (e9.localName) {
case "abstractNumId":
result.abstractId = xml2.attr(e9, "val");
break;
case "lvlOverride":
result.overrides.push(parseNumberingLevelOverrride(e9, xml2));
break;
}
}
return result;
}
function parseAbstractNumbering(elem, xml2) {
let result = {
id: xml2.attr(elem, "abstractNumId"),
levels: []
};
for (let e9 of xml2.elements(elem)) {
switch (e9.localName) {
case "name":
result.name = xml2.attr(e9, "val");
break;
case "multiLevelType":
result.multiLevelType = xml2.attr(e9, "val");
break;
case "numStyleLink":
result.numberingStyleLink = xml2.attr(e9, "val");
break;
case "styleLink":
result.styleLink = xml2.attr(e9, "val");
break;
case "lvl":
result.levels.push(parseNumberingLevel(e9, xml2));
break;
}
}
return result;
}
function parseNumberingLevel(elem, xml2) {
let result = {
level: xml2.intAttr(elem, "ilvl")
};
for (let e9 of xml2.elements(elem)) {
switch (e9.localName) {
case "start":
result.start = xml2.attr(e9, "val");
break;
case "lvlRestart":
result.restart = xml2.intAttr(e9, "val");
break;
case "numFmt":
result.format = xml2.attr(e9, "val");
break;
case "lvlText":
result.text = xml2.attr(e9, "val");
break;
case "lvlJc":
result.justification = xml2.attr(e9, "val");
break;
case "lvlPicBulletId":
result.bulletPictureId = xml2.attr(e9, "val");
break;
case "pStyle":
result.paragraphStyle = xml2.attr(e9, "val");
break;
case "pPr":
result.paragraphProps = parseParagraphProperties(e9, xml2);
break;
case "rPr":
result.runProps = parseRunProperties(e9, xml2);
break;
}
}
return result;
}
function parseNumberingLevelOverrride(elem, xml2) {
let result = {
level: xml2.intAttr(elem, "ilvl")
};
for (let e9 of xml2.elements(elem)) {
switch (e9.localName) {
case "startOverride":
result.start = xml2.intAttr(e9, "val");
break;
case "lvl":
result.numberingLevel = parseNumberingLevel(e9, xml2);
break;
}
}
return result;
}
function parseNumberingBulletPicture(elem, xml2) {
var pict = xml2.element(elem, "pict");
var shape = pict && xml2.element(pict, "shape");
var imagedata = shape && xml2.element(shape, "imagedata");
return imagedata ? {
id: xml2.attr(elem, "numPicBulletId"),
referenceId: xml2.attr(imagedata, "id"),
style: xml2.attr(shape, "style")
} : null;
}
function parseExtendedProps(root, xmlParser) {
const result = {};
for (let el of xmlParser.elements(root)) {
switch (el.localName) {
case "Template":
result.template = el.textContent;
break;
case "Pages":
result.pages = safeParseToInt(el.textContent);
break;
case "Words":
result.words = safeParseToInt(el.textContent);
break;
case "Characters":
result.characters = safeParseToInt(el.textContent);
break;
case "Application":
result.application = el.textContent;
break;
case "Lines":
result.lines = safeParseToInt(el.textContent);
break;
case "Paragraphs":
result.paragraphs = safeParseToInt(el.textContent);
break;
case "Company":
result.company = el.textContent;
break;
case "AppVersion":
result.appVersion = el.textContent;
break;
}
}
return result;
}
function safeParseToInt(value) {
if (typeof value === "undefined")
return;
return parseInt(value);
}
function parseCoreProps(root, xmlParser) {
const result = {};
for (let el of xmlParser.elements(root)) {
switch (el.localName) {
case "title":
result.title = el.textContent;
break;
case "description":
result.description = el.textContent;
break;
case "subject":
result.subject = el.textContent;
break;
case "creator":
result.creator = el.textContent;
break;
case "keywords":
result.keywords = el.textContent;
break;
case "language":
result.language = el.textContent;
break;
case "lastModifiedBy":
result.lastModifiedBy = el.textContent;
break;
case "revision":
el.textContent && (result.revision = parseInt(el.textContent));
break;
}
}
return result;
}
function parseTheme(elem, xml2) {
var result = new DmlTheme();
var themeElements = xml2.element(elem, "themeElements");
for (let el of xml2.elements(themeElements)) {
switch (el.localName) {
case "clrScheme":
result.colorScheme = parseColorScheme(el, xml2);
break;
case "fontScheme":
result.fontScheme = parseFontScheme(el, xml2);
break;
}
}
return result;
}
function parseColorScheme(elem, xml2) {
var result = {
name: xml2.attr(elem, "name"),
colors: {}
};
for (let el of xml2.elements(elem)) {
var srgbClr = xml2.element(el, "srgbClr");
var sysClr = xml2.element(el, "sysClr");
if (srgbClr) {
result.colors[el.localName] = xml2.attr(srgbClr, "val");
} else if (sysClr) {
result.colors[el.localName] = xml2.attr(sysClr, "lastClr");
}
}
return result;
}
function parseFontScheme(elem, xml2) {
var result = {
name: xml2.attr(elem, "name")
};
for (let el of xml2.elements(elem)) {
switch (el.localName) {
case "majorFont":
result.majorFont = parseFontInfo(el, xml2);
break;
case "minorFont":
result.minorFont = parseFontInfo(el, xml2);
break;
}
}
return result;
}
function parseFontInfo(elem, xml2) {
return {
latinTypeface: xml2.elementAttr(elem, "latin", "typeface"),
eaTypeface: xml2.elementAttr(elem, "ea", "typeface"),
csTypeface: xml2.elementAttr(elem, "cs", "typeface")
};
}
function parseSettings(elem, xml2) {
var result = {};
for (let el of xml2.elements(elem)) {
switch (el.localName) {
case "defaultTabStop":
result.defaultTabStop = xml2.lengthAttr(el, "val");
break;
case "footnotePr":
result.footnoteProps = parseNoteProperties(el, xml2);
break;
case "endnotePr":
result.endnoteProps = parseNoteProperties(el, xml2);
break;
case "autoHyphenation":
result.autoHyphenation = xml2.boolAttr(el, "val");
break;
}
}
return result;
}
function parseNoteProperties(elem, xml2) {
var result = {
defaultNoteIds: []
};
for (let el of xml2.elements(elem)) {
switch (el.localName) {
case "numFmt":
result.nummeringFormat = xml2.attr(el, "val");
break;
case "footnote":
case "endnote":
result.defaultNoteIds.push(xml2.attr(el, "id"));
break;
}
}
return result;
}
function parseCustomProps(root, xml2) {
return xml2.elements(root, "property").map((e9) => {
const firstChild = e9.firstChild;
return {
formatId: xml2.attr(e9, "fmtid"),
name: xml2.attr(e9, "name"),
type: firstChild.nodeName,
value: firstChild.textContent
};
});
}
function deobfuscate(data, guidKey) {
const len = 16;
const trimmed = guidKey.replace(/{|}|-/g, "");
const numbers2 = new Array(len);
for (let i7 = 0; i7 < len; i7++)
numbers2[len - i7 - 1] = parseInt(trimmed.substring(i7 * 2, i7 * 2 + 2), 16);
for (let i7 = 0; i7 < 32; i7++)
data[i7] = data[i7] ^ numbers2[i7 % len];
return data;
}
function parseBookmarkStart(elem, xml2) {
return {
type: DomType.BookmarkStart,
id: xml2.attr(elem, "id"),
name: xml2.attr(elem, "name"),
colFirst: xml2.intAttr(elem, "colFirst"),
colLast: xml2.intAttr(elem, "colLast")
};
}
function parseBookmarkEnd(elem, xml2) {
return {
type: DomType.BookmarkEnd,
id: xml2.attr(elem, "id")
};
}
function parseVmlElement(elem, parser) {
var result = new VmlElement();
switch (elem.localName) {
case "rect":
result.tagName = "rect";
Object.assign(result.attrs, { width: "100%", height: "100%" });
break;
case "oval":
result.tagName = "ellipse";
Object.assign(result.attrs, { cx: "50%", cy: "50%", rx: "50%", ry: "50%" });
break;
case "line":
result.tagName = "line";
break;
case "shape":
result.tagName = "g";
break;
case "textbox":
result.tagName = "foreignObject";
Object.assign(result.attrs, { width: "100%", height: "100%" });
break;
default:
return null;
}
for (const at of globalXmlParser.attrs(elem)) {
switch (at.localName) {
case "style":
result.cssStyleText = at.value;
break;
case "fillcolor":
result.attrs.fill = at.value;
break;
case "from":
const [x1, y1] = parsePoint(at.value);
Object.assign(result.attrs, { x1, y1 });
break;
case "to":
const [x2, y22] = parsePoint(at.value);
Object.assign(result.attrs, { x2, y2: y22 });
break;
}
}
for (const el of globalXmlParser.elements(elem)) {
switch (el.localName) {
case "stroke":
Object.assign(result.attrs, parseStroke(el));
break;
case "fill":
Object.assign(result.attrs, parseFill());
break;
case "imagedata":
result.tagName = "image";
Object.assign(result.attrs, { width: "100%", height: "100%" });
result.imageHref = {
id: globalXmlParser.attr(el, "id"),
title: globalXmlParser.attr(el, "title")
};
break;
case "txbxContent":
result.children.push(...parser.parseBodyElements(el));
break;
default:
const child = parseVmlElement(el, parser);
child && result.children.push(child);
break;
}
}
return result;
}
function parseStroke(el) {
return {
"stroke": globalXmlParser.attr(el, "color"),
"stroke-width": globalXmlParser.lengthAttr(el, "weight", LengthUsage.Emu) ?? "1px"
};
}
function parseFill(el) {
return {};
}
function parsePoint(val2) {
return val2.split(",");
}
function computePixelToPoint(container = document.body) {
const temp = document.createElement("div");
temp.style.width = "100pt";
container.appendChild(temp);
const result = 100 / temp.offsetWidth;
container.removeChild(temp);
return result;
}
function updateTabStop(elem, tabs, defaultTabSize, pixelToPoint = 72 / 96) {
const p4 = elem.closest("p");
const ebb = elem.getBoundingClientRect();
const pbb = p4.getBoundingClientRect();
const pcs = getComputedStyle(p4);
const tabStops = tabs?.length > 0 ? tabs.map((t6) => ({
pos: lengthToPoint(t6.position),
leader: t6.leader,
style: t6.style
})).sort((a3, b4) => a3.pos - b4.pos) : [defaultTab];
const lastTab = tabStops[tabStops.length - 1];
const pWidthPt = pbb.width * pixelToPoint;
const size = lengthToPoint(defaultTabSize);
let pos = lastTab.pos + size;
if (pos < pWidthPt) {
for (; pos < pWidthPt && tabStops.length < maxTabs; pos += size) {
tabStops.push({ ...defaultTab, pos });
}
}
const marginLeft = parseFloat(pcs.marginLeft);
const pOffset = pbb.left + marginLeft;
const left = (ebb.left - pOffset) * pixelToPoint;
const tab = tabStops.find((t6) => t6.style != "clear" && t6.pos > left);
if (tab == null)
return;
let width = 1;
if (tab.style == "right" || tab.style == "center") {
const tabStops2 = Array.from(p4.querySelectorAll(`.${elem.className}`));
const nextIdx = tabStops2.indexOf(elem) + 1;
const range2 = document.createRange();
range2.setStart(elem, 1);
if (nextIdx < tabStops2.length) {
range2.setEndBefore(tabStops2[nextIdx]);
} else {
range2.setEndAfter(p4);
}
const mul = tab.style == "center" ? 0.5 : 1;
const nextBB = range2.getBoundingClientRect();
const offset = nextBB.left + mul * nextBB.width - (pbb.left - marginLeft);
width = tab.pos - offset * pixelToPoint;
} else {
width = tab.pos - left;
}
elem.innerHTML = " ";
elem.style.textDecoration = "inherit";
elem.style.wordSpacing = `${width.toFixed(0)}pt`;
switch (tab.leader) {
case "dot":
case "middleDot":
elem.style.textDecoration = "underline";
elem.style.textDecorationStyle = "dotted";
break;
case "hyphen":
case "heavy":
case "underscore":
elem.style.textDecoration = "underline";
break;
}
}
function lengthToPoint(length) {
return parseFloat(length);
}
function removeAllElements(elem) {
elem.innerHTML = "";
}
function appendChildren(elem, children) {
children.forEach((c6) => elem.appendChild(isString2(c6) ? document.createTextNode(c6) : c6));
}
function findParent(elem, type) {
var parent = elem.parent;
while (parent != null && parent.type != type)
parent = parent.parent;
return parent;
}
function parseAsync(data, userOptions) {
const ops = { ...defaultOptions2, ...userOptions };
return WordDocument.load(data, new DocumentParser(ops), ops);
}
async function renderDocument(document2, bodyContainer, styleContainer, userOptions) {
const ops = { ...defaultOptions2, ...userOptions };
const renderer = new HtmlRenderer(window.document);
return await renderer.render(document2, bodyContainer, styleContainer, ops);
}
async function renderAsync(data, bodyContainer, styleContainer, userOptions) {
const doc = await parseAsync(data, userOptions);
await renderDocument(doc, bodyContainer, styleContainer, userOptions);
return doc;
}
var import_jszip, RelationshipTypes, ns$1, LengthUsage, XmlParser, globalXmlParser, Part, embedFontTypeMap, FontTablePart, OpenXmlPackage, DocumentPart, SectionType, NumberingPart, StylesPart, DomType, OpenXmlElementBase, WmlHeader, WmlFooter, BaseHeaderFooterPart, HeaderPart, FooterPart, ExtendedPropsPart, CorePropsPart, DmlTheme, ThemePart, WmlBaseNote, WmlFootnote, WmlEndnote, BaseNotePart, FootnotesPart, EndnotesPart, SettingsPart, CustomPropsPart, CommentsPart, CommentsExtendedPart, topLevelRels, WordDocument, VmlElement, WmlComment, WmlCommentReference, WmlCommentRangeStart, WmlCommentRangeEnd, autos, supportedNamespaceURIs, mmlTagMap, DocumentParser, knownColors, xmlUtil, values, defaultTab, maxTabs, ns, HtmlRenderer, defaultOptions2;
var init_docx_preview = __esm({
"../pi-mono/node_modules/docx-preview/dist/docx-preview.mjs"() {
init_process_shim();
import_jszip = __toESM(require_jszip_min(), 1);
(function(RelationshipTypes2) {
RelationshipTypes2["OfficeDocument"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
RelationshipTypes2["FontTable"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable";
RelationshipTypes2["Image"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
RelationshipTypes2["Numbering"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering";
RelationshipTypes2["Styles"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
RelationshipTypes2["StylesWithEffects"] = "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects";
RelationshipTypes2["Theme"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme";
RelationshipTypes2["Settings"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings";
RelationshipTypes2["WebSettings"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings";
RelationshipTypes2["Hyperlink"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
RelationshipTypes2["Footnotes"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes";
RelationshipTypes2["Endnotes"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes";
RelationshipTypes2["Footer"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer";
RelationshipTypes2["Header"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header";
RelationshipTypes2["ExtendedProperties"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties";
RelationshipTypes2["CoreProperties"] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
RelationshipTypes2["CustomProperties"] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/custom-properties";
RelationshipTypes2["Comments"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
RelationshipTypes2["CommentsExtended"] = "http://schemas.microsoft.com/office/2011/relationships/commentsExtended";
RelationshipTypes2["AltChunk"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk";
})(RelationshipTypes || (RelationshipTypes = {}));
ns$1 = {
wordml: "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
};
LengthUsage = {
Dxa: { mul: 0.05, unit: "pt" },
Emu: { mul: 1 / 12700, unit: "pt" },
FontSize: { mul: 0.5, unit: "pt" },
Border: { mul: 0.125, unit: "pt", min: 0.25, max: 12 },
Point: { mul: 1, unit: "pt" },
Percent: { mul: 0.02, unit: "%" }
};
XmlParser = class {
elements(elem, localName = null) {
const result = [];
for (let i7 = 0, l5 = elem.childNodes.length; i7 < l5; i7++) {
let c6 = elem.childNodes.item(i7);
if (c6.nodeType == Node.ELEMENT_NODE && (localName == null || c6.localName == localName))
result.push(c6);
}
return result;
}
element(elem, localName) {
for (let i7 = 0, l5 = elem.childNodes.length; i7 < l5; i7++) {
let c6 = elem.childNodes.item(i7);
if (c6.nodeType == 1 && c6.localName == localName)
return c6;
}
return null;
}
elementAttr(elem, localName, attrLocalName) {
var el = this.element(elem, localName);
return el ? this.attr(el, attrLocalName) : void 0;
}
attrs(elem) {
return Array.from(elem.attributes);
}
attr(elem, localName) {
for (let i7 = 0, l5 = elem.attributes.length; i7 < l5; i7++) {
let a3 = elem.attributes.item(i7);
if (a3.localName == localName)
return a3.value;
}
return null;
}
intAttr(node, attrName, defaultValue = null) {
var val2 = this.attr(node, attrName);
return val2 ? parseInt(val2) : defaultValue;
}
hexAttr(node, attrName, defaultValue = null) {
var val2 = this.attr(node, attrName);
return val2 ? parseInt(val2, 16) : defaultValue;
}
floatAttr(node, attrName, defaultValue = null) {
var val2 = this.attr(node, attrName);
return val2 ? parseFloat(val2) : defaultValue;
}
boolAttr(node, attrName, defaultValue = null) {
return convertBoolean(this.attr(node, attrName), defaultValue);
}
lengthAttr(node, attrName, usage = LengthUsage.Dxa) {
return convertLength(this.attr(node, attrName), usage);
}
};
globalXmlParser = new XmlParser();
Part = class {
constructor(_package, path6) {
this._package = _package;
this.path = path6;
}
async load() {
this.rels = await this._package.loadRelationships(this.path);
const xmlText = await this._package.load(this.path);
const xmlDoc = this._package.parseXmlDocument(xmlText);
if (this._package.options.keepOrigin) {
this._xmlDocument = xmlDoc;
}
this.parseXml(xmlDoc.firstElementChild);
}
save() {
this._package.update(this.path, serializeXmlString(this._xmlDocument));
}
parseXml(root) {
}
};
embedFontTypeMap = {
embedRegular: "regular",
embedBold: "bold",
embedItalic: "italic",
embedBoldItalic: "boldItalic"
};
FontTablePart = class extends Part {
parseXml(root) {
this.fonts = parseFonts(root, this._package.xmlParser);
}
};
OpenXmlPackage = class _OpenXmlPackage {
constructor(_zip, options) {
this._zip = _zip;
this.options = options;
this.xmlParser = new XmlParser();
}
get(path6) {
const p4 = normalizePath(path6);
return this._zip.files[p4] ?? this._zip.files[p4.replace(/\//g, "\\")];
}
update(path6, content) {
this._zip.file(path6, content);
}
static async load(input, options) {
const zip = await import_jszip.default.loadAsync(input);
return new _OpenXmlPackage(zip, options);
}
save(type = "blob") {
return this._zip.generateAsync({ type });
}
load(path6, type = "string") {
return this.get(path6)?.async(type) ?? Promise.resolve(null);
}
async loadRelationships(path6 = null) {
let relsPath = `_rels/.rels`;
if (path6 != null) {
const [f4, fn] = splitPath(path6);
relsPath = `${f4}_rels/${fn}.rels`;
}
const txt = await this.load(relsPath);
return txt ? parseRelationships(this.parseXmlDocument(txt).firstElementChild, this.xmlParser) : null;
}
parseXmlDocument(txt) {
return parseXmlString(txt, this.options.trimXmlDeclaration);
}
};
DocumentPart = class extends Part {
constructor(pkg, path6, parser) {
super(pkg, path6);
this._documentParser = parser;
}
parseXml(root) {
this.body = this._documentParser.parseDocumentFile(root);
}
};
(function(SectionType2) {
SectionType2["Continuous"] = "continuous";
SectionType2["NextPage"] = "nextPage";
SectionType2["NextColumn"] = "nextColumn";
SectionType2["EvenPage"] = "evenPage";
SectionType2["OddPage"] = "oddPage";
})(SectionType || (SectionType = {}));
NumberingPart = class extends Part {
constructor(pkg, path6, parser) {
super(pkg, path6);
this._documentParser = parser;
}
parseXml(root) {
Object.assign(this, parseNumberingPart(root, this._package.xmlParser));
this.domNumberings = this._documentParser.parseNumberingFile(root);
}
};
StylesPart = class extends Part {
constructor(pkg, path6, parser) {
super(pkg, path6);
this._documentParser = parser;
}
parseXml(root) {
this.styles = this._documentParser.parseStylesFile(root);
}
};
(function(DomType2) {
DomType2["Document"] = "document";
DomType2["Paragraph"] = "paragraph";
DomType2["Run"] = "run";
DomType2["Break"] = "break";
DomType2["NoBreakHyphen"] = "noBreakHyphen";
DomType2["Table"] = "table";
DomType2["Row"] = "row";
DomType2["Cell"] = "cell";
DomType2["Hyperlink"] = "hyperlink";
DomType2["SmartTag"] = "smartTag";
DomType2["Drawing"] = "drawing";
DomType2["Image"] = "image";
DomType2["Text"] = "text";
DomType2["Tab"] = "tab";
DomType2["Symbol"] = "symbol";
DomType2["BookmarkStart"] = "bookmarkStart";
DomType2["BookmarkEnd"] = "bookmarkEnd";
DomType2["Footer"] = "footer";
DomType2["Header"] = "header";
DomType2["FootnoteReference"] = "footnoteReference";
DomType2["EndnoteReference"] = "endnoteReference";
DomType2["Footnote"] = "footnote";
DomType2["Endnote"] = "endnote";
DomType2["SimpleField"] = "simpleField";
DomType2["ComplexField"] = "complexField";
DomType2["Instruction"] = "instruction";
DomType2["VmlPicture"] = "vmlPicture";
DomType2["MmlMath"] = "mmlMath";
DomType2["MmlMathParagraph"] = "mmlMathParagraph";
DomType2["MmlFraction"] = "mmlFraction";
DomType2["MmlFunction"] = "mmlFunction";
DomType2["MmlFunctionName"] = "mmlFunctionName";
DomType2["MmlNumerator"] = "mmlNumerator";
DomType2["MmlDenominator"] = "mmlDenominator";
DomType2["MmlRadical"] = "mmlRadical";
DomType2["MmlBase"] = "mmlBase";
DomType2["MmlDegree"] = "mmlDegree";
DomType2["MmlSuperscript"] = "mmlSuperscript";
DomType2["MmlSubscript"] = "mmlSubscript";
DomType2["MmlPreSubSuper"] = "mmlPreSubSuper";
DomType2["MmlSubArgument"] = "mmlSubArgument";
DomType2["MmlSuperArgument"] = "mmlSuperArgument";
DomType2["MmlNary"] = "mmlNary";
DomType2["MmlDelimiter"] = "mmlDelimiter";
DomType2["MmlRun"] = "mmlRun";
DomType2["MmlEquationArray"] = "mmlEquationArray";
DomType2["MmlLimit"] = "mmlLimit";
DomType2["MmlLimitLower"] = "mmlLimitLower";
DomType2["MmlMatrix"] = "mmlMatrix";
DomType2["MmlMatrixRow"] = "mmlMatrixRow";
DomType2["MmlBox"] = "mmlBox";
DomType2["MmlBar"] = "mmlBar";
DomType2["MmlGroupChar"] = "mmlGroupChar";
DomType2["VmlElement"] = "vmlElement";
DomType2["Inserted"] = "inserted";
DomType2["Deleted"] = "deleted";
DomType2["DeletedText"] = "deletedText";
DomType2["Comment"] = "comment";
DomType2["CommentReference"] = "commentReference";
DomType2["CommentRangeStart"] = "commentRangeStart";
DomType2["CommentRangeEnd"] = "commentRangeEnd";
DomType2["AltChunk"] = "altChunk";
})(DomType || (DomType = {}));
OpenXmlElementBase = class {
constructor() {
this.children = [];
this.cssStyle = {};
}
};
WmlHeader = class extends OpenXmlElementBase {
constructor() {
super(...arguments);
this.type = DomType.Header;
}
};
WmlFooter = class extends OpenXmlElementBase {
constructor() {
super(...arguments);
this.type = DomType.Footer;
}
};
BaseHeaderFooterPart = class extends Part {
constructor(pkg, path6, parser) {
super(pkg, path6);
this._documentParser = parser;
}
parseXml(root) {
this.rootElement = this.createRootElement();
this.rootElement.children = this._documentParser.parseBodyElements(root);
}
};
HeaderPart = class extends BaseHeaderFooterPart {
createRootElement() {
return new WmlHeader();
}
};
FooterPart = class extends BaseHeaderFooterPart {
createRootElement() {
return new WmlFooter();
}
};
ExtendedPropsPart = class extends Part {
parseXml(root) {
this.props = parseExtendedProps(root, this._package.xmlParser);
}
};
CorePropsPart = class extends Part {
parseXml(root) {
this.props = parseCoreProps(root, this._package.xmlParser);
}
};
DmlTheme = class {
};
ThemePart = class extends Part {
constructor(pkg, path6) {
super(pkg, path6);
}
parseXml(root) {
this.theme = parseTheme(root, this._package.xmlParser);
}
};
WmlBaseNote = class {
};
WmlFootnote = class extends WmlBaseNote {
constructor() {
super(...arguments);
this.type = DomType.Footnote;
}
};
WmlEndnote = class extends WmlBaseNote {
constructor() {
super(...arguments);
this.type = DomType.Endnote;
}
};
BaseNotePart = class extends Part {
constructor(pkg, path6, parser) {
super(pkg, path6);
this._documentParser = parser;
}
};
FootnotesPart = class extends BaseNotePart {
constructor(pkg, path6, parser) {
super(pkg, path6, parser);
}
parseXml(root) {
this.notes = this._documentParser.parseNotes(root, "footnote", WmlFootnote);
}
};
EndnotesPart = class extends BaseNotePart {
constructor(pkg, path6, parser) {
super(pkg, path6, parser);
}
parseXml(root) {
this.notes = this._documentParser.parseNotes(root, "endnote", WmlEndnote);
}
};
SettingsPart = class extends Part {
constructor(pkg, path6) {
super(pkg, path6);
}
parseXml(root) {
this.settings = parseSettings(root, this._package.xmlParser);
}
};
CustomPropsPart = class extends Part {
parseXml(root) {
this.props = parseCustomProps(root, this._package.xmlParser);
}
};
CommentsPart = class extends Part {
constructor(pkg, path6, parser) {
super(pkg, path6);
this._documentParser = parser;
}
parseXml(root) {
this.comments = this._documentParser.parseComments(root);
this.commentMap = keyBy(this.comments, (x2) => x2.id);
}
};
CommentsExtendedPart = class extends Part {
constructor(pkg, path6) {
super(pkg, path6);
this.comments = [];
}
parseXml(root) {
const xml2 = this._package.xmlParser;
for (let el of xml2.elements(root, "commentEx")) {
this.comments.push({
paraId: xml2.attr(el, "paraId"),
paraIdParent: xml2.attr(el, "paraIdParent"),
done: xml2.boolAttr(el, "done")
});
}
this.commentMap = keyBy(this.comments, (x2) => x2.paraId);
}
};
topLevelRels = [
{ type: RelationshipTypes.OfficeDocument, target: "word/document.xml" },
{ type: RelationshipTypes.ExtendedProperties, target: "docProps/app.xml" },
{ type: RelationshipTypes.CoreProperties, target: "docProps/core.xml" },
{ type: RelationshipTypes.CustomProperties, target: "docProps/custom.xml" }
];
WordDocument = class _WordDocument {
constructor() {
this.parts = [];
this.partsMap = {};
}
static async load(blob, parser, options) {
var d4 = new _WordDocument();
d4._options = options;
d4._parser = parser;
d4._package = await OpenXmlPackage.load(blob, options);
d4.rels = await d4._package.loadRelationships();
await Promise.all(topLevelRels.map((rel2) => {
const r8 = d4.rels.find((x2) => x2.type === rel2.type) ?? rel2;
return d4.loadRelationshipPart(r8.target, r8.type);
}));
return d4;
}
save(type = "blob") {
return this._package.save(type);
}
async loadRelationshipPart(path6, type) {
if (this.partsMap[path6])
return this.partsMap[path6];
if (!this._package.get(path6))
return null;
let part = null;
switch (type) {
case RelationshipTypes.OfficeDocument:
this.documentPart = part = new DocumentPart(this._package, path6, this._parser);
break;
case RelationshipTypes.FontTable:
this.fontTablePart = part = new FontTablePart(this._package, path6);
break;
case RelationshipTypes.Numbering:
this.numberingPart = part = new NumberingPart(this._package, path6, this._parser);
break;
case RelationshipTypes.Styles:
this.stylesPart = part = new StylesPart(this._package, path6, this._parser);
break;
case RelationshipTypes.Theme:
this.themePart = part = new ThemePart(this._package, path6);
break;
case RelationshipTypes.Footnotes:
this.footnotesPart = part = new FootnotesPart(this._package, path6, this._parser);
break;
case RelationshipTypes.Endnotes:
this.endnotesPart = part = new EndnotesPart(this._package, path6, this._parser);
break;
case RelationshipTypes.Footer:
part = new FooterPart(this._package, path6, this._parser);
break;
case RelationshipTypes.Header:
part = new HeaderPart(this._package, path6, this._parser);
break;
case RelationshipTypes.CoreProperties:
this.corePropsPart = part = new CorePropsPart(this._package, path6);
break;
case RelationshipTypes.ExtendedProperties:
this.extendedPropsPart = part = new ExtendedPropsPart(this._package, path6);
break;
case RelationshipTypes.CustomProperties:
part = new CustomPropsPart(this._package, path6);
break;
case RelationshipTypes.Settings:
this.settingsPart = part = new SettingsPart(this._package, path6);
break;
case RelationshipTypes.Comments:
this.commentsPart = part = new CommentsPart(this._package, path6, this._parser);
break;
case RelationshipTypes.CommentsExtended:
this.commentsExtendedPart = part = new CommentsExtendedPart(this._package, path6);
break;
}
if (part == null)
return Promise.resolve(null);
this.partsMap[path6] = part;
this.parts.push(part);
await part.load();
if (part.rels?.length > 0) {
const [folder] = splitPath(part.path);
await Promise.all(part.rels.map((rel2) => this.loadRelationshipPart(resolvePath(rel2.target, folder), rel2.type)));
}
return part;
}
async loadDocumentImage(id, part) {
const x2 = await this.loadResource(part ?? this.documentPart, id, "blob");
return this.blobToURL(x2);
}
async loadNumberingImage(id) {
const x2 = await this.loadResource(this.numberingPart, id, "blob");
return this.blobToURL(x2);
}
async loadFont(id, key) {
const x2 = await this.loadResource(this.fontTablePart, id, "uint8array");
return x2 ? this.blobToURL(new Blob([deobfuscate(x2, key)])) : x2;
}
async loadAltChunk(id, part) {
return await this.loadResource(part ?? this.documentPart, id, "string");
}
blobToURL(blob) {
if (!blob)
return null;
if (this._options.useBase64URL) {
return blobToBase64(blob);
}
return URL.createObjectURL(blob);
}
findPartByRelId(id, basePart = null) {
var rel2 = (basePart.rels ?? this.rels).find((r8) => r8.id == id);
const folder = basePart ? splitPath(basePart.path)[0] : "";
return rel2 ? this.partsMap[resolvePath(rel2.target, folder)] : null;
}
getPathById(part, id) {
const rel2 = part.rels.find((x2) => x2.id == id);
const [folder] = splitPath(part.path);
return rel2 ? resolvePath(rel2.target, folder) : null;
}
loadResource(part, id, outputType) {
const path6 = this.getPathById(part, id);
return path6 ? this._package.load(path6, outputType) : Promise.resolve(null);
}
};
VmlElement = class extends OpenXmlElementBase {
constructor() {
super(...arguments);
this.type = DomType.VmlElement;
this.attrs = {};
}
};
WmlComment = class extends OpenXmlElementBase {
constructor() {
super(...arguments);
this.type = DomType.Comment;
}
};
WmlCommentReference = class extends OpenXmlElementBase {
constructor(id) {
super();
this.id = id;
this.type = DomType.CommentReference;
}
};
WmlCommentRangeStart = class extends OpenXmlElementBase {
constructor(id) {
super();
this.id = id;
this.type = DomType.CommentRangeStart;
}
};
WmlCommentRangeEnd = class extends OpenXmlElementBase {
constructor(id) {
super();
this.id = id;
this.type = DomType.CommentRangeEnd;
}
};
autos = {
shd: "inherit",
color: "black",
borderColor: "black",
highlight: "transparent"
};
supportedNamespaceURIs = [];
mmlTagMap = {
"oMath": DomType.MmlMath,
"oMathPara": DomType.MmlMathParagraph,
"f": DomType.MmlFraction,
"func": DomType.MmlFunction,
"fName": DomType.MmlFunctionName,
"num": DomType.MmlNumerator,
"den": DomType.MmlDenominator,
"rad": DomType.MmlRadical,
"deg": DomType.MmlDegree,
"e": DomType.MmlBase,
"sSup": DomType.MmlSuperscript,
"sSub": DomType.MmlSubscript,
"sPre": DomType.MmlPreSubSuper,
"sup": DomType.MmlSuperArgument,
"sub": DomType.MmlSubArgument,
"d": DomType.MmlDelimiter,
"nary": DomType.MmlNary,
"eqArr": DomType.MmlEquationArray,
"lim": DomType.MmlLimit,
"limLow": DomType.MmlLimitLower,
"m": DomType.MmlMatrix,
"mr": DomType.MmlMatrixRow,
"box": DomType.MmlBox,
"bar": DomType.MmlBar,
"groupChr": DomType.MmlGroupChar
};
DocumentParser = class {
constructor(options) {
this.options = {
ignoreWidth: false,
debug: false,
...options
};
}
parseNotes(xmlDoc, elemName, elemClass) {
var result = [];
for (let el of globalXmlParser.elements(xmlDoc, elemName)) {
const node = new elemClass();
node.id = globalXmlParser.attr(el, "id");
node.noteType = globalXmlParser.attr(el, "type");
node.children = this.parseBodyElements(el);
result.push(node);
}
return result;
}
parseComments(xmlDoc) {
var result = [];
for (let el of globalXmlParser.elements(xmlDoc, "comment")) {
const item = new WmlComment();
item.id = globalXmlParser.attr(el, "id");
item.author = globalXmlParser.attr(el, "author");
item.initials = globalXmlParser.attr(el, "initials");
item.date = globalXmlParser.attr(el, "date");
item.children = this.parseBodyElements(el);
result.push(item);
}
return result;
}
parseDocumentFile(xmlDoc) {
var xbody = globalXmlParser.element(xmlDoc, "body");
var background = globalXmlParser.element(xmlDoc, "background");
var sectPr = globalXmlParser.element(xbody, "sectPr");
return {
type: DomType.Document,
children: this.parseBodyElements(xbody),
props: sectPr ? parseSectionProperties(sectPr, globalXmlParser) : {},
cssStyle: background ? this.parseBackground(background) : {}
};
}
parseBackground(elem) {
var result = {};
var color2 = xmlUtil.colorAttr(elem, "color");
if (color2) {
result["background-color"] = color2;
}
return result;
}
parseBodyElements(element) {
var children = [];
for (const elem of globalXmlParser.elements(element)) {
switch (elem.localName) {
case "p":
children.push(this.parseParagraph(elem));
break;
case "altChunk":
children.push(this.parseAltChunk(elem));
break;
case "tbl":
children.push(this.parseTable(elem));
break;
case "sdt":
children.push(...this.parseSdt(elem, (e9) => this.parseBodyElements(e9)));
break;
}
}
return children;
}
parseStylesFile(xstyles) {
var result = [];
for (const n7 of globalXmlParser.elements(xstyles)) {
switch (n7.localName) {
case "style":
result.push(this.parseStyle(n7));
break;
case "docDefaults":
result.push(this.parseDefaultStyles(n7));
break;
}
}
return result;
}
parseDefaultStyles(node) {
var result = {
id: null,
name: null,
target: null,
basedOn: null,
styles: []
};
for (const c6 of globalXmlParser.elements(node)) {
switch (c6.localName) {
case "rPrDefault":
var rPr = globalXmlParser.element(c6, "rPr");
if (rPr)
result.styles.push({
target: "span",
values: this.parseDefaultProperties(rPr, {})
});
break;
case "pPrDefault":
var pPr = globalXmlParser.element(c6, "pPr");
if (pPr)
result.styles.push({
target: "p",
values: this.parseDefaultProperties(pPr, {})
});
break;
}
}
return result;
}
parseStyle(node) {
var result = {
id: globalXmlParser.attr(node, "styleId"),
isDefault: globalXmlParser.boolAttr(node, "default"),
name: null,
target: null,
basedOn: null,
styles: [],
linked: null
};
switch (globalXmlParser.attr(node, "type")) {
case "paragraph":
result.target = "p";
break;
case "table":
result.target = "table";
break;
case "character":
result.target = "span";
break;
}
for (const n7 of globalXmlParser.elements(node)) {
switch (n7.localName) {
case "basedOn":
result.basedOn = globalXmlParser.attr(n7, "val");
break;
case "name":
result.name = globalXmlParser.attr(n7, "val");
break;
case "link":
result.linked = globalXmlParser.attr(n7, "val");
break;
case "next":
result.next = globalXmlParser.attr(n7, "val");
break;
case "aliases":
result.aliases = globalXmlParser.attr(n7, "val").split(",");
break;
case "pPr":
result.styles.push({
target: "p",
values: this.parseDefaultProperties(n7, {})
});
result.paragraphProps = parseParagraphProperties(n7, globalXmlParser);
break;
case "rPr":
result.styles.push({
target: "span",
values: this.parseDefaultProperties(n7, {})
});
result.runProps = parseRunProperties(n7, globalXmlParser);
break;
case "tblPr":
case "tcPr":
result.styles.push({
target: "td",
values: this.parseDefaultProperties(n7, {})
});
break;
case "tblStylePr":
for (let s6 of this.parseTableStyle(n7))
result.styles.push(s6);
break;
case "rsid":
case "qFormat":
case "hidden":
case "semiHidden":
case "unhideWhenUsed":
case "autoRedefine":
case "uiPriority":
break;
default:
this.options.debug && console.warn(`DOCX: Unknown style element: ${n7.localName}`);
}
}
return result;
}
parseTableStyle(node) {
var result = [];
var type = globalXmlParser.attr(node, "type");
var selector = "";
var modificator = "";
switch (type) {
case "firstRow":
modificator = ".first-row";
selector = "tr.first-row td";
break;
case "lastRow":
modificator = ".last-row";
selector = "tr.last-row td";
break;
case "firstCol":
modificator = ".first-col";
selector = "td.first-col";
break;
case "lastCol":
modificator = ".last-col";
selector = "td.last-col";
break;
case "band1Vert":
modificator = ":not(.no-vband)";
selector = "td.odd-col";
break;
case "band2Vert":
modificator = ":not(.no-vband)";
selector = "td.even-col";
break;
case "band1Horz":
modificator = ":not(.no-hband)";
selector = "tr.odd-row";
break;
case "band2Horz":
modificator = ":not(.no-hband)";
selector = "tr.even-row";
break;
default:
return [];
}
for (const n7 of globalXmlParser.elements(node)) {
switch (n7.localName) {
case "pPr":
result.push({
target: `${selector} p`,
mod: modificator,
values: this.parseDefaultProperties(n7, {})
});
break;
case "rPr":
result.push({
target: `${selector} span`,
mod: modificator,
values: this.parseDefaultProperties(n7, {})
});
break;
case "tblPr":
case "tcPr":
result.push({
target: selector,
mod: modificator,
values: this.parseDefaultProperties(n7, {})
});
break;
}
}
return result;
}
parseNumberingFile(node) {
var result = [];
var mapping = {};
var bullets = [];
for (const n7 of globalXmlParser.elements(node)) {
switch (n7.localName) {
case "abstractNum":
this.parseAbstractNumbering(n7, bullets).forEach((x2) => result.push(x2));
break;
case "numPicBullet":
bullets.push(this.parseNumberingPicBullet(n7));
break;
case "num":
var numId = globalXmlParser.attr(n7, "numId");
var abstractNumId = globalXmlParser.elementAttr(n7, "abstractNumId", "val");
mapping[abstractNumId] = numId;
break;
}
}
result.forEach((x2) => x2.id = mapping[x2.id]);
return result;
}
parseNumberingPicBullet(elem) {
var pict = globalXmlParser.element(elem, "pict");
var shape = pict && globalXmlParser.element(pict, "shape");
var imagedata = shape && globalXmlParser.element(shape, "imagedata");
return imagedata ? {
id: globalXmlParser.intAttr(elem, "numPicBulletId"),
src: globalXmlParser.attr(imagedata, "id"),
style: globalXmlParser.attr(shape, "style")
} : null;
}
parseAbstractNumbering(node, bullets) {
var result = [];
var id = globalXmlParser.attr(node, "abstractNumId");
for (const n7 of globalXmlParser.elements(node)) {
switch (n7.localName) {
case "lvl":
result.push(this.parseNumberingLevel(id, n7, bullets));
break;
}
}
return result;
}
parseNumberingLevel(id, node, bullets) {
var result = {
id,
level: globalXmlParser.intAttr(node, "ilvl"),
start: 1,
pStyleName: void 0,
pStyle: {},
rStyle: {},
suff: "tab"
};
for (const n7 of globalXmlParser.elements(node)) {
switch (n7.localName) {
case "start":
result.start = globalXmlParser.intAttr(n7, "val");
break;
case "pPr":
this.parseDefaultProperties(n7, result.pStyle);
break;
case "rPr":
this.parseDefaultProperties(n7, result.rStyle);
break;
case "lvlPicBulletId":
var bulletId = globalXmlParser.intAttr(n7, "val");
result.bullet = bullets.find((x2) => x2?.id == bulletId);
break;
case "lvlText":
result.levelText = globalXmlParser.attr(n7, "val");
break;
case "pStyle":
result.pStyleName = globalXmlParser.attr(n7, "val");
break;
case "numFmt":
result.format = globalXmlParser.attr(n7, "val");
break;
case "suff":
result.suff = globalXmlParser.attr(n7, "val");
break;
}
}
return result;
}
parseSdt(node, parser) {
const sdtContent = globalXmlParser.element(node, "sdtContent");
return sdtContent ? parser(sdtContent) : [];
}
parseInserted(node, parentParser) {
return {
type: DomType.Inserted,
children: parentParser(node)?.children ?? []
};
}
parseDeleted(node, parentParser) {
return {
type: DomType.Deleted,
children: parentParser(node)?.children ?? []
};
}
parseAltChunk(node) {
return { type: DomType.AltChunk, children: [], id: globalXmlParser.attr(node, "id") };
}
parseParagraph(node) {
var result = { type: DomType.Paragraph, children: [] };
for (let el of globalXmlParser.elements(node)) {
switch (el.localName) {
case "pPr":
this.parseParagraphProperties(el, result);
break;
case "r":
result.children.push(this.parseRun(el, result));
break;
case "hyperlink":
result.children.push(this.parseHyperlink(el, result));
break;
case "smartTag":
result.children.push(this.parseSmartTag(el, result));
break;
case "bookmarkStart":
result.children.push(parseBookmarkStart(el, globalXmlParser));
break;
case "bookmarkEnd":
result.children.push(parseBookmarkEnd(el, globalXmlParser));
break;
case "commentRangeStart":
result.children.push(new WmlCommentRangeStart(globalXmlParser.attr(el, "id")));
break;
case "commentRangeEnd":
result.children.push(new WmlCommentRangeEnd(globalXmlParser.attr(el, "id")));
break;
case "oMath":
case "oMathPara":
result.children.push(this.parseMathElement(el));
break;
case "sdt":
result.children.push(...this.parseSdt(el, (e9) => this.parseParagraph(e9).children));
break;
case "ins":
result.children.push(this.parseInserted(el, (e9) => this.parseParagraph(e9)));
break;
case "del":
result.children.push(this.parseDeleted(el, (e9) => this.parseParagraph(e9)));
break;
}
}
return result;
}
parseParagraphProperties(elem, paragraph) {
this.parseDefaultProperties(elem, paragraph.cssStyle = {}, null, (c6) => {
if (parseParagraphProperty(c6, paragraph, globalXmlParser))
return true;
switch (c6.localName) {
case "pStyle":
paragraph.styleName = globalXmlParser.attr(c6, "val");
break;
case "cnfStyle":
paragraph.className = values.classNameOfCnfStyle(c6);
break;
case "framePr":
this.parseFrame(c6, paragraph);
break;
case "rPr":
break;
default:
return false;
}
return true;
});
}
parseFrame(node, paragraph) {
var dropCap = globalXmlParser.attr(node, "dropCap");
if (dropCap == "drop")
paragraph.cssStyle["float"] = "left";
}
parseHyperlink(node, parent) {
var result = { type: DomType.Hyperlink, parent, children: [] };
result.anchor = globalXmlParser.attr(node, "anchor");
result.id = globalXmlParser.attr(node, "id");
for (const c6 of globalXmlParser.elements(node)) {
switch (c6.localName) {
case "r":
result.children.push(this.parseRun(c6, result));
break;
}
}
return result;
}
parseSmartTag(node, parent) {
var result = { type: DomType.SmartTag, parent, children: [] };
var uri = globalXmlParser.attr(node, "uri");
var element = globalXmlParser.attr(node, "element");
if (uri)
result.uri = uri;
if (element)
result.element = element;
for (const c6 of globalXmlParser.elements(node)) {
switch (c6.localName) {
case "r":
result.children.push(this.parseRun(c6, result));
break;
}
}
return result;
}
parseRun(node, parent) {
var result = { type: DomType.Run, parent, children: [] };
for (let c6 of globalXmlParser.elements(node)) {
c6 = this.checkAlternateContent(c6);
switch (c6.localName) {
case "t":
result.children.push({
type: DomType.Text,
text: c6.textContent
});
break;
case "delText":
result.children.push({
type: DomType.DeletedText,
text: c6.textContent
});
break;
case "commentReference":
result.children.push(new WmlCommentReference(globalXmlParser.attr(c6, "id")));
break;
case "fldSimple":
result.children.push({
type: DomType.SimpleField,
instruction: globalXmlParser.attr(c6, "instr"),
lock: globalXmlParser.boolAttr(c6, "lock", false),
dirty: globalXmlParser.boolAttr(c6, "dirty", false)
});
break;
case "instrText":
result.fieldRun = true;
result.children.push({
type: DomType.Instruction,
text: c6.textContent
});
break;
case "fldChar":
result.fieldRun = true;
result.children.push({
type: DomType.ComplexField,
charType: globalXmlParser.attr(c6, "fldCharType"),
lock: globalXmlParser.boolAttr(c6, "lock", false),
dirty: globalXmlParser.boolAttr(c6, "dirty", false)
});
break;
case "noBreakHyphen":
result.children.push({ type: DomType.NoBreakHyphen });
break;
case "br":
result.children.push({
type: DomType.Break,
break: globalXmlParser.attr(c6, "type") || "textWrapping"
});
break;
case "lastRenderedPageBreak":
result.children.push({
type: DomType.Break,
break: "lastRenderedPageBreak"
});
break;
case "sym":
result.children.push({
type: DomType.Symbol,
font: encloseFontFamily(globalXmlParser.attr(c6, "font")),
char: globalXmlParser.attr(c6, "char")
});
break;
case "tab":
result.children.push({ type: DomType.Tab });
break;
case "footnoteReference":
result.children.push({
type: DomType.FootnoteReference,
id: globalXmlParser.attr(c6, "id")
});
break;
case "endnoteReference":
result.children.push({
type: DomType.EndnoteReference,
id: globalXmlParser.attr(c6, "id")
});
break;
case "drawing":
let d4 = this.parseDrawing(c6);
if (d4)
result.children = [d4];
break;
case "pict":
result.children.push(this.parseVmlPicture(c6));
break;
case "rPr":
this.parseRunProperties(c6, result);
break;
}
}
return result;
}
parseMathElement(elem) {
const propsTag = `${elem.localName}Pr`;
const result = { type: mmlTagMap[elem.localName], children: [] };
for (const el of globalXmlParser.elements(elem)) {
const childType = mmlTagMap[el.localName];
if (childType) {
result.children.push(this.parseMathElement(el));
} else if (el.localName == "r") {
var run = this.parseRun(el);
run.type = DomType.MmlRun;
result.children.push(run);
} else if (el.localName == propsTag) {
result.props = this.parseMathProperies(el);
}
}
return result;
}
parseMathProperies(elem) {
const result = {};
for (const el of globalXmlParser.elements(elem)) {
switch (el.localName) {
case "chr":
result.char = globalXmlParser.attr(el, "val");
break;
case "vertJc":
result.verticalJustification = globalXmlParser.attr(el, "val");
break;
case "pos":
result.position = globalXmlParser.attr(el, "val");
break;
case "degHide":
result.hideDegree = globalXmlParser.boolAttr(el, "val");
break;
case "begChr":
result.beginChar = globalXmlParser.attr(el, "val");
break;
case "endChr":
result.endChar = globalXmlParser.attr(el, "val");
break;
}
}
return result;
}
parseRunProperties(elem, run) {
this.parseDefaultProperties(elem, run.cssStyle = {}, null, (c6) => {
switch (c6.localName) {
case "rStyle":
run.styleName = globalXmlParser.attr(c6, "val");
break;
case "vertAlign":
run.verticalAlign = values.valueOfVertAlign(c6, true);
break;
default:
return false;
}
return true;
});
}
parseVmlPicture(elem) {
const result = { type: DomType.VmlPicture, children: [] };
for (const el of globalXmlParser.elements(elem)) {
const child = parseVmlElement(el, this);
child && result.children.push(child);
}
return result;
}
checkAlternateContent(elem) {
if (elem.localName != "AlternateContent")
return elem;
var choice = globalXmlParser.element(elem, "Choice");
if (choice) {
var requires = globalXmlParser.attr(choice, "Requires");
var namespaceURI = elem.lookupNamespaceURI(requires);
if (supportedNamespaceURIs.includes(namespaceURI))
return choice.firstElementChild;
}
return globalXmlParser.element(elem, "Fallback")?.firstElementChild;
}
parseDrawing(node) {
for (var n7 of globalXmlParser.elements(node)) {
switch (n7.localName) {
case "inline":
case "anchor":
return this.parseDrawingWrapper(n7);
}
}
}
parseDrawingWrapper(node) {
var result = { type: DomType.Drawing, children: [], cssStyle: {} };
var isAnchor = node.localName == "anchor";
let wrapType = null;
let simplePos = globalXmlParser.boolAttr(node, "simplePos");
globalXmlParser.boolAttr(node, "behindDoc");
let posX = { relative: "page", align: "left", offset: "0" };
let posY = { relative: "page", align: "top", offset: "0" };
for (var n7 of globalXmlParser.elements(node)) {
switch (n7.localName) {
case "simplePos":
if (simplePos) {
posX.offset = globalXmlParser.lengthAttr(n7, "x", LengthUsage.Emu);
posY.offset = globalXmlParser.lengthAttr(n7, "y", LengthUsage.Emu);
}
break;
case "extent":
result.cssStyle["width"] = globalXmlParser.lengthAttr(n7, "cx", LengthUsage.Emu);
result.cssStyle["height"] = globalXmlParser.lengthAttr(n7, "cy", LengthUsage.Emu);
break;
case "positionH":
case "positionV":
if (!simplePos) {
let pos = n7.localName == "positionH" ? posX : posY;
var alignNode = globalXmlParser.element(n7, "align");
var offsetNode = globalXmlParser.element(n7, "posOffset");
pos.relative = globalXmlParser.attr(n7, "relativeFrom") ?? pos.relative;
if (alignNode)
pos.align = alignNode.textContent;
if (offsetNode)
pos.offset = convertLength(offsetNode.textContent, LengthUsage.Emu);
}
break;
case "wrapTopAndBottom":
wrapType = "wrapTopAndBottom";
break;
case "wrapNone":
wrapType = "wrapNone";
break;
case "graphic":
var g3 = this.parseGraphic(n7);
if (g3)
result.children.push(g3);
break;
}
}
if (wrapType == "wrapTopAndBottom") {
result.cssStyle["display"] = "block";
if (posX.align) {
result.cssStyle["text-align"] = posX.align;
result.cssStyle["width"] = "100%";
}
} else if (wrapType == "wrapNone") {
result.cssStyle["display"] = "block";
result.cssStyle["position"] = "relative";
result.cssStyle["width"] = "0px";
result.cssStyle["height"] = "0px";
if (posX.offset)
result.cssStyle["left"] = posX.offset;
if (posY.offset)
result.cssStyle["top"] = posY.offset;
} else if (isAnchor && (posX.align == "left" || posX.align == "right")) {
result.cssStyle["float"] = posX.align;
}
return result;
}
parseGraphic(elem) {
var graphicData = globalXmlParser.element(elem, "graphicData");
for (let n7 of globalXmlParser.elements(graphicData)) {
switch (n7.localName) {
case "pic":
return this.parsePicture(n7);
}
}
return null;
}
parsePicture(elem) {
var result = { type: DomType.Image, src: "", cssStyle: {} };
var blipFill = globalXmlParser.element(elem, "blipFill");
var blip = globalXmlParser.element(blipFill, "blip");
var srcRect = globalXmlParser.element(blipFill, "srcRect");
result.src = globalXmlParser.attr(blip, "embed");
if (srcRect) {
result.srcRect = [
globalXmlParser.intAttr(srcRect, "l", 0) / 1e5,
globalXmlParser.intAttr(srcRect, "t", 0) / 1e5,
globalXmlParser.intAttr(srcRect, "r", 0) / 1e5,
globalXmlParser.intAttr(srcRect, "b", 0) / 1e5
];
}
var spPr = globalXmlParser.element(elem, "spPr");
var xfrm = globalXmlParser.element(spPr, "xfrm");
result.cssStyle["position"] = "relative";
if (xfrm) {
result.rotation = globalXmlParser.intAttr(xfrm, "rot", 0) / 6e4;
for (var n7 of globalXmlParser.elements(xfrm)) {
switch (n7.localName) {
case "ext":
result.cssStyle["width"] = globalXmlParser.lengthAttr(n7, "cx", LengthUsage.Emu);
result.cssStyle["height"] = globalXmlParser.lengthAttr(n7, "cy", LengthUsage.Emu);
break;
case "off":
result.cssStyle["left"] = globalXmlParser.lengthAttr(n7, "x", LengthUsage.Emu);
result.cssStyle["top"] = globalXmlParser.lengthAttr(n7, "y", LengthUsage.Emu);
break;
}
}
}
return result;
}
parseTable(node) {
var result = { type: DomType.Table, children: [] };
for (const c6 of globalXmlParser.elements(node)) {
switch (c6.localName) {
case "tr":
result.children.push(this.parseTableRow(c6));
break;
case "tblGrid":
result.columns = this.parseTableColumns(c6);
break;
case "tblPr":
this.parseTableProperties(c6, result);
break;
}
}
return result;
}
parseTableColumns(node) {
var result = [];
for (const n7 of globalXmlParser.elements(node)) {
switch (n7.localName) {
case "gridCol":
result.push({ width: globalXmlParser.lengthAttr(n7, "w") });
break;
}
}
return result;
}
parseTableProperties(elem, table) {
table.cssStyle = {};
table.cellStyle = {};
this.parseDefaultProperties(elem, table.cssStyle, table.cellStyle, (c6) => {
switch (c6.localName) {
case "tblStyle":
table.styleName = globalXmlParser.attr(c6, "val");
break;
case "tblLook":
table.className = values.classNameOftblLook(c6);
break;
case "tblpPr":
this.parseTablePosition(c6, table);
break;
case "tblStyleColBandSize":
table.colBandSize = globalXmlParser.intAttr(c6, "val");
break;
case "tblStyleRowBandSize":
table.rowBandSize = globalXmlParser.intAttr(c6, "val");
break;
case "hidden":
table.cssStyle["display"] = "none";
break;
default:
return false;
}
return true;
});
switch (table.cssStyle["text-align"]) {
case "center":
delete table.cssStyle["text-align"];
table.cssStyle["margin-left"] = "auto";
table.cssStyle["margin-right"] = "auto";
break;
case "right":
delete table.cssStyle["text-align"];
table.cssStyle["margin-left"] = "auto";
break;
}
}
parseTablePosition(node, table) {
var topFromText = globalXmlParser.lengthAttr(node, "topFromText");
var bottomFromText = globalXmlParser.lengthAttr(node, "bottomFromText");
var rightFromText = globalXmlParser.lengthAttr(node, "rightFromText");
var leftFromText = globalXmlParser.lengthAttr(node, "leftFromText");
table.cssStyle["float"] = "left";
table.cssStyle["margin-bottom"] = values.addSize(table.cssStyle["margin-bottom"], bottomFromText);
table.cssStyle["margin-left"] = values.addSize(table.cssStyle["margin-left"], leftFromText);
table.cssStyle["margin-right"] = values.addSize(table.cssStyle["margin-right"], rightFromText);
table.cssStyle["margin-top"] = values.addSize(table.cssStyle["margin-top"], topFromText);
}
parseTableRow(node) {
var result = { type: DomType.Row, children: [] };
for (const c6 of globalXmlParser.elements(node)) {
switch (c6.localName) {
case "tc":
result.children.push(this.parseTableCell(c6));
break;
case "trPr":
case "tblPrEx":
this.parseTableRowProperties(c6, result);
break;
}
}
return result;
}
parseTableRowProperties(elem, row) {
row.cssStyle = this.parseDefaultProperties(elem, {}, null, (c6) => {
switch (c6.localName) {
case "cnfStyle":
row.className = values.classNameOfCnfStyle(c6);
break;
case "tblHeader":
row.isHeader = globalXmlParser.boolAttr(c6, "val");
break;
case "gridBefore":
row.gridBefore = globalXmlParser.intAttr(c6, "val");
break;
case "gridAfter":
row.gridAfter = globalXmlParser.intAttr(c6, "val");
break;
default:
return false;
}
return true;
});
}
parseTableCell(node) {
var result = { type: DomType.Cell, children: [] };
for (const c6 of globalXmlParser.elements(node)) {
switch (c6.localName) {
case "tbl":
result.children.push(this.parseTable(c6));
break;
case "p":
result.children.push(this.parseParagraph(c6));
break;
case "tcPr":
this.parseTableCellProperties(c6, result);
break;
}
}
return result;
}
parseTableCellProperties(elem, cell) {
cell.cssStyle = this.parseDefaultProperties(elem, {}, null, (c6) => {
switch (c6.localName) {
case "gridSpan":
cell.span = globalXmlParser.intAttr(c6, "val", null);
break;
case "vMerge":
cell.verticalMerge = globalXmlParser.attr(c6, "val") ?? "continue";
break;
case "cnfStyle":
cell.className = values.classNameOfCnfStyle(c6);
break;
default:
return false;
}
return true;
});
this.parseTableCellVerticalText(elem, cell);
}
parseTableCellVerticalText(elem, cell) {
const directionMap = {
"btLr": {
writingMode: "vertical-rl",
transform: "rotate(180deg)"
},
"lrTb": {
writingMode: "vertical-lr",
transform: "none"
},
"tbRl": {
writingMode: "vertical-rl",
transform: "none"
}
};
for (const c6 of globalXmlParser.elements(elem)) {
if (c6.localName === "textDirection") {
const direction = globalXmlParser.attr(c6, "val");
const style = directionMap[direction] || { writingMode: "horizontal-tb" };
cell.cssStyle["writing-mode"] = style.writingMode;
cell.cssStyle["transform"] = style.transform;
}
}
}
parseDefaultProperties(elem, style = null, childStyle = null, handler = null) {
style = style || {};
for (const c6 of globalXmlParser.elements(elem)) {
if (handler?.(c6))
continue;
switch (c6.localName) {
case "jc":
style["text-align"] = values.valueOfJc(c6);
break;
case "textAlignment":
style["vertical-align"] = values.valueOfTextAlignment(c6);
break;
case "color":
style["color"] = xmlUtil.colorAttr(c6, "val", null, autos.color);
break;
case "sz":
style["font-size"] = style["min-height"] = globalXmlParser.lengthAttr(c6, "val", LengthUsage.FontSize);
break;
case "shd":
style["background-color"] = xmlUtil.colorAttr(c6, "fill", null, autos.shd);
break;
case "highlight":
style["background-color"] = xmlUtil.colorAttr(c6, "val", null, autos.highlight);
break;
case "vertAlign":
break;
case "position":
style.verticalAlign = globalXmlParser.lengthAttr(c6, "val", LengthUsage.FontSize);
break;
case "tcW":
if (this.options.ignoreWidth)
break;
case "tblW":
style["width"] = values.valueOfSize(c6, "w");
break;
case "trHeight":
this.parseTrHeight(c6, style);
break;
case "strike":
style["text-decoration"] = globalXmlParser.boolAttr(c6, "val", true) ? "line-through" : "none";
break;
case "b":
style["font-weight"] = globalXmlParser.boolAttr(c6, "val", true) ? "bold" : "normal";
break;
case "i":
style["font-style"] = globalXmlParser.boolAttr(c6, "val", true) ? "italic" : "normal";
break;
case "caps":
style["text-transform"] = globalXmlParser.boolAttr(c6, "val", true) ? "uppercase" : "none";
break;
case "smallCaps":
style["font-variant"] = globalXmlParser.boolAttr(c6, "val", true) ? "small-caps" : "none";
break;
case "u":
this.parseUnderline(c6, style);
break;
case "ind":
case "tblInd":
this.parseIndentation(c6, style);
break;
case "rFonts":
this.parseFont(c6, style);
break;
case "tblBorders":
this.parseBorderProperties(c6, childStyle || style);
break;
case "tblCellSpacing":
style["border-spacing"] = values.valueOfMargin(c6);
style["border-collapse"] = "separate";
break;
case "pBdr":
this.parseBorderProperties(c6, style);
break;
case "bdr":
style["border"] = values.valueOfBorder(c6);
break;
case "tcBorders":
this.parseBorderProperties(c6, style);
break;
case "vanish":
if (globalXmlParser.boolAttr(c6, "val", true))
style["display"] = "none";
break;
case "kern":
break;
case "noWrap":
break;
case "tblCellMar":
case "tcMar":
this.parseMarginProperties(c6, childStyle || style);
break;
case "tblLayout":
style["table-layout"] = values.valueOfTblLayout(c6);
break;
case "vAlign":
style["vertical-align"] = values.valueOfTextAlignment(c6);
break;
case "spacing":
if (elem.localName == "pPr")
this.parseSpacing(c6, style);
break;
case "wordWrap":
if (globalXmlParser.boolAttr(c6, "val"))
style["overflow-wrap"] = "break-word";
break;
case "suppressAutoHyphens":
style["hyphens"] = globalXmlParser.boolAttr(c6, "val", true) ? "none" : "auto";
break;
case "lang":
style["$lang"] = globalXmlParser.attr(c6, "val");
break;
case "rtl":
case "bidi":
if (globalXmlParser.boolAttr(c6, "val", true))
style["direction"] = "rtl";
break;
case "bCs":
case "iCs":
case "szCs":
case "tabs":
case "outlineLvl":
case "contextualSpacing":
case "tblStyleColBandSize":
case "tblStyleRowBandSize":
case "webHidden":
case "pageBreakBefore":
case "suppressLineNumbers":
case "keepLines":
case "keepNext":
case "widowControl":
case "bidi":
case "rtl":
case "noProof":
break;
default:
if (this.options.debug)
console.warn(`DOCX: Unknown document element: ${elem.localName}.${c6.localName}`);
break;
}
}
return style;
}
parseUnderline(node, style) {
var val2 = globalXmlParser.attr(node, "val");
if (val2 == null)
return;
switch (val2) {
case "dash":
case "dashDotDotHeavy":
case "dashDotHeavy":
case "dashedHeavy":
case "dashLong":
case "dashLongHeavy":
case "dotDash":
case "dotDotDash":
style["text-decoration"] = "underline dashed";
break;
case "dotted":
case "dottedHeavy":
style["text-decoration"] = "underline dotted";
break;
case "double":
style["text-decoration"] = "underline double";
break;
case "single":
case "thick":
style["text-decoration"] = "underline";
break;
case "wave":
case "wavyDouble":
case "wavyHeavy":
style["text-decoration"] = "underline wavy";
break;
case "words":
style["text-decoration"] = "underline";
break;
case "none":
style["text-decoration"] = "none";
break;
}
var col = xmlUtil.colorAttr(node, "color");
if (col)
style["text-decoration-color"] = col;
}
parseFont(node, style) {
var ascii = globalXmlParser.attr(node, "ascii");
var asciiTheme = values.themeValue(node, "asciiTheme");
var eastAsia = globalXmlParser.attr(node, "eastAsia");
var fonts = [ascii, asciiTheme, eastAsia].filter((x2) => x2).map((x2) => encloseFontFamily(x2));
if (fonts.length > 0)
style["font-family"] = [...new Set(fonts)].join(", ");
}
parseIndentation(node, style) {
var firstLine = globalXmlParser.lengthAttr(node, "firstLine");
var hanging = globalXmlParser.lengthAttr(node, "hanging");
var left = globalXmlParser.lengthAttr(node, "left");
var start = globalXmlParser.lengthAttr(node, "start");
var right = globalXmlParser.lengthAttr(node, "right");
var end = globalXmlParser.lengthAttr(node, "end");
if (firstLine)
style["text-indent"] = firstLine;
if (hanging)
style["text-indent"] = `-${hanging}`;
if (left || start)
style["margin-inline-start"] = left || start;
if (right || end)
style["margin-inline-end"] = right || end;
}
parseSpacing(node, style) {
var before = globalXmlParser.lengthAttr(node, "before");
var after = globalXmlParser.lengthAttr(node, "after");
var line = globalXmlParser.intAttr(node, "line", null);
var lineRule = globalXmlParser.attr(node, "lineRule");
if (before)
style["margin-top"] = before;
if (after)
style["margin-bottom"] = after;
if (line !== null) {
switch (lineRule) {
case "auto":
style["line-height"] = `${(line / 240).toFixed(2)}`;
break;
case "atLeast":
style["line-height"] = `calc(100% + ${line / 20}pt)`;
break;
default:
style["line-height"] = style["min-height"] = `${line / 20}pt`;
break;
}
}
}
parseMarginProperties(node, output) {
for (const c6 of globalXmlParser.elements(node)) {
switch (c6.localName) {
case "left":
output["padding-left"] = values.valueOfMargin(c6);
break;
case "right":
output["padding-right"] = values.valueOfMargin(c6);
break;
case "top":
output["padding-top"] = values.valueOfMargin(c6);
break;
case "bottom":
output["padding-bottom"] = values.valueOfMargin(c6);
break;
}
}
}
parseTrHeight(node, output) {
switch (globalXmlParser.attr(node, "hRule")) {
case "exact":
output["height"] = globalXmlParser.lengthAttr(node, "val");
break;
case "atLeast":
default:
output["height"] = globalXmlParser.lengthAttr(node, "val");
break;
}
}
parseBorderProperties(node, output) {
for (const c6 of globalXmlParser.elements(node)) {
switch (c6.localName) {
case "start":
case "left":
output["border-left"] = values.valueOfBorder(c6);
break;
case "end":
case "right":
output["border-right"] = values.valueOfBorder(c6);
break;
case "top":
output["border-top"] = values.valueOfBorder(c6);
break;
case "bottom":
output["border-bottom"] = values.valueOfBorder(c6);
break;
}
}
}
};
knownColors = ["black", "blue", "cyan", "darkBlue", "darkCyan", "darkGray", "darkGreen", "darkMagenta", "darkRed", "darkYellow", "green", "lightGray", "magenta", "none", "red", "white", "yellow"];
xmlUtil = class {
static colorAttr(node, attrName, defValue = null, autoColor = "black") {
var v4 = globalXmlParser.attr(node, attrName);
if (v4) {
if (v4 == "auto") {
return autoColor;
} else if (knownColors.includes(v4)) {
return v4;
}
return `#${v4}`;
}
var themeColor = globalXmlParser.attr(node, "themeColor");
return themeColor ? `var(--docx-${themeColor}-color)` : defValue;
}
};
values = class _values {
static themeValue(c6, attr) {
var val2 = globalXmlParser.attr(c6, attr);
return val2 ? `var(--docx-${val2}-font)` : null;
}
static valueOfSize(c6, attr) {
var type = LengthUsage.Dxa;
switch (globalXmlParser.attr(c6, "type")) {
case "dxa":
break;
case "pct":
type = LengthUsage.Percent;
break;
case "auto":
return "auto";
}
return globalXmlParser.lengthAttr(c6, attr, type);
}
static valueOfMargin(c6) {
return globalXmlParser.lengthAttr(c6, "w");
}
static valueOfBorder(c6) {
var type = _values.parseBorderType(globalXmlParser.attr(c6, "val"));
if (type == "none")
return "none";
var color2 = xmlUtil.colorAttr(c6, "color");
var size = globalXmlParser.lengthAttr(c6, "sz", LengthUsage.Border);
return `${size} ${type} ${color2 == "auto" ? autos.borderColor : color2}`;
}
static parseBorderType(type) {
switch (type) {
case "single":
return "solid";
case "dashDotStroked":
return "solid";
case "dashed":
return "dashed";
case "dashSmallGap":
return "dashed";
case "dotDash":
return "dotted";
case "dotDotDash":
return "dotted";
case "dotted":
return "dotted";
case "double":
return "double";
case "doubleWave":
return "double";
case "inset":
return "inset";
case "nil":
return "none";
case "none":
return "none";
case "outset":
return "outset";
case "thick":
return "solid";
case "thickThinLargeGap":
return "solid";
case "thickThinMediumGap":
return "solid";
case "thickThinSmallGap":
return "solid";
case "thinThickLargeGap":
return "solid";
case "thinThickMediumGap":
return "solid";
case "thinThickSmallGap":
return "solid";
case "thinThickThinLargeGap":
return "solid";
case "thinThickThinMediumGap":
return "solid";
case "thinThickThinSmallGap":
return "solid";
case "threeDEmboss":
return "solid";
case "threeDEngrave":
return "solid";
case "triple":
return "double";
case "wave":
return "solid";
}
return "solid";
}
static valueOfTblLayout(c6) {
var type = globalXmlParser.attr(c6, "val");
return type == "fixed" ? "fixed" : "auto";
}
static classNameOfCnfStyle(c6) {
const val2 = globalXmlParser.attr(c6, "val");
const classes = [
"first-row",
"last-row",
"first-col",
"last-col",
"odd-col",
"even-col",
"odd-row",
"even-row",
"ne-cell",
"nw-cell",
"se-cell",
"sw-cell"
];
return classes.filter((_3, i7) => val2[i7] == "1").join(" ");
}
static valueOfJc(c6) {
var type = globalXmlParser.attr(c6, "val");
switch (type) {
case "start":
case "left":
return "left";
case "center":
return "center";
case "end":
case "right":
return "right";
case "both":
return "justify";
}
return type;
}
static valueOfVertAlign(c6, asTagName = false) {
var type = globalXmlParser.attr(c6, "val");
switch (type) {
case "subscript":
return "sub";
case "superscript":
return asTagName ? "sup" : "super";
}
return asTagName ? null : type;
}
static valueOfTextAlignment(c6) {
var type = globalXmlParser.attr(c6, "val");
switch (type) {
case "auto":
case "baseline":
return "baseline";
case "top":
return "top";
case "center":
return "middle";
case "bottom":
return "bottom";
}
return type;
}
static addSize(a3, b4) {
if (a3 == null)
return b4;
if (b4 == null)
return a3;
return `calc(${a3} + ${b4})`;
}
static classNameOftblLook(c6) {
const val2 = globalXmlParser.hexAttr(c6, "val", 0);
let className = "";
if (globalXmlParser.boolAttr(c6, "firstRow") || val2 & 32)
className += " first-row";
if (globalXmlParser.boolAttr(c6, "lastRow") || val2 & 64)
className += " last-row";
if (globalXmlParser.boolAttr(c6, "firstColumn") || val2 & 128)
className += " first-col";
if (globalXmlParser.boolAttr(c6, "lastColumn") || val2 & 256)
className += " last-col";
if (globalXmlParser.boolAttr(c6, "noHBand") || val2 & 512)
className += " no-hband";
if (globalXmlParser.boolAttr(c6, "noVBand") || val2 & 1024)
className += " no-vband";
return className.trim();
}
};
defaultTab = { pos: 0, leader: "none", style: "left" };
maxTabs = 50;
ns = {
svg: "http://www.w3.org/2000/svg",
mathML: "http://www.w3.org/1998/Math/MathML"
};
HtmlRenderer = class {
constructor(htmlDocument) {
this.htmlDocument = htmlDocument;
this.className = "docx";
this.styleMap = {};
this.currentPart = null;
this.tableVerticalMerges = [];
this.currentVerticalMerge = null;
this.tableCellPositions = [];
this.currentCellPosition = null;
this.footnoteMap = {};
this.endnoteMap = {};
this.currentEndnoteIds = [];
this.usedHederFooterParts = [];
this.currentTabs = [];
this.commentMap = {};
this.tasks = [];
this.postRenderTasks = [];
}
async render(document2, bodyContainer, styleContainer = null, options) {
this.document = document2;
this.options = options;
this.className = options.className;
this.rootSelector = options.inWrapper ? `.${this.className}-wrapper` : ":root";
this.styleMap = null;
this.tasks = [];
if (this.options.renderComments && globalThis.Highlight) {
this.commentHighlight = new Highlight();
}
styleContainer = styleContainer || bodyContainer;
removeAllElements(styleContainer);
removeAllElements(bodyContainer);
styleContainer.appendChild(this.createComment("docxjs library predefined styles"));
styleContainer.appendChild(this.renderDefaultStyle());
if (document2.themePart) {
styleContainer.appendChild(this.createComment("docxjs document theme values"));
this.renderTheme(document2.themePart, styleContainer);
}
if (document2.stylesPart != null) {
this.styleMap = this.processStyles(document2.stylesPart.styles);
styleContainer.appendChild(this.createComment("docxjs document styles"));
styleContainer.appendChild(this.renderStyles(document2.stylesPart.styles));
}
if (document2.numberingPart) {
this.prodessNumberings(document2.numberingPart.domNumberings);
styleContainer.appendChild(this.createComment("docxjs document numbering styles"));
styleContainer.appendChild(this.renderNumbering(document2.numberingPart.domNumberings, styleContainer));
}
if (document2.footnotesPart) {
this.footnoteMap = keyBy(document2.footnotesPart.notes, (x2) => x2.id);
}
if (document2.endnotesPart) {
this.endnoteMap = keyBy(document2.endnotesPart.notes, (x2) => x2.id);
}
if (document2.settingsPart) {
this.defaultTabSize = document2.settingsPart.settings?.defaultTabStop;
}
if (!options.ignoreFonts && document2.fontTablePart)
this.renderFontTable(document2.fontTablePart, styleContainer);
var sectionElements = this.renderSections(document2.documentPart.body);
if (this.options.inWrapper) {
bodyContainer.appendChild(this.renderWrapper(sectionElements));
} else {
appendChildren(bodyContainer, sectionElements);
}
if (this.commentHighlight && options.renderComments) {
CSS.highlights.set(`${this.className}-comments`, this.commentHighlight);
}
this.postRenderTasks.forEach((t6) => t6());
await Promise.allSettled(this.tasks);
this.refreshTabStops();
}
renderTheme(themePart, styleContainer) {
const variables = {};
const fontScheme = themePart.theme?.fontScheme;
if (fontScheme) {
if (fontScheme.majorFont) {
variables["--docx-majorHAnsi-font"] = fontScheme.majorFont.latinTypeface;
}
if (fontScheme.minorFont) {
variables["--docx-minorHAnsi-font"] = fontScheme.minorFont.latinTypeface;
}
}
const colorScheme = themePart.theme?.colorScheme;
if (colorScheme) {
for (let [k2, v4] of Object.entries(colorScheme.colors)) {
variables[`--docx-${k2}-color`] = `#${v4}`;
}
}
const cssText = this.styleToString(`.${this.className}`, variables);
styleContainer.appendChild(this.createStyleElement(cssText));
}
renderFontTable(fontsPart, styleContainer) {
for (let f4 of fontsPart.fonts) {
for (let ref of f4.embedFontRefs) {
this.tasks.push(this.document.loadFont(ref.id, ref.key).then((fontData) => {
const cssValues = {
"font-family": encloseFontFamily(f4.name),
"src": `url(${fontData})`
};
if (ref.type == "bold" || ref.type == "boldItalic") {
cssValues["font-weight"] = "bold";
}
if (ref.type == "italic" || ref.type == "boldItalic") {
cssValues["font-style"] = "italic";
}
const cssText = this.styleToString("@font-face", cssValues);
styleContainer.appendChild(this.createComment(`docxjs ${f4.name} font`));
styleContainer.appendChild(this.createStyleElement(cssText));
}));
}
}
}
processStyleName(className) {
return className ? `${this.className}_${escapeClassName(className)}` : this.className;
}
processStyles(styles2) {
const stylesMap = keyBy(styles2.filter((x2) => x2.id != null), (x2) => x2.id);
for (const style of styles2.filter((x2) => x2.basedOn)) {
var baseStyle = stylesMap[style.basedOn];
if (baseStyle) {
style.paragraphProps = mergeDeep(style.paragraphProps, baseStyle.paragraphProps);
style.runProps = mergeDeep(style.runProps, baseStyle.runProps);
for (const baseValues of baseStyle.styles) {
const styleValues = style.styles.find((x2) => x2.target == baseValues.target);
if (styleValues) {
this.copyStyleProperties(baseValues.values, styleValues.values);
} else {
style.styles.push({ ...baseValues, values: { ...baseValues.values } });
}
}
} else if (this.options.debug)
console.warn(`Can't find base style ${style.basedOn}`);
}
for (let style of styles2) {
style.cssName = this.processStyleName(style.id);
}
return stylesMap;
}
prodessNumberings(numberings) {
for (let num of numberings.filter((n7) => n7.pStyleName)) {
const style = this.findStyle(num.pStyleName);
if (style?.paragraphProps?.numbering) {
style.paragraphProps.numbering.level = num.level;
}
}
}
processElement(element) {
if (element.children) {
for (var e9 of element.children) {
e9.parent = element;
if (e9.type == DomType.Table) {
this.processTable(e9);
} else {
this.processElement(e9);
}
}
}
}
processTable(table) {
for (var r8 of table.children) {
for (var c6 of r8.children) {
c6.cssStyle = this.copyStyleProperties(table.cellStyle, c6.cssStyle, [
"border-left",
"border-right",
"border-top",
"border-bottom",
"padding-left",
"padding-right",
"padding-top",
"padding-bottom"
]);
this.processElement(c6);
}
}
}
copyStyleProperties(input, output, attrs = null) {
if (!input)
return output;
if (output == null)
output = {};
if (attrs == null)
attrs = Object.getOwnPropertyNames(input);
for (var key of attrs) {
if (input.hasOwnProperty(key) && !output.hasOwnProperty(key))
output[key] = input[key];
}
return output;
}
createPageElement(className, props) {
var elem = this.createElement("section", { className });
if (props) {
if (props.pageMargins) {
elem.style.paddingLeft = props.pageMargins.left;
elem.style.paddingRight = props.pageMargins.right;
elem.style.paddingTop = props.pageMargins.top;
elem.style.paddingBottom = props.pageMargins.bottom;
}
if (props.pageSize) {
if (!this.options.ignoreWidth)
elem.style.width = props.pageSize.width;
if (!this.options.ignoreHeight)
elem.style.minHeight = props.pageSize.height;
}
}
return elem;
}
createSectionContent(props) {
var elem = this.createElement("article");
if (props.columns && props.columns.numberOfColumns) {
elem.style.columnCount = `${props.columns.numberOfColumns}`;
elem.style.columnGap = props.columns.space;
if (props.columns.separator) {
elem.style.columnRule = "1px solid black";
}
}
return elem;
}
renderSections(document2) {
const result = [];
this.processElement(document2);
const sections = this.splitBySection(document2.children, document2.props);
const pages = this.groupByPageBreaks(sections);
let prevProps = null;
for (let i7 = 0, l5 = pages.length; i7 < l5; i7++) {
this.currentFootnoteIds = [];
const section = pages[i7][0];
let props = section.sectProps;
const pageElement = this.createPageElement(this.className, props);
this.renderStyleValues(document2.cssStyle, pageElement);
this.options.renderHeaders && this.renderHeaderFooter(props.headerRefs, props, result.length, prevProps != props, pageElement);
for (const sect of pages[i7]) {
var contentElement = this.createSectionContent(sect.sectProps);
this.renderElements(sect.elements, contentElement);
pageElement.appendChild(contentElement);
props = sect.sectProps;
}
if (this.options.renderFootnotes) {
this.renderNotes(this.currentFootnoteIds, this.footnoteMap, pageElement);
}
if (this.options.renderEndnotes && i7 == l5 - 1) {
this.renderNotes(this.currentEndnoteIds, this.endnoteMap, pageElement);
}
this.options.renderFooters && this.renderHeaderFooter(props.footerRefs, props, result.length, prevProps != props, pageElement);
result.push(pageElement);
prevProps = props;
}
return result;
}
renderHeaderFooter(refs, props, page, firstOfSection, into) {
if (!refs)
return;
var ref = (props.titlePage && firstOfSection ? refs.find((x2) => x2.type == "first") : null) ?? (page % 2 == 1 ? refs.find((x2) => x2.type == "even") : null) ?? refs.find((x2) => x2.type == "default");
var part = ref && this.document.findPartByRelId(ref.id, this.document.documentPart);
if (part) {
this.currentPart = part;
if (!this.usedHederFooterParts.includes(part.path)) {
this.processElement(part.rootElement);
this.usedHederFooterParts.push(part.path);
}
const [el] = this.renderElements([part.rootElement], into);
if (props?.pageMargins) {
if (part.rootElement.type === DomType.Header) {
el.style.marginTop = `calc(${props.pageMargins.header} - ${props.pageMargins.top})`;
el.style.minHeight = `calc(${props.pageMargins.top} - ${props.pageMargins.header})`;
} else if (part.rootElement.type === DomType.Footer) {
el.style.marginBottom = `calc(${props.pageMargins.footer} - ${props.pageMargins.bottom})`;
el.style.minHeight = `calc(${props.pageMargins.bottom} - ${props.pageMargins.footer})`;
}
}
this.currentPart = null;
}
}
isPageBreakElement(elem) {
if (elem.type != DomType.Break)
return false;
if (elem.break == "lastRenderedPageBreak")
return !this.options.ignoreLastRenderedPageBreak;
return elem.break == "page";
}
isPageBreakSection(prev, next) {
if (!prev)
return false;
if (!next)
return false;
return prev.pageSize?.orientation != next.pageSize?.orientation || prev.pageSize?.width != next.pageSize?.width || prev.pageSize?.height != next.pageSize?.height;
}
splitBySection(elements2, defaultProps) {
var current2 = { sectProps: null, elements: [], pageBreak: false };
var result = [current2];
for (let elem of elements2) {
if (elem.type == DomType.Paragraph) {
const s6 = this.findStyle(elem.styleName);
if (s6?.paragraphProps?.pageBreakBefore) {
current2.sectProps = sectProps;
current2.pageBreak = true;
current2 = { sectProps: null, elements: [], pageBreak: false };
result.push(current2);
}
}
current2.elements.push(elem);
if (elem.type == DomType.Paragraph) {
const p4 = elem;
var sectProps = p4.sectionProps;
var pBreakIndex = -1;
var rBreakIndex = -1;
if (this.options.breakPages && p4.children) {
pBreakIndex = p4.children.findIndex((r8) => {
rBreakIndex = r8.children?.findIndex(this.isPageBreakElement.bind(this)) ?? -1;
return rBreakIndex != -1;
});
}
if (sectProps || pBreakIndex != -1) {
current2.sectProps = sectProps;
current2.pageBreak = pBreakIndex != -1;
current2 = { sectProps: null, elements: [], pageBreak: false };
result.push(current2);
}
if (pBreakIndex != -1) {
let breakRun = p4.children[pBreakIndex];
let splitRun = rBreakIndex < breakRun.children.length - 1;
if (pBreakIndex < p4.children.length - 1 || splitRun) {
var children = elem.children;
var newParagraph = { ...elem, children: children.slice(pBreakIndex) };
elem.children = children.slice(0, pBreakIndex);
current2.elements.push(newParagraph);
if (splitRun) {
let runChildren = breakRun.children;
let newRun = { ...breakRun, children: runChildren.slice(0, rBreakIndex) };
elem.children.push(newRun);
breakRun.children = runChildren.slice(rBreakIndex);
}
}
}
}
}
let currentSectProps = null;
for (let i7 = result.length - 1; i7 >= 0; i7--) {
if (result[i7].sectProps == null) {
result[i7].sectProps = currentSectProps ?? defaultProps;
} else {
currentSectProps = result[i7].sectProps;
}
}
return result;
}
groupByPageBreaks(sections) {
let current2 = [];
let prev;
const result = [current2];
for (let s6 of sections) {
current2.push(s6);
if (this.options.ignoreLastRenderedPageBreak || s6.pageBreak || this.isPageBreakSection(prev, s6.sectProps))
result.push(current2 = []);
prev = s6.sectProps;
}
return result.filter((x2) => x2.length > 0);
}
renderWrapper(children) {
return this.createElement("div", { className: `${this.className}-wrapper` }, children);
}
renderDefaultStyle() {
var c6 = this.className;
var wrapperStyle = `
.${c6}-wrapper { background: gray; padding: 30px; padding-bottom: 0px; display: flex; flex-flow: column; align-items: center; }
.${c6}-wrapper>section.${c6} { background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); margin-bottom: 30px; }`;
if (this.options.hideWrapperOnPrint) {
wrapperStyle = `@media not print { ${wrapperStyle} }`;
}
var styleText = `${wrapperStyle}
.${c6} { color: black; hyphens: auto; text-underline-position: from-font; }
section.${c6} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: hidden; }
section.${c6}>article { margin-bottom: auto; z-index: 1; }
section.${c6}>footer { z-index: 1; }
.${c6} table { border-collapse: collapse; }
.${c6} table td, .${c6} table th { vertical-align: top; }
.${c6} p { margin: 0pt; min-height: 1em; }
.${c6} span { white-space: pre-wrap; overflow-wrap: break-word; }
.${c6} a { color: inherit; text-decoration: inherit; }
.${c6} svg { fill: transparent; }
`;
if (this.options.renderComments) {
styleText += `
.${c6}-comment-ref { cursor: default; }
.${c6}-comment-popover { display: none; z-index: 1000; padding: 0.5rem; background: white; position: absolute; box-shadow: 0 0 0.25rem rgba(0, 0, 0, 0.25); width: 30ch; }
.${c6}-comment-ref:hover~.${c6}-comment-popover { display: block; }
.${c6}-comment-author,.${c6}-comment-date { font-size: 0.875rem; color: #888; }
`;
}
return this.createStyleElement(styleText);
}
renderNumbering(numberings, styleContainer) {
var styleText = "";
var resetCounters = [];
for (var num of numberings) {
var selector = `p.${this.numberingClass(num.id, num.level)}`;
var listStyleType = "none";
if (num.bullet) {
let valiable = `--${this.className}-${num.bullet.src}`.toLowerCase();
styleText += this.styleToString(`${selector}:before`, {
"content": "' '",
"display": "inline-block",
"background": `var(${valiable})`
}, num.bullet.style);
this.tasks.push(this.document.loadNumberingImage(num.bullet.src).then((data) => {
var text3 = `${this.rootSelector} { ${valiable}: url(${data}) }`;
styleContainer.appendChild(this.createStyleElement(text3));
}));
} else if (num.levelText) {
let counter = this.numberingCounter(num.id, num.level);
const counterReset = counter + " " + (num.start - 1);
if (num.level > 0) {
styleText += this.styleToString(`p.${this.numberingClass(num.id, num.level - 1)}`, {
"counter-set": counterReset
});
}
resetCounters.push(counterReset);
styleText += this.styleToString(`${selector}:before`, {
"content": this.levelTextToContent(num.levelText, num.suff, num.id, this.numFormatToCssValue(num.format)),
"counter-increment": counter,
...num.rStyle
});
} else {
listStyleType = this.numFormatToCssValue(num.format);
}
styleText += this.styleToString(selector, {
"display": "list-item",
"list-style-position": "inside",
"list-style-type": listStyleType,
...num.pStyle
});
}
if (resetCounters.length > 0) {
styleText += this.styleToString(this.rootSelector, {
"counter-reset": resetCounters.join(" ")
});
}
return this.createStyleElement(styleText);
}
renderStyles(styles2) {
var styleText = "";
const stylesMap = this.styleMap;
const defautStyles = keyBy(styles2.filter((s6) => s6.isDefault), (s6) => s6.target);
for (const style of styles2) {
var subStyles = style.styles;
if (style.linked) {
var linkedStyle = style.linked && stylesMap[style.linked];
if (linkedStyle)
subStyles = subStyles.concat(linkedStyle.styles);
else if (this.options.debug)
console.warn(`Can't find linked style ${style.linked}`);
}
for (const subStyle of subStyles) {
var selector = `${style.target ?? ""}.${style.cssName}`;
if (style.target != subStyle.target)
selector += ` ${subStyle.target}`;
if (defautStyles[style.target] == style)
selector = `.${this.className} ${style.target}, ` + selector;
styleText += this.styleToString(selector, subStyle.values);
}
}
return this.createStyleElement(styleText);
}
renderNotes(noteIds, notesMap, into) {
var notes = noteIds.map((id) => notesMap[id]).filter((x2) => x2);
if (notes.length > 0) {
var result = this.createElement("ol", null, this.renderElements(notes));
into.appendChild(result);
}
}
renderElement(elem) {
switch (elem.type) {
case DomType.Paragraph:
return this.renderParagraph(elem);
case DomType.BookmarkStart:
return this.renderBookmarkStart(elem);
case DomType.BookmarkEnd:
return null;
case DomType.Run:
return this.renderRun(elem);
case DomType.Table:
return this.renderTable(elem);
case DomType.Row:
return this.renderTableRow(elem);
case DomType.Cell:
return this.renderTableCell(elem);
case DomType.Hyperlink:
return this.renderHyperlink(elem);
case DomType.SmartTag:
return this.renderSmartTag(elem);
case DomType.Drawing:
return this.renderDrawing(elem);
case DomType.Image:
return this.renderImage(elem);
case DomType.Text:
return this.renderText(elem);
case DomType.Text:
return this.renderText(elem);
case DomType.DeletedText:
return this.renderDeletedText(elem);
case DomType.Tab:
return this.renderTab(elem);
case DomType.Symbol:
return this.renderSymbol(elem);
case DomType.Break:
return this.renderBreak(elem);
case DomType.Footer:
return this.renderContainer(elem, "footer");
case DomType.Header:
return this.renderContainer(elem, "header");
case DomType.Footnote:
case DomType.Endnote:
return this.renderContainer(elem, "li");
case DomType.FootnoteReference:
return this.renderFootnoteReference(elem);
case DomType.EndnoteReference:
return this.renderEndnoteReference(elem);
case DomType.NoBreakHyphen:
return this.createElement("wbr");
case DomType.VmlPicture:
return this.renderVmlPicture(elem);
case DomType.VmlElement:
return this.renderVmlElement(elem);
case DomType.MmlMath:
return this.renderContainerNS(elem, ns.mathML, "math", { xmlns: ns.mathML });
case DomType.MmlMathParagraph:
return this.renderContainer(elem, "span");
case DomType.MmlFraction:
return this.renderContainerNS(elem, ns.mathML, "mfrac");
case DomType.MmlBase:
return this.renderContainerNS(elem, ns.mathML, elem.parent.type == DomType.MmlMatrixRow ? "mtd" : "mrow");
case DomType.MmlNumerator:
case DomType.MmlDenominator:
case DomType.MmlFunction:
case DomType.MmlLimit:
case DomType.MmlBox:
return this.renderContainerNS(elem, ns.mathML, "mrow");
case DomType.MmlGroupChar:
return this.renderMmlGroupChar(elem);
case DomType.MmlLimitLower:
return this.renderContainerNS(elem, ns.mathML, "munder");
case DomType.MmlMatrix:
return this.renderContainerNS(elem, ns.mathML, "mtable");
case DomType.MmlMatrixRow:
return this.renderContainerNS(elem, ns.mathML, "mtr");
case DomType.MmlRadical:
return this.renderMmlRadical(elem);
case DomType.MmlSuperscript:
return this.renderContainerNS(elem, ns.mathML, "msup");
case DomType.MmlSubscript:
return this.renderContainerNS(elem, ns.mathML, "msub");
case DomType.MmlDegree:
case DomType.MmlSuperArgument:
case DomType.MmlSubArgument:
return this.renderContainerNS(elem, ns.mathML, "mn");
case DomType.MmlFunctionName:
return this.renderContainerNS(elem, ns.mathML, "ms");
case DomType.MmlDelimiter:
return this.renderMmlDelimiter(elem);
case DomType.MmlRun:
return this.renderMmlRun(elem);
case DomType.MmlNary:
return this.renderMmlNary(elem);
case DomType.MmlPreSubSuper:
return this.renderMmlPreSubSuper(elem);
case DomType.MmlBar:
return this.renderMmlBar(elem);
case DomType.MmlEquationArray:
return this.renderMllList(elem);
case DomType.Inserted:
return this.renderInserted(elem);
case DomType.Deleted:
return this.renderDeleted(elem);
case DomType.CommentRangeStart:
return this.renderCommentRangeStart(elem);
case DomType.CommentRangeEnd:
return this.renderCommentRangeEnd(elem);
case DomType.CommentReference:
return this.renderCommentReference(elem);
case DomType.AltChunk:
return this.renderAltChunk(elem);
}
return null;
}
renderElements(elems, into) {
if (elems == null)
return null;
var result = elems.flatMap((e9) => this.renderElement(e9)).filter((e9) => e9 != null);
if (into)
appendChildren(into, result);
return result;
}
renderContainer(elem, tagName, props) {
return this.createElement(tagName, props, this.renderElements(elem.children));
}
renderContainerNS(elem, ns2, tagName, props) {
return this.createElementNS(ns2, tagName, props, this.renderElements(elem.children));
}
renderParagraph(elem) {
var result = this.renderContainer(elem, "p");
const style = this.findStyle(elem.styleName);
elem.tabs ?? (elem.tabs = style?.paragraphProps?.tabs);
this.renderClass(elem, result);
this.renderStyleValues(elem.cssStyle, result);
this.renderCommonProperties(result.style, elem);
const numbering = elem.numbering ?? style?.paragraphProps?.numbering;
if (numbering) {
result.classList.add(this.numberingClass(numbering.id, numbering.level));
}
return result;
}
renderRunProperties(style, props) {
this.renderCommonProperties(style, props);
}
renderCommonProperties(style, props) {
if (props == null)
return;
if (props.color) {
style["color"] = props.color;
}
if (props.fontSize) {
style["font-size"] = props.fontSize;
}
}
renderHyperlink(elem) {
var result = this.renderContainer(elem, "a");
this.renderStyleValues(elem.cssStyle, result);
let href = "";
if (elem.id) {
const rel2 = this.document.documentPart.rels.find((it) => it.id == elem.id && it.targetMode === "External");
href = rel2?.target ?? href;
}
if (elem.anchor) {
href += `#${elem.anchor}`;
}
result.href = href;
return result;
}
renderSmartTag(elem) {
return this.renderContainer(elem, "span");
}
renderCommentRangeStart(commentStart) {
if (!this.options.renderComments)
return null;
const rng = new Range();
this.commentHighlight?.add(rng);
const result = this.createComment(`start of comment #${commentStart.id}`);
this.later(() => rng.setStart(result, 0));
this.commentMap[commentStart.id] = rng;
return result;
}
renderCommentRangeEnd(commentEnd) {
if (!this.options.renderComments)
return null;
const rng = this.commentMap[commentEnd.id];
const result = this.createComment(`end of comment #${commentEnd.id}`);
this.later(() => rng?.setEnd(result, 0));
return result;
}
renderCommentReference(commentRef) {
if (!this.options.renderComments)
return null;
var comment = this.document.commentsPart?.commentMap[commentRef.id];
if (!comment)
return null;
const frg = new DocumentFragment();
const commentRefEl = this.createElement("span", { className: `${this.className}-comment-ref` }, ["\u{1F4AC}"]);
const commentsContainerEl = this.createElement("div", { className: `${this.className}-comment-popover` });
this.renderCommentContent(comment, commentsContainerEl);
frg.appendChild(this.createComment(`comment #${comment.id} by ${comment.author} on ${comment.date}`));
frg.appendChild(commentRefEl);
frg.appendChild(commentsContainerEl);
return frg;
}
renderAltChunk(elem) {
if (!this.options.renderAltChunks)
return null;
var result = this.createElement("iframe");
this.tasks.push(this.document.loadAltChunk(elem.id, this.currentPart).then((x2) => {
result.srcdoc = x2;
}));
return result;
}
renderCommentContent(comment, container) {
container.appendChild(this.createElement("div", { className: `${this.className}-comment-author` }, [comment.author]));
container.appendChild(this.createElement("div", { className: `${this.className}-comment-date` }, [new Date(comment.date).toLocaleString()]));
this.renderElements(comment.children, container);
}
renderDrawing(elem) {
var result = this.renderContainer(elem, "div");
result.style.display = "inline-block";
result.style.position = "relative";
result.style.textIndent = "0px";
this.renderStyleValues(elem.cssStyle, result);
return result;
}
renderImage(elem) {
let result = this.createElement("img");
let transform = elem.cssStyle?.transform;
this.renderStyleValues(elem.cssStyle, result);
if (elem.srcRect && elem.srcRect.some((x2) => x2 != 0)) {
var [left, top, right, bottom] = elem.srcRect;
transform = `scale(${1 / (1 - left - right)}, ${1 / (1 - top - bottom)})`;
result.style["clip-path"] = `rect(${(100 * top).toFixed(2)}% ${(100 * (1 - right)).toFixed(2)}% ${(100 * (1 - bottom)).toFixed(2)}% ${(100 * left).toFixed(2)}%)`;
}
if (elem.rotation)
transform = `rotate(${elem.rotation}deg) ${transform ?? ""}`;
result.style.transform = transform?.trim();
if (this.document) {
this.tasks.push(this.document.loadDocumentImage(elem.src, this.currentPart).then((x2) => {
result.src = x2;
}));
}
return result;
}
renderText(elem) {
return this.htmlDocument.createTextNode(elem.text);
}
renderDeletedText(elem) {
return this.options.renderChanges ? this.renderText(elem) : null;
}
renderBreak(elem) {
if (elem.break == "textWrapping") {
return this.createElement("br");
}
return null;
}
renderInserted(elem) {
if (this.options.renderChanges)
return this.renderContainer(elem, "ins");
return this.renderElements(elem.children);
}
renderDeleted(elem) {
if (this.options.renderChanges)
return this.renderContainer(elem, "del");
return null;
}
renderSymbol(elem) {
var span = this.createElement("span");
span.style.fontFamily = elem.font;
span.innerHTML = `${elem.char};`;
return span;
}
renderFootnoteReference(elem) {
var result = this.createElement("sup");
this.currentFootnoteIds.push(elem.id);
result.textContent = `${this.currentFootnoteIds.length}`;
return result;
}
renderEndnoteReference(elem) {
var result = this.createElement("sup");
this.currentEndnoteIds.push(elem.id);
result.textContent = `${this.currentEndnoteIds.length}`;
return result;
}
renderTab(elem) {
var tabSpan = this.createElement("span");
tabSpan.innerHTML = " ";
if (this.options.experimental) {
tabSpan.className = this.tabStopClass();
var stops = findParent(elem, DomType.Paragraph)?.tabs;
this.currentTabs.push({ stops, span: tabSpan });
}
return tabSpan;
}
renderBookmarkStart(elem) {
return this.createElement("span", { id: elem.name });
}
renderRun(elem) {
if (elem.fieldRun)
return null;
const result = this.createElement("span");
if (elem.id)
result.id = elem.id;
this.renderClass(elem, result);
this.renderStyleValues(elem.cssStyle, result);
if (elem.verticalAlign) {
const wrapper = this.createElement(elem.verticalAlign);
this.renderElements(elem.children, wrapper);
result.appendChild(wrapper);
} else {
this.renderElements(elem.children, result);
}
return result;
}
renderTable(elem) {
let result = this.createElement("table");
this.tableCellPositions.push(this.currentCellPosition);
this.tableVerticalMerges.push(this.currentVerticalMerge);
this.currentVerticalMerge = {};
this.currentCellPosition = { col: 0, row: 0 };
if (elem.columns)
result.appendChild(this.renderTableColumns(elem.columns));
this.renderClass(elem, result);
this.renderElements(elem.children, result);
this.renderStyleValues(elem.cssStyle, result);
this.currentVerticalMerge = this.tableVerticalMerges.pop();
this.currentCellPosition = this.tableCellPositions.pop();
return result;
}
renderTableColumns(columns) {
let result = this.createElement("colgroup");
for (let col of columns) {
let colElem = this.createElement("col");
if (col.width)
colElem.style.width = col.width;
result.appendChild(colElem);
}
return result;
}
renderTableRow(elem) {
let result = this.createElement("tr");
this.currentCellPosition.col = 0;
if (elem.gridBefore)
result.appendChild(this.renderTableCellPlaceholder(elem.gridBefore));
this.renderClass(elem, result);
this.renderElements(elem.children, result);
this.renderStyleValues(elem.cssStyle, result);
if (elem.gridAfter)
result.appendChild(this.renderTableCellPlaceholder(elem.gridAfter));
this.currentCellPosition.row++;
return result;
}
renderTableCellPlaceholder(colSpan) {
const result = this.createElement("td", { colSpan });
result.style["border"] = "none";
return result;
}
renderTableCell(elem) {
let result = this.renderContainer(elem, "td");
const key = this.currentCellPosition.col;
if (elem.verticalMerge) {
if (elem.verticalMerge == "restart") {
this.currentVerticalMerge[key] = result;
result.rowSpan = 1;
} else if (this.currentVerticalMerge[key]) {
this.currentVerticalMerge[key].rowSpan += 1;
result.style.display = "none";
}
} else {
this.currentVerticalMerge[key] = null;
}
this.renderClass(elem, result);
this.renderStyleValues(elem.cssStyle, result);
if (elem.span)
result.colSpan = elem.span;
this.currentCellPosition.col += result.colSpan;
return result;
}
renderVmlPicture(elem) {
return this.renderContainer(elem, "div");
}
renderVmlElement(elem) {
var container = this.createSvgElement("svg");
container.setAttribute("style", elem.cssStyleText);
const result = this.renderVmlChildElement(elem);
if (elem.imageHref?.id) {
this.tasks.push(this.document?.loadDocumentImage(elem.imageHref.id, this.currentPart).then((x2) => result.setAttribute("href", x2)));
}
container.appendChild(result);
requestAnimationFrame(() => {
const bb = container.firstElementChild.getBBox();
container.setAttribute("width", `${Math.ceil(bb.x + bb.width)}`);
container.setAttribute("height", `${Math.ceil(bb.y + bb.height)}`);
});
return container;
}
renderVmlChildElement(elem) {
const result = this.createSvgElement(elem.tagName);
Object.entries(elem.attrs).forEach(([k2, v4]) => result.setAttribute(k2, v4));
for (let child of elem.children) {
if (child.type == DomType.VmlElement) {
result.appendChild(this.renderVmlChildElement(child));
} else {
result.appendChild(...asArray(this.renderElement(child)));
}
}
return result;
}
renderMmlRadical(elem) {
const base = elem.children.find((el) => el.type == DomType.MmlBase);
if (elem.props?.hideDegree) {
return this.createElementNS(ns.mathML, "msqrt", null, this.renderElements([base]));
}
const degree = elem.children.find((el) => el.type == DomType.MmlDegree);
return this.createElementNS(ns.mathML, "mroot", null, this.renderElements([base, degree]));
}
renderMmlDelimiter(elem) {
const children = [];
children.push(this.createElementNS(ns.mathML, "mo", null, [elem.props.beginChar ?? "("]));
children.push(...this.renderElements(elem.children));
children.push(this.createElementNS(ns.mathML, "mo", null, [elem.props.endChar ?? ")"]));
return this.createElementNS(ns.mathML, "mrow", null, children);
}
renderMmlNary(elem) {
const children = [];
const grouped = keyBy(elem.children, (x2) => x2.type);
const sup2 = grouped[DomType.MmlSuperArgument];
const sub2 = grouped[DomType.MmlSubArgument];
const supElem = sup2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sup2))) : null;
const subElem = sub2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sub2))) : null;
const charElem = this.createElementNS(ns.mathML, "mo", null, [elem.props?.char ?? "\u222B"]);
if (supElem || subElem) {
children.push(this.createElementNS(ns.mathML, "munderover", null, [charElem, subElem, supElem]));
} else if (supElem) {
children.push(this.createElementNS(ns.mathML, "mover", null, [charElem, supElem]));
} else if (subElem) {
children.push(this.createElementNS(ns.mathML, "munder", null, [charElem, subElem]));
} else {
children.push(charElem);
}
children.push(...this.renderElements(grouped[DomType.MmlBase].children));
return this.createElementNS(ns.mathML, "mrow", null, children);
}
renderMmlPreSubSuper(elem) {
const children = [];
const grouped = keyBy(elem.children, (x2) => x2.type);
const sup2 = grouped[DomType.MmlSuperArgument];
const sub2 = grouped[DomType.MmlSubArgument];
const supElem = sup2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sup2))) : null;
const subElem = sub2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sub2))) : null;
const stubElem = this.createElementNS(ns.mathML, "mo", null);
children.push(this.createElementNS(ns.mathML, "msubsup", null, [stubElem, subElem, supElem]));
children.push(...this.renderElements(grouped[DomType.MmlBase].children));
return this.createElementNS(ns.mathML, "mrow", null, children);
}
renderMmlGroupChar(elem) {
const tagName = elem.props.verticalJustification === "bot" ? "mover" : "munder";
const result = this.renderContainerNS(elem, ns.mathML, tagName);
if (elem.props.char) {
result.appendChild(this.createElementNS(ns.mathML, "mo", null, [elem.props.char]));
}
return result;
}
renderMmlBar(elem) {
const result = this.renderContainerNS(elem, ns.mathML, "mrow");
switch (elem.props.position) {
case "top":
result.style.textDecoration = "overline";
break;
case "bottom":
result.style.textDecoration = "underline";
break;
}
return result;
}
renderMmlRun(elem) {
const result = this.createElementNS(ns.mathML, "ms", null, this.renderElements(elem.children));
this.renderClass(elem, result);
this.renderStyleValues(elem.cssStyle, result);
return result;
}
renderMllList(elem) {
const result = this.createElementNS(ns.mathML, "mtable");
this.renderClass(elem, result);
this.renderStyleValues(elem.cssStyle, result);
for (let child of this.renderElements(elem.children)) {
result.appendChild(this.createElementNS(ns.mathML, "mtr", null, [
this.createElementNS(ns.mathML, "mtd", null, [child])
]));
}
return result;
}
renderStyleValues(style, ouput) {
for (let k2 in style) {
if (k2.startsWith("$")) {
ouput.setAttribute(k2.slice(1), style[k2]);
} else {
ouput.style[k2] = style[k2];
}
}
}
renderClass(input, ouput) {
if (input.className)
ouput.className = input.className;
if (input.styleName)
ouput.classList.add(this.processStyleName(input.styleName));
}
findStyle(styleName) {
return styleName && this.styleMap?.[styleName];
}
numberingClass(id, lvl) {
return `${this.className}-num-${id}-${lvl}`;
}
tabStopClass() {
return `${this.className}-tab-stop`;
}
styleToString(selectors, values2, cssText = null) {
let result = `${selectors} {\r
`;
for (const key in values2) {
if (key.startsWith("$"))
continue;
result += ` ${key}: ${values2[key]};\r
`;
}
if (cssText)
result += cssText;
return result + "}\r\n";
}
numberingCounter(id, lvl) {
return `${this.className}-num-${id}-${lvl}`;
}
levelTextToContent(text3, suff, id, numformat) {
const suffMap = {
"tab": "\\9",
"space": "\\a0"
};
var result = text3.replace(/%\d*/g, (s6) => {
let lvl = parseInt(s6.substring(1), 10) - 1;
return `"counter(${this.numberingCounter(id, lvl)}, ${numformat})"`;
});
return `"${result}${suffMap[suff] ?? ""}"`;
}
numFormatToCssValue(format2) {
var mapping = {
none: "none",
bullet: "disc",
decimal: "decimal",
lowerLetter: "lower-alpha",
upperLetter: "upper-alpha",
lowerRoman: "lower-roman",
upperRoman: "upper-roman",
decimalZero: "decimal-leading-zero",
aiueo: "katakana",
aiueoFullWidth: "katakana",
chineseCounting: "simp-chinese-informal",
chineseCountingThousand: "simp-chinese-informal",
chineseLegalSimplified: "simp-chinese-formal",
chosung: "hangul-consonant",
ideographDigital: "cjk-ideographic",
ideographTraditional: "cjk-heavenly-stem",
ideographLegalTraditional: "trad-chinese-formal",
ideographZodiac: "cjk-earthly-branch",
iroha: "katakana-iroha",
irohaFullWidth: "katakana-iroha",
japaneseCounting: "japanese-informal",
japaneseDigitalTenThousand: "cjk-decimal",
japaneseLegal: "japanese-formal",
thaiNumbers: "thai",
koreanCounting: "korean-hangul-formal",
koreanDigital: "korean-hangul-formal",
koreanDigital2: "korean-hanja-informal",
hebrew1: "hebrew",
hebrew2: "hebrew",
hindiNumbers: "devanagari",
ganada: "hangul",
taiwaneseCounting: "cjk-ideographic",
taiwaneseCountingThousand: "cjk-ideographic",
taiwaneseDigital: "cjk-decimal"
};
return mapping[format2] ?? format2;
}
refreshTabStops() {
if (!this.options.experimental)
return;
setTimeout(() => {
const pixelToPoint = computePixelToPoint();
for (let tab of this.currentTabs) {
updateTabStop(tab.span, tab.stops, this.defaultTabSize, pixelToPoint);
}
}, 500);
}
createElementNS(ns2, tagName, props, children) {
var result = ns2 ? this.htmlDocument.createElementNS(ns2, tagName) : this.htmlDocument.createElement(tagName);
Object.assign(result, props);
children && appendChildren(result, children);
return result;
}
createElement(tagName, props, children) {
return this.createElementNS(void 0, tagName, props, children);
}
createSvgElement(tagName, props, children) {
return this.createElementNS(ns.svg, tagName, props, children);
}
createStyleElement(cssText) {
return this.createElement("style", { innerHTML: cssText });
}
createComment(text3) {
return this.htmlDocument.createComment(text3);
}
later(func) {
this.postRenderTasks.push(func);
}
};
defaultOptions2 = {
ignoreHeight: false,
ignoreWidth: false,
ignoreFonts: false,
breakPages: true,
debug: false,
experimental: false,
className: "docx",
inWrapper: true,
hideWrapperOnPrint: false,
trimXmlDeclaration: true,
ignoreLastRenderedPageBreak: true,
renderHeaders: true,
renderFooters: true,
renderFootnotes: true,
renderEndnotes: true,
useBase64URL: false,
renderChanges: false,
renderComments: false,
renderAltChunks: true
};
}
});
// ../pi-mono/node_modules/pdfjs-dist/build/pdf.mjs
function setVerbosityLevel(level) {
if (Number.isInteger(level)) {
verbosity = level;
}
}
function getVerbosityLevel() {
return verbosity;
}
function info(msg) {
if (verbosity >= VerbosityLevel.INFOS) {
console.info(`Info: ${msg}`);
}
}
function warn(msg) {
if (verbosity >= VerbosityLevel.WARNINGS) {
console.warn(`Warning: ${msg}`);
}
}
function unreachable(msg) {
throw new Error(msg);
}
function assert(cond, msg) {
if (!cond) {
unreachable(msg);
}
}
function _isValidProtocol(url) {
switch (url?.protocol) {
case "http:":
case "https:":
case "ftp:":
case "mailto:":
case "tel:":
return true;
default:
return false;
}
}
function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
if (!url) {
return null;
}
if (options && typeof url === "string") {
if (options.addDefaultProtocol && url.startsWith("www.")) {
const dots = url.match(/\./g);
if (dots?.length >= 2) {
url = `http://${url}`;
}
}
if (options.tryConvertEncoding) {
try {
url = stringToUTF8String(url);
} catch {
}
}
}
const absoluteUrl = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);
return _isValidProtocol(absoluteUrl) ? absoluteUrl : null;
}
function updateUrlHash(url, hash, allowRel = false) {
const res = URL.parse(url);
if (res) {
res.hash = hash;
return res.href;
}
if (allowRel && createValidAbsoluteUrl(url, "http://example.com")) {
return url.split("#", 1)[0] + `${hash ? `#${hash}` : ""}`;
}
return "";
}
function shadow(obj, prop, value, nonSerializable = false) {
Object.defineProperty(obj, prop, {
value,
enumerable: !nonSerializable,
configurable: true,
writable: false
});
return value;
}
function bytesToString(bytes) {
if (typeof bytes !== "object" || bytes?.length === void 0) {
unreachable("Invalid argument for bytesToString");
}
const length = bytes.length;
const MAX_ARGUMENT_COUNT = 8192;
if (length < MAX_ARGUMENT_COUNT) {
return String.fromCharCode.apply(null, bytes);
}
const strBuf = [];
for (let i7 = 0; i7 < length; i7 += MAX_ARGUMENT_COUNT) {
const chunkEnd = Math.min(i7 + MAX_ARGUMENT_COUNT, length);
const chunk = bytes.subarray(i7, chunkEnd);
strBuf.push(String.fromCharCode.apply(null, chunk));
}
return strBuf.join("");
}
function stringToBytes(str2) {
if (typeof str2 !== "string") {
unreachable("Invalid argument for stringToBytes");
}
const length = str2.length;
const bytes = new Uint8Array(length);
for (let i7 = 0; i7 < length; ++i7) {
bytes[i7] = str2.charCodeAt(i7) & 255;
}
return bytes;
}
function string32(value) {
return String.fromCharCode(value >> 24 & 255, value >> 16 & 255, value >> 8 & 255, value & 255);
}
function isLittleEndian() {
const buffer8 = new Uint8Array(4);
buffer8[0] = 1;
const view32 = new Uint32Array(buffer8.buffer, 0, 1);
return view32[0] === 1;
}
function isEvalSupported() {
try {
new Function("");
return true;
} catch {
return false;
}
}
function stringToUTF8String(str2) {
return decodeURIComponent(escape(str2));
}
function normalizeUnicode(str2) {
if (!NormalizeRegex) {
NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;
NormalizationMap = /* @__PURE__ */ new Map([["\uFB05", "\u017Ft"]]);
}
return str2.replaceAll(NormalizeRegex, (_3, p1, p22) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p22));
}
function getUuid() {
if (typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
const buf = new Uint8Array(32);
crypto.getRandomValues(buf);
return bytesToString(buf);
}
function _isValidExplicitDest(validRef, validName, dest) {
if (!Array.isArray(dest) || dest.length < 2) {
return false;
}
const [page, zoom, ...args] = dest;
if (!validRef(page) && !Number.isInteger(page)) {
return false;
}
if (!validName(zoom)) {
return false;
}
const argsLen = args.length;
let allowNull = true;
switch (zoom.name) {
case "XYZ":
if (argsLen < 2 || argsLen > 3) {
return false;
}
break;
case "Fit":
case "FitB":
return argsLen === 0;
case "FitH":
case "FitBH":
case "FitV":
case "FitBV":
if (argsLen > 1) {
return false;
}
break;
case "FitR":
if (argsLen !== 4) {
return false;
}
allowNull = false;
break;
default:
return false;
}
for (const arg of args) {
if (typeof arg === "number" || allowNull && arg === null) {
continue;
}
return false;
}
return true;
}
function MathClamp(v4, min, max) {
return Math.min(Math.max(v4, min), max);
}
function toBase64Util(arr) {
if (Uint8Array.prototype.toBase64) {
return arr.toBase64();
}
return btoa(bytesToString(arr));
}
function fromBase64Util(str2) {
if (Uint8Array.fromBase64) {
return Uint8Array.fromBase64(str2);
}
return stringToBytes(atob(str2));
}
async function fetchData(url, type = "text") {
if (isValidFetchUrl(url, document.baseURI)) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
switch (type) {
case "arraybuffer":
return response.arrayBuffer();
case "blob":
return response.blob();
case "json":
return response.json();
}
return response.text();
}
return new Promise((resolve2, reject) => {
const request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = type;
request.onreadystatechange = () => {
if (request.readyState !== XMLHttpRequest.DONE) {
return;
}
if (request.status === 200 || request.status === 0) {
switch (type) {
case "arraybuffer":
case "blob":
case "json":
resolve2(request.response);
return;
}
resolve2(request.responseText);
return;
}
reject(new Error(request.statusText));
};
request.send(null);
});
}
function isDataScheme(url) {
const ii = url.length;
let i7 = 0;
while (i7 < ii && url[i7].trim() === "") {
i7++;
}
return url.substring(i7, i7 + 5).toLowerCase() === "data:";
}
function isPdfFile(filename) {
return typeof filename === "string" && /\.pdf$/i.test(filename);
}
function getFilenameFromUrl(url) {
[url] = url.split(/[#?]/, 1);
return url.substring(url.lastIndexOf("/") + 1);
}
function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
if (typeof url !== "string") {
return defaultFilename;
}
if (isDataScheme(url)) {
warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
return defaultFilename;
}
const getURL = (urlString) => {
try {
return new URL(urlString);
} catch {
try {
return new URL(decodeURIComponent(urlString));
} catch {
try {
return new URL(urlString, "https://foo.bar");
} catch {
try {
return new URL(decodeURIComponent(urlString), "https://foo.bar");
} catch {
return null;
}
}
}
}
};
const newURL = getURL(url);
if (!newURL) {
return defaultFilename;
}
const decode5 = (name) => {
try {
let decoded = decodeURIComponent(name);
if (decoded.includes("/")) {
decoded = decoded.split("/").at(-1);
if (decoded.test(/^\.pdf$/i)) {
return decoded;
}
return name;
}
return decoded;
} catch {
return name;
}
};
const pdfRegex = /\.pdf$/i;
const filename = newURL.pathname.split("/").at(-1);
if (pdfRegex.test(filename)) {
return decode5(filename);
}
if (newURL.searchParams.size > 0) {
const values2 = Array.from(newURL.searchParams.values()).reverse();
for (const value of values2) {
if (pdfRegex.test(value)) {
return decode5(value);
}
}
const keys2 = Array.from(newURL.searchParams.keys()).reverse();
for (const key of keys2) {
if (pdfRegex.test(key)) {
return decode5(key);
}
}
}
if (newURL.hash) {
const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
const hashFilename = reFilename.exec(newURL.hash);
if (hashFilename) {
return decode5(hashFilename[0]);
}
}
return defaultFilename;
}
function isValidFetchUrl(url, baseUrl) {
const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);
return res?.protocol === "http:" || res?.protocol === "https:";
}
function noContextMenu(e9) {
e9.preventDefault();
}
function stopEvent(e9) {
e9.preventDefault();
e9.stopPropagation();
}
function deprecated(details) {
console.log("Deprecated API usage: " + details);
}
function getXfaPageViewport(xfaPage, {
scale = 1,
rotation = 0
}) {
const {
width,
height
} = xfaPage.attributes.style;
const viewBox = [0, 0, parseInt(width), parseInt(height)];
return new PageViewport({
viewBox,
userUnit: 1,
scale,
rotation
});
}
function getRGB(color2) {
if (color2.startsWith("#")) {
const colorRGB = parseInt(color2.slice(1), 16);
return [(colorRGB & 16711680) >> 16, (colorRGB & 65280) >> 8, colorRGB & 255];
}
if (color2.startsWith("rgb(")) {
return color2.slice(4, -1).split(",").map((x2) => parseInt(x2));
}
if (color2.startsWith("rgba(")) {
return color2.slice(5, -1).split(",").map((x2) => parseInt(x2)).slice(0, 3);
}
warn(`Not a valid color format: "${color2}"`);
return [0, 0, 0];
}
function getColorValues(colors2) {
const span = document.createElement("span");
span.style.visibility = "hidden";
span.style.colorScheme = "only light";
document.body.append(span);
for (const name of colors2.keys()) {
span.style.color = name;
const computedColor = window.getComputedStyle(span).color;
colors2.set(name, getRGB(computedColor));
}
span.remove();
}
function getCurrentTransform(ctx) {
const {
a: a3,
b: b4,
c: c6,
d: d4,
e: e9,
f: f4
} = ctx.getTransform();
return [a3, b4, c6, d4, e9, f4];
}
function getCurrentTransformInverse(ctx) {
const {
a: a3,
b: b4,
c: c6,
d: d4,
e: e9,
f: f4
} = ctx.getTransform().invertSelf();
return [a3, b4, c6, d4, e9, f4];
}
function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
if (viewport instanceof PageViewport) {
const {
pageWidth,
pageHeight
} = viewport.rawDims;
const {
style
} = div;
const useRound = util_FeatureTest.isCSSRoundSupported;
const w3 = `var(--total-scale-factor) * ${pageWidth}px`, h7 = `var(--total-scale-factor) * ${pageHeight}px`;
const widthStr = useRound ? `round(down, ${w3}, var(--scale-round-x))` : `calc(${w3})`, heightStr = useRound ? `round(down, ${h7}, var(--scale-round-y))` : `calc(${h7})`;
if (!mustFlip || viewport.rotation % 180 === 0) {
style.width = widthStr;
style.height = heightStr;
} else {
style.width = heightStr;
style.height = widthStr;
}
}
if (mustRotate) {
div.setAttribute("data-main-rotation", viewport.rotation);
}
}
function applyOpacity(r8, g3, b4, opacity) {
opacity = Math.min(Math.max(opacity ?? 1, 0), 1);
const white = 255 * (1 - opacity);
r8 = Math.round(r8 * opacity + white);
g3 = Math.round(g3 * opacity + white);
b4 = Math.round(b4 * opacity + white);
return [r8, g3, b4];
}
function RGBToHSL(rgb, output) {
const r8 = rgb[0] / 255;
const g3 = rgb[1] / 255;
const b4 = rgb[2] / 255;
const max = Math.max(r8, g3, b4);
const min = Math.min(r8, g3, b4);
const l5 = (max + min) / 2;
if (max === min) {
output[0] = output[1] = 0;
} else {
const d4 = max - min;
output[1] = l5 < 0.5 ? d4 / (max + min) : d4 / (2 - max - min);
switch (max) {
case r8:
output[0] = ((g3 - b4) / d4 + (g3 < b4 ? 6 : 0)) * 60;
break;
case g3:
output[0] = ((b4 - r8) / d4 + 2) * 60;
break;
case b4:
output[0] = ((r8 - g3) / d4 + 4) * 60;
break;
}
}
output[2] = l5;
}
function HSLToRGB(hsl, output) {
const h7 = hsl[0];
const s6 = hsl[1];
const l5 = hsl[2];
const c6 = (1 - Math.abs(2 * l5 - 1)) * s6;
const x2 = c6 * (1 - Math.abs(h7 / 60 % 2 - 1));
const m4 = l5 - c6 / 2;
switch (Math.floor(h7 / 60)) {
case 0:
output[0] = c6 + m4;
output[1] = x2 + m4;
output[2] = m4;
break;
case 1:
output[0] = x2 + m4;
output[1] = c6 + m4;
output[2] = m4;
break;
case 2:
output[0] = m4;
output[1] = c6 + m4;
output[2] = x2 + m4;
break;
case 3:
output[0] = m4;
output[1] = x2 + m4;
output[2] = c6 + m4;
break;
case 4:
output[0] = x2 + m4;
output[1] = m4;
output[2] = c6 + m4;
break;
case 5:
case 6:
output[0] = c6 + m4;
output[1] = m4;
output[2] = x2 + m4;
break;
}
}
function computeLuminance(x2) {
return x2 <= 0.03928 ? x2 / 12.92 : ((x2 + 0.055) / 1.055) ** 2.4;
}
function contrastRatio(hsl1, hsl2, output) {
HSLToRGB(hsl1, output);
output.map(computeLuminance);
const lum1 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2];
HSLToRGB(hsl2, output);
output.map(computeLuminance);
const lum2 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2];
return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);
}
function findContrastColor(baseColor, fixedColor) {
const key = baseColor[0] + baseColor[1] * 256 + baseColor[2] * 65536 + fixedColor[0] * 16777216 + fixedColor[1] * 4294967296 + fixedColor[2] * 1099511627776;
let cachedValue = contrastCache.get(key);
if (cachedValue) {
return cachedValue;
}
const array = new Float32Array(9);
const output = array.subarray(0, 3);
const baseHSL = array.subarray(3, 6);
RGBToHSL(baseColor, baseHSL);
const fixedHSL = array.subarray(6, 9);
RGBToHSL(fixedColor, fixedHSL);
const isFixedColorDark = fixedHSL[2] < 0.5;
const minContrast = isFixedColorDark ? 12 : 4.5;
baseHSL[2] = isFixedColorDark ? Math.sqrt(baseHSL[2]) : 1 - Math.sqrt(1 - baseHSL[2]);
if (contrastRatio(baseHSL, fixedHSL, output) < minContrast) {
let start, end;
if (isFixedColorDark) {
start = baseHSL[2];
end = 1;
} else {
start = 0;
end = baseHSL[2];
}
const PRECISION = 5e-3;
while (end - start > PRECISION) {
const mid = baseHSL[2] = (start + end) / 2;
if (isFixedColorDark === contrastRatio(baseHSL, fixedHSL, output) < minContrast) {
start = mid;
} else {
end = mid;
}
}
baseHSL[2] = isFixedColorDark ? end : start;
}
HSLToRGB(baseHSL, output);
cachedValue = Util.makeHexColor(Math.round(output[0] * 255), Math.round(output[1] * 255), Math.round(output[2] * 255));
contrastCache.set(key, cachedValue);
return cachedValue;
}
function renderRichText({
html,
dir,
className
}, container) {
const fragment2 = document.createDocumentFragment();
if (typeof html === "string") {
const p4 = document.createElement("p");
p4.dir = dir || "auto";
const lines = html.split(/(?:\r\n?|\n)/);
for (let i7 = 0, ii = lines.length; i7 < ii; ++i7) {
const line = lines[i7];
p4.append(document.createTextNode(line));
if (i7 < ii - 1) {
p4.append(document.createElement("br"));
}
}
fragment2.append(p4);
} else {
XfaLayer.render({
xfaHtml: html,
div: fragment2,
intent: "richText"
});
}
fragment2.firstChild.classList.add("richText", className);
container.append(fragment2);
}
function makePathFromDrawOPS(data) {
const path6 = new Path2D();
if (!data) {
return path6;
}
for (let i7 = 0, ii = data.length; i7 < ii; ) {
switch (data[i7++]) {
case DrawOPS.moveTo:
path6.moveTo(data[i7++], data[i7++]);
break;
case DrawOPS.lineTo:
path6.lineTo(data[i7++], data[i7++]);
break;
case DrawOPS.curveTo:
path6.bezierCurveTo(data[i7++], data[i7++], data[i7++], data[i7++], data[i7++], data[i7++]);
break;
case DrawOPS.quadraticCurveTo:
path6.quadraticCurveTo(data[i7++], data[i7++], data[i7++], data[i7++]);
break;
case DrawOPS.closePath:
path6.closePath();
break;
default:
warn(`Unrecognized drawing path operator: ${data[i7 - 1]}`);
break;
}
}
return path6;
}
function bindEvents(obj, element, names2) {
for (const name of names2) {
element.addEventListener(name, obj[name].bind(obj));
}
}
function getUrlProp(val2) {
if (val2 instanceof URL) {
return val2.href;
}
if (typeof val2 === "string") {
if (isNodeJS) {
return val2;
}
const url = URL.parse(val2, window.location);
if (url) {
return url.href;
}
}
throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.");
}
function getDataProp(val2) {
if (isNodeJS && typeof Buffer !== "undefined" && val2 instanceof Buffer) {
throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");
}
if (val2 instanceof Uint8Array && val2.byteLength === val2.buffer.byteLength) {
return val2;
}
if (typeof val2 === "string") {
return stringToBytes(val2);
}
if (val2 instanceof ArrayBuffer || ArrayBuffer.isView(val2) || typeof val2 === "object" && !isNaN(val2?.length)) {
return new Uint8Array(val2);
}
throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.");
}
function getFactoryUrlProp(val2) {
if (typeof val2 !== "string") {
return null;
}
if (val2.endsWith("/")) {
return val2;
}
throw new Error(`Invalid factory url: "${val2}" must include trailing slash.`);
}
function onFn() {
}
function wrapReason(ex) {
if (ex instanceof AbortException || ex instanceof InvalidPDFException || ex instanceof PasswordException || ex instanceof ResponseException || ex instanceof UnknownErrorException) {
return ex;
}
if (!(ex instanceof Error || typeof ex === "object" && ex !== null)) {
unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
}
switch (ex.name) {
case "AbortException":
return new AbortException(ex.message);
case "InvalidPDFException":
return new InvalidPDFException(ex.message);
case "PasswordException":
return new PasswordException(ex.message, ex.code);
case "ResponseException":
return new ResponseException(ex.message, ex.status, ex.missing);
case "UnknownErrorException":
return new UnknownErrorException(ex.message, ex.details);
}
return new UnknownErrorException(ex.message, ex.toString());
}
async function node_utils_fetchData(url) {
const fs = process.getBuiltinModule("fs");
const data = await fs.promises.readFile(url);
return new Uint8Array(data);
}
function expandBBox(array, index2, minX, minY, maxX, maxY) {
array[index2 * 4 + 0] = Math.min(array[index2 * 4 + 0], minX);
array[index2 * 4 + 1] = Math.min(array[index2 * 4 + 1], minY);
array[index2 * 4 + 2] = Math.max(array[index2 * 4 + 2], maxX);
array[index2 * 4 + 3] = Math.max(array[index2 * 4 + 3], maxY);
}
function applyBoundingBox(ctx, bbox) {
if (!bbox) {
return;
}
const width = bbox[2] - bbox[0];
const height = bbox[3] - bbox[1];
const region = new Path2D();
region.rect(bbox[0], bbox[1], width, height);
ctx.clip(region);
}
function drawTriangle(data, context, p1, p22, p32, c1, c22, c32) {
const coords = context.coords, colors2 = context.colors;
const bytes = data.data, rowSize = data.width * 4;
let tmp;
if (coords[p1 + 1] > coords[p22 + 1]) {
tmp = p1;
p1 = p22;
p22 = tmp;
tmp = c1;
c1 = c22;
c22 = tmp;
}
if (coords[p22 + 1] > coords[p32 + 1]) {
tmp = p22;
p22 = p32;
p32 = tmp;
tmp = c22;
c22 = c32;
c32 = tmp;
}
if (coords[p1 + 1] > coords[p22 + 1]) {
tmp = p1;
p1 = p22;
p22 = tmp;
tmp = c1;
c1 = c22;
c22 = tmp;
}
const x1 = (coords[p1] + context.offsetX) * context.scaleX;
const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
const x2 = (coords[p22] + context.offsetX) * context.scaleX;
const y22 = (coords[p22 + 1] + context.offsetY) * context.scaleY;
const x3 = (coords[p32] + context.offsetX) * context.scaleX;
const y32 = (coords[p32 + 1] + context.offsetY) * context.scaleY;
if (y1 >= y32) {
return;
}
const c1r = colors2[c1], c1g = colors2[c1 + 1], c1b = colors2[c1 + 2];
const c2r = colors2[c22], c2g = colors2[c22 + 1], c2b = colors2[c22 + 2];
const c3r = colors2[c32], c3g = colors2[c32 + 1], c3b = colors2[c32 + 2];
const minY = Math.round(y1), maxY = Math.round(y32);
let xa, car, cag, cab;
let xb, cbr, cbg, cbb;
for (let y4 = minY; y4 <= maxY; y4++) {
if (y4 < y22) {
const k3 = y4 < y1 ? 0 : (y1 - y4) / (y1 - y22);
xa = x1 - (x1 - x2) * k3;
car = c1r - (c1r - c2r) * k3;
cag = c1g - (c1g - c2g) * k3;
cab = c1b - (c1b - c2b) * k3;
} else {
let k3;
if (y4 > y32) {
k3 = 1;
} else if (y22 === y32) {
k3 = 0;
} else {
k3 = (y22 - y4) / (y22 - y32);
}
xa = x2 - (x2 - x3) * k3;
car = c2r - (c2r - c3r) * k3;
cag = c2g - (c2g - c3g) * k3;
cab = c2b - (c2b - c3b) * k3;
}
let k2;
if (y4 < y1) {
k2 = 0;
} else if (y4 > y32) {
k2 = 1;
} else {
k2 = (y1 - y4) / (y1 - y32);
}
xb = x1 - (x1 - x3) * k2;
cbr = c1r - (c1r - c3r) * k2;
cbg = c1g - (c1g - c3g) * k2;
cbb = c1b - (c1b - c3b) * k2;
const x1_ = Math.round(Math.min(xa, xb));
const x2_ = Math.round(Math.max(xa, xb));
let j3 = rowSize * y4 + x1_ * 4;
for (let x4 = x1_; x4 <= x2_; x4++) {
k2 = (xa - x4) / (xa - xb);
if (k2 < 0) {
k2 = 0;
} else if (k2 > 1) {
k2 = 1;
}
bytes[j3++] = car - (car - cbr) * k2 | 0;
bytes[j3++] = cag - (cag - cbg) * k2 | 0;
bytes[j3++] = cab - (cab - cbb) * k2 | 0;
bytes[j3++] = 255;
}
}
}
function drawFigure(data, figure, context) {
const ps = figure.coords;
const cs = figure.colors;
let i7, ii;
switch (figure.type) {
case MeshFigureType.LATTICE:
const verticesPerRow = figure.verticesPerRow;
const rows = Math.floor(ps.length / verticesPerRow) - 1;
const cols = verticesPerRow - 1;
for (i7 = 0; i7 < rows; i7++) {
let q2 = i7 * verticesPerRow;
for (let j3 = 0; j3 < cols; j3++, q2++) {
drawTriangle(data, context, ps[q2], ps[q2 + 1], ps[q2 + verticesPerRow], cs[q2], cs[q2 + 1], cs[q2 + verticesPerRow]);
drawTriangle(data, context, ps[q2 + verticesPerRow + 1], ps[q2 + 1], ps[q2 + verticesPerRow], cs[q2 + verticesPerRow + 1], cs[q2 + 1], cs[q2 + verticesPerRow]);
}
}
break;
case MeshFigureType.TRIANGLES:
for (i7 = 0, ii = ps.length; i7 < ii; i7 += 3) {
drawTriangle(data, context, ps[i7], ps[i7 + 1], ps[i7 + 2], cs[i7], cs[i7 + 1], cs[i7 + 2]);
}
break;
default:
throw new Error("illegal figure");
}
}
function getShadingPattern(IR) {
switch (IR[0]) {
case "RadialAxial":
return new RadialAxialShadingPattern(IR);
case "Mesh":
return new MeshShadingPattern(IR);
case "Dummy":
return new DummyShadingPattern();
}
throw new Error(`Unknown IR type: ${IR[0]}`);
}
function convertBlackAndWhiteToRGBA({
src,
srcPos = 0,
dest,
width,
height,
nonBlackColor = 4294967295,
inverseDecode = false
}) {
const black = util_FeatureTest.isLittleEndian ? 4278190080 : 255;
const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor];
const widthInSource = width >> 3;
const widthRemainder = width & 7;
const srcLength = src.length;
dest = new Uint32Array(dest.buffer);
let destPos = 0;
for (let i7 = 0; i7 < height; i7++) {
for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
const elem2 = srcPos < srcLength ? src[srcPos] : 255;
dest[destPos++] = elem2 & 128 ? oneMapping : zeroMapping;
dest[destPos++] = elem2 & 64 ? oneMapping : zeroMapping;
dest[destPos++] = elem2 & 32 ? oneMapping : zeroMapping;
dest[destPos++] = elem2 & 16 ? oneMapping : zeroMapping;
dest[destPos++] = elem2 & 8 ? oneMapping : zeroMapping;
dest[destPos++] = elem2 & 4 ? oneMapping : zeroMapping;
dest[destPos++] = elem2 & 2 ? oneMapping : zeroMapping;
dest[destPos++] = elem2 & 1 ? oneMapping : zeroMapping;
}
if (widthRemainder === 0) {
continue;
}
const elem = srcPos < srcLength ? src[srcPos++] : 255;
for (let j3 = 0; j3 < widthRemainder; j3++) {
dest[destPos++] = elem & 1 << 7 - j3 ? oneMapping : zeroMapping;
}
}
return {
srcPos,
destPos
};
}
function mirrorContextOperations(ctx, destCtx) {
if (ctx._removeMirroring) {
throw new Error("Context is already forwarding operations.");
}
ctx.__originalSave = ctx.save;
ctx.__originalRestore = ctx.restore;
ctx.__originalRotate = ctx.rotate;
ctx.__originalScale = ctx.scale;
ctx.__originalTranslate = ctx.translate;
ctx.__originalTransform = ctx.transform;
ctx.__originalSetTransform = ctx.setTransform;
ctx.__originalResetTransform = ctx.resetTransform;
ctx.__originalClip = ctx.clip;
ctx.__originalMoveTo = ctx.moveTo;
ctx.__originalLineTo = ctx.lineTo;
ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
ctx.__originalRect = ctx.rect;
ctx.__originalClosePath = ctx.closePath;
ctx.__originalBeginPath = ctx.beginPath;
ctx._removeMirroring = () => {
ctx.save = ctx.__originalSave;
ctx.restore = ctx.__originalRestore;
ctx.rotate = ctx.__originalRotate;
ctx.scale = ctx.__originalScale;
ctx.translate = ctx.__originalTranslate;
ctx.transform = ctx.__originalTransform;
ctx.setTransform = ctx.__originalSetTransform;
ctx.resetTransform = ctx.__originalResetTransform;
ctx.clip = ctx.__originalClip;
ctx.moveTo = ctx.__originalMoveTo;
ctx.lineTo = ctx.__originalLineTo;
ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
ctx.rect = ctx.__originalRect;
ctx.closePath = ctx.__originalClosePath;
ctx.beginPath = ctx.__originalBeginPath;
delete ctx._removeMirroring;
};
ctx.save = function() {
destCtx.save();
this.__originalSave();
};
ctx.restore = function() {
destCtx.restore();
this.__originalRestore();
};
ctx.translate = function(x2, y4) {
destCtx.translate(x2, y4);
this.__originalTranslate(x2, y4);
};
ctx.scale = function(x2, y4) {
destCtx.scale(x2, y4);
this.__originalScale(x2, y4);
};
ctx.transform = function(a3, b4, c6, d4, e9, f4) {
destCtx.transform(a3, b4, c6, d4, e9, f4);
this.__originalTransform(a3, b4, c6, d4, e9, f4);
};
ctx.setTransform = function(a3, b4, c6, d4, e9, f4) {
destCtx.setTransform(a3, b4, c6, d4, e9, f4);
this.__originalSetTransform(a3, b4, c6, d4, e9, f4);
};
ctx.resetTransform = function() {
destCtx.resetTransform();
this.__originalResetTransform();
};
ctx.rotate = function(angle) {
destCtx.rotate(angle);
this.__originalRotate(angle);
};
ctx.clip = function(rule) {
destCtx.clip(rule);
this.__originalClip(rule);
};
ctx.moveTo = function(x2, y4) {
destCtx.moveTo(x2, y4);
this.__originalMoveTo(x2, y4);
};
ctx.lineTo = function(x2, y4) {
destCtx.lineTo(x2, y4);
this.__originalLineTo(x2, y4);
};
ctx.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x2, y4) {
destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x2, y4);
this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x2, y4);
};
ctx.rect = function(x2, y4, width, height) {
destCtx.rect(x2, y4, width, height);
this.__originalRect(x2, y4, width, height);
};
ctx.closePath = function() {
destCtx.closePath();
this.__originalClosePath();
};
ctx.beginPath = function() {
destCtx.beginPath();
this.__originalBeginPath();
};
}
function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
const [a3, b4, c6, d4, tx, ty] = getCurrentTransform(ctx);
if (b4 === 0 && c6 === 0) {
const tlX = destX * a3 + tx;
const rTlX = Math.round(tlX);
const tlY = destY * d4 + ty;
const rTlY = Math.round(tlY);
const brX = (destX + destW) * a3 + tx;
const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
const brY = (destY + destH) * d4 + ty;
const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
ctx.setTransform(Math.sign(a3), 0, 0, Math.sign(d4), rTlX, rTlY);
ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
ctx.setTransform(a3, b4, c6, d4, tx, ty);
return [rWidth, rHeight];
}
if (a3 === 0 && d4 === 0) {
const tlX = destY * c6 + tx;
const rTlX = Math.round(tlX);
const tlY = destX * b4 + ty;
const rTlY = Math.round(tlY);
const brX = (destY + destH) * c6 + tx;
const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
const brY = (destX + destW) * b4 + ty;
const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
ctx.setTransform(0, Math.sign(b4), Math.sign(c6), 0, rTlX, rTlY);
ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
ctx.setTransform(a3, b4, c6, d4, tx, ty);
return [rHeight, rWidth];
}
ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
const scaleX = Math.hypot(a3, b4);
const scaleY = Math.hypot(c6, d4);
return [scaleX * destW, scaleY * destH];
}
function putBinaryImageData(ctx, imgData) {
if (imgData instanceof ImageData) {
ctx.putImageData(imgData, 0, 0);
return;
}
const height = imgData.height, width = imgData.width;
const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
let srcPos = 0, destPos;
const src = imgData.data;
const dest = chunkImgData.data;
let i7, j3, thisChunkHeight, elemsInThisChunk;
if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) {
const srcLength = src.byteLength;
const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
const dest32DataLength = dest32.length;
const fullSrcDiff = width + 7 >> 3;
const white = 4294967295;
const black = util_FeatureTest.isLittleEndian ? 4278190080 : 255;
for (i7 = 0; i7 < totalChunks; i7++) {
thisChunkHeight = i7 < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
destPos = 0;
for (j3 = 0; j3 < thisChunkHeight; j3++) {
const srcDiff = srcLength - srcPos;
let k2 = 0;
const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
const kEndUnrolled = kEnd & ~7;
let mask = 0;
let srcByte = 0;
for (; k2 < kEndUnrolled; k2 += 8) {
srcByte = src[srcPos++];
dest32[destPos++] = srcByte & 128 ? white : black;
dest32[destPos++] = srcByte & 64 ? white : black;
dest32[destPos++] = srcByte & 32 ? white : black;
dest32[destPos++] = srcByte & 16 ? white : black;
dest32[destPos++] = srcByte & 8 ? white : black;
dest32[destPos++] = srcByte & 4 ? white : black;
dest32[destPos++] = srcByte & 2 ? white : black;
dest32[destPos++] = srcByte & 1 ? white : black;
}
for (; k2 < kEnd; k2++) {
if (mask === 0) {
srcByte = src[srcPos++];
mask = 128;
}
dest32[destPos++] = srcByte & mask ? white : black;
mask >>= 1;
}
}
while (destPos < dest32DataLength) {
dest32[destPos++] = 0;
}
ctx.putImageData(chunkImgData, 0, i7 * FULL_CHUNK_HEIGHT);
}
} else if (imgData.kind === util_ImageKind.RGBA_32BPP) {
j3 = 0;
elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
for (i7 = 0; i7 < fullChunks; i7++) {
dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
srcPos += elemsInThisChunk;
ctx.putImageData(chunkImgData, 0, j3);
j3 += FULL_CHUNK_HEIGHT;
}
if (i7 < totalChunks) {
elemsInThisChunk = width * partialChunkHeight * 4;
dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
ctx.putImageData(chunkImgData, 0, j3);
}
} else if (imgData.kind === util_ImageKind.RGB_24BPP) {
thisChunkHeight = FULL_CHUNK_HEIGHT;
elemsInThisChunk = width * thisChunkHeight;
for (i7 = 0; i7 < totalChunks; i7++) {
if (i7 >= fullChunks) {
thisChunkHeight = partialChunkHeight;
elemsInThisChunk = width * thisChunkHeight;
}
destPos = 0;
for (j3 = elemsInThisChunk; j3--; ) {
dest[destPos++] = src[srcPos++];
dest[destPos++] = src[srcPos++];
dest[destPos++] = src[srcPos++];
dest[destPos++] = 255;
}
ctx.putImageData(chunkImgData, 0, i7 * FULL_CHUNK_HEIGHT);
}
} else {
throw new Error(`bad image kind: ${imgData.kind}`);
}
}
function putBinaryImageMask(ctx, imgData) {
if (imgData.bitmap) {
ctx.drawImage(imgData.bitmap, 0, 0);
return;
}
const height = imgData.height, width = imgData.width;
const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
let srcPos = 0;
const src = imgData.data;
const dest = chunkImgData.data;
for (let i7 = 0; i7 < totalChunks; i7++) {
const thisChunkHeight = i7 < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
({
srcPos
} = convertBlackAndWhiteToRGBA({
src,
srcPos,
dest,
width,
height: thisChunkHeight,
nonBlackColor: 0
}));
ctx.putImageData(chunkImgData, 0, i7 * FULL_CHUNK_HEIGHT);
}
}
function copyCtxState(sourceCtx, destCtx) {
const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"];
for (const property of properties) {
if (sourceCtx[property] !== void 0) {
destCtx[property] = sourceCtx[property];
}
}
if (sourceCtx.setLineDash !== void 0) {
destCtx.setLineDash(sourceCtx.getLineDash());
destCtx.lineDashOffset = sourceCtx.lineDashOffset;
}
}
function resetCtxToDefault(ctx) {
ctx.strokeStyle = ctx.fillStyle = "#000000";
ctx.fillRule = "nonzero";
ctx.globalAlpha = 1;
ctx.lineWidth = 1;
ctx.lineCap = "butt";
ctx.lineJoin = "miter";
ctx.miterLimit = 10;
ctx.globalCompositeOperation = "source-over";
ctx.font = "10px sans-serif";
if (ctx.setLineDash !== void 0) {
ctx.setLineDash([]);
ctx.lineDashOffset = 0;
}
const {
filter: filter2
} = ctx;
if (filter2 !== "none" && filter2 !== "") {
ctx.filter = "none";
}
}
function getImageSmoothingEnabled(transform, interpolate3) {
if (interpolate3) {
return true;
}
Util.singularValueDecompose2dScale(transform, XY);
const actualScale = Math.fround(OutputScale.pixelRatio * PixelsPerInch.PDF_TO_CSS_UNITS);
return XY[0] <= actualScale && XY[1] <= actualScale;
}
function getFilenameFromContentDispositionHeader(contentDisposition) {
let needsEncodingFixup = true;
let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
if (tmp) {
tmp = tmp[1];
let filename = rfc2616unquote(tmp);
filename = unescape(filename);
filename = rfc5987decode(filename);
filename = rfc2047decode(filename);
return fixupEncoding(filename);
}
tmp = rfc2231getparam(contentDisposition);
if (tmp) {
const filename = rfc2047decode(tmp);
return fixupEncoding(filename);
}
tmp = toParamRegExp("filename", "i").exec(contentDisposition);
if (tmp) {
tmp = tmp[1];
let filename = rfc2616unquote(tmp);
filename = rfc2047decode(filename);
return fixupEncoding(filename);
}
function toParamRegExp(attributePattern, flags) {
return new RegExp("(?:^|;)\\s*" + attributePattern + '\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)', flags);
}
function textdecode(encoding, value) {
if (encoding) {
if (!/^[\x00-\xFF]+$/.test(value)) {
return value;
}
try {
const decoder = new TextDecoder(encoding, {
fatal: true
});
const buffer = stringToBytes(value);
value = decoder.decode(buffer);
needsEncodingFixup = false;
} catch {
}
}
return value;
}
function fixupEncoding(value) {
if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
value = textdecode("utf-8", value);
if (needsEncodingFixup) {
value = textdecode("iso-8859-1", value);
}
}
return value;
}
function rfc2231getparam(contentDispositionStr) {
const matches = [];
let match2;
const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
while ((match2 = iter.exec(contentDispositionStr)) !== null) {
let [, n7, quot, part] = match2;
n7 = parseInt(n7, 10);
if (n7 in matches) {
if (n7 === 0) {
break;
}
continue;
}
matches[n7] = [quot, part];
}
const parts = [];
for (let n7 = 0; n7 < matches.length; ++n7) {
if (!(n7 in matches)) {
break;
}
let [quot, part] = matches[n7];
part = rfc2616unquote(part);
if (quot) {
part = unescape(part);
if (n7 === 0) {
part = rfc5987decode(part);
}
}
parts.push(part);
}
return parts.join("");
}
function rfc2616unquote(value) {
if (value.startsWith('"')) {
const parts = value.slice(1).split('\\"');
for (let i7 = 0; i7 < parts.length; ++i7) {
const quotindex = parts[i7].indexOf('"');
if (quotindex !== -1) {
parts[i7] = parts[i7].slice(0, quotindex);
parts.length = i7 + 1;
}
parts[i7] = parts[i7].replaceAll(/\\(.)/g, "$1");
}
value = parts.join('"');
}
return value;
}
function rfc5987decode(extvalue) {
const encodingend = extvalue.indexOf("'");
if (encodingend === -1) {
return extvalue;
}
const encoding = extvalue.slice(0, encodingend);
const langvalue = extvalue.slice(encodingend + 1);
const value = langvalue.replace(/^[^']*'/, "");
return textdecode(encoding, value);
}
function rfc2047decode(value) {
if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
return value;
}
return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function(matches, charset, encoding, text3) {
if (encoding === "q" || encoding === "Q") {
text3 = text3.replaceAll("_", " ");
text3 = text3.replaceAll(/=([0-9a-fA-F]{2})/g, function(match2, hex2) {
return String.fromCharCode(parseInt(hex2, 16));
});
return textdecode(charset, text3);
}
try {
text3 = atob(text3);
} catch {
}
return textdecode(charset, text3);
});
}
return "";
}
function createHeaders(isHttp, httpHeaders) {
const headers = new Headers();
if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") {
return headers;
}
for (const key in httpHeaders) {
const val2 = httpHeaders[key];
if (val2 !== void 0) {
headers.append(key, val2);
}
}
return headers;
}
function getResponseOrigin(url) {
return URL.parse(url)?.origin ?? null;
}
function validateRangeRequestCapabilities({
responseHeaders,
isHttp,
rangeChunkSize,
disableRange
}) {
const returnValues = {
allowRangeRequests: false,
suggestedLength: void 0
};
const length = parseInt(responseHeaders.get("Content-Length"), 10);
if (!Number.isInteger(length)) {
return returnValues;
}
returnValues.suggestedLength = length;
if (length <= 2 * rangeChunkSize) {
return returnValues;
}
if (disableRange || !isHttp) {
return returnValues;
}
if (responseHeaders.get("Accept-Ranges") !== "bytes") {
return returnValues;
}
const contentEncoding = responseHeaders.get("Content-Encoding") || "identity";
if (contentEncoding !== "identity") {
return returnValues;
}
returnValues.allowRangeRequests = true;
return returnValues;
}
function extractFilenameFromHeader(responseHeaders) {
const contentDisposition = responseHeaders.get("Content-Disposition");
if (contentDisposition) {
let filename = getFilenameFromContentDispositionHeader(contentDisposition);
if (filename.includes("%")) {
try {
filename = decodeURIComponent(filename);
} catch {
}
}
if (isPdfFile(filename)) {
return filename;
}
}
return null;
}
function createResponseError(status, url) {
return new ResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status, status === 404 || status === 0 && url.startsWith("file:"));
}
function validateResponseStatus(status) {
return status === 200 || status === 206;
}
function createFetchOptions(headers, withCredentials, abortController) {
return {
method: "GET",
headers,
signal: abortController.signal,
mode: "cors",
credentials: withCredentials ? "include" : "same-origin",
redirect: "follow"
};
}
function getArrayBuffer(val2) {
if (val2 instanceof Uint8Array) {
return val2.buffer;
}
if (val2 instanceof ArrayBuffer) {
return val2;
}
warn(`getArrayBuffer - unexpected data format: ${val2}`);
return new Uint8Array(val2).buffer;
}
function network_getArrayBuffer(xhr) {
const data = xhr.response;
if (typeof data !== "string") {
return data;
}
return stringToBytes(data).buffer;
}
function parseUrlOrPath(sourceUrl) {
if (urlRegex.test(sourceUrl)) {
return new URL(sourceUrl);
}
const url = process.getBuiltinModule("url");
return new URL(url.pathToFileURL(sourceUrl));
}
function getDocument(src = {}) {
if (typeof src === "string" || src instanceof URL) {
src = {
url: src
};
} else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {
src = {
data: src
};
}
const task = new PDFDocumentLoadingTask();
const {
docId
} = task;
const url = src.url ? getUrlProp(src.url) : null;
const data = src.data ? getDataProp(src.data) : null;
const httpHeaders = src.httpHeaders || null;
const withCredentials = src.withCredentials === true;
const password = src.password ?? null;
const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : 2 ** 16;
let worker = src.worker instanceof PDFWorker ? src.worker : null;
const verbosity2 = src.verbosity;
const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null;
const cMapUrl = getFactoryUrlProp(src.cMapUrl);
const cMapPacked = src.cMapPacked !== false;
const CMapReaderFactory = src.CMapReaderFactory || (isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory);
const iccUrl = getFactoryUrlProp(src.iccUrl);
const standardFontDataUrl = getFactoryUrlProp(src.standardFontDataUrl);
const StandardFontDataFactory = src.StandardFontDataFactory || (isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory);
const wasmUrl = getFactoryUrlProp(src.wasmUrl);
const WasmFactory = src.WasmFactory || (isNodeJS ? NodeWasmFactory : DOMWasmFactory);
const ignoreErrors = src.stopAtErrors !== true;
const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
const isEvalSupported2 = src.isEvalSupported !== false;
const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS;
const isImageDecoderSupported = typeof src.isImageDecoderSupported === "boolean" ? src.isImageDecoderSupported : !isNodeJS && (util_FeatureTest.platform.isFirefox || !globalThis.chrome);
const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1;
const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS;
const fontExtraProperties = src.fontExtraProperties === true;
const enableXfa = src.enableXfa === true;
const ownerDocument = src.ownerDocument || globalThis.document;
const disableRange = src.disableRange === true;
const disableStream = src.disableStream === true;
const disableAutoFetch = src.disableAutoFetch === true;
const pdfBug = src.pdfBug === true;
const CanvasFactory = src.CanvasFactory || (isNodeJS ? NodeCanvasFactory : DOMCanvasFactory);
const FilterFactory = src.FilterFactory || (isNodeJS ? NodeFilterFactory : DOMFilterFactory);
const enableHWA = src.enableHWA === true;
const useWasm = src.useWasm !== false;
const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace;
const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : !!(CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && WasmFactory === DOMWasmFactory && cMapUrl && standardFontDataUrl && wasmUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI) && isValidFetchUrl(wasmUrl, document.baseURI));
const styleElement = null;
setVerbosityLevel(verbosity2);
const transportFactory = {
canvasFactory: new CanvasFactory({
ownerDocument,
enableHWA
}),
filterFactory: new FilterFactory({
docId,
ownerDocument
}),
cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({
baseUrl: cMapUrl,
isCompressed: cMapPacked
}),
standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({
baseUrl: standardFontDataUrl
}),
wasmFactory: useWorkerFetch ? null : new WasmFactory({
baseUrl: wasmUrl
})
};
if (!worker) {
worker = PDFWorker.create({
verbosity: verbosity2,
port: GlobalWorkerOptions.workerPort
});
task._worker = worker;
}
const docParams = {
docId,
apiVersion: "5.4.394",
data,
password,
disableAutoFetch,
rangeChunkSize,
length,
docBaseUrl,
enableXfa,
evaluatorOptions: {
maxImageSize,
disableFontFace,
ignoreErrors,
isEvalSupported: isEvalSupported2,
isOffscreenCanvasSupported,
isImageDecoderSupported,
canvasMaxAreaInBytes,
fontExtraProperties,
useSystemFonts,
useWasm,
useWorkerFetch,
cMapUrl,
iccUrl,
standardFontDataUrl,
wasmUrl
}
};
const transportParams = {
ownerDocument,
pdfBug,
styleElement,
loadingParams: {
disableAutoFetch,
enableXfa
}
};
worker.promise.then(function() {
if (task.destroyed) {
throw new Error("Loading aborted");
}
if (worker.destroyed) {
throw new Error("Worker was destroyed");
}
const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null);
let networkStream;
if (rangeTransport) {
networkStream = new PDFDataTransportStream(rangeTransport, {
disableRange,
disableStream
});
} else if (!data) {
if (!url) {
throw new Error("getDocument - no `url` parameter provided.");
}
const NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : isNodeJS ? PDFNodeStream : PDFNetworkStream;
networkStream = new NetworkStream({
url,
length,
httpHeaders,
withCredentials,
rangeChunkSize,
disableRange,
disableStream
});
}
return workerIdPromise.then((workerId) => {
if (task.destroyed) {
throw new Error("Loading aborted");
}
if (worker.destroyed) {
throw new Error("Worker was destroyed");
}
const messageHandler = new MessageHandler(docId, workerId, worker.port);
const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory, enableHWA);
task._transport = transport;
messageHandler.send("Ready", null);
});
}).catch(task._capability.reject);
return task;
}
function makeColorComp(n7) {
return Math.floor(Math.max(0, Math.min(1, n7)) * 255).toString(16).padStart(2, "0");
}
function scaleAndClamp(x2) {
return Math.max(0, Math.min(255, 255 * x2));
}
var __webpack_require__, isNodeJS, FONT_IDENTITY_MATRIX, LINE_FACTOR, LINE_DESCENT_FACTOR, BASELINE_FACTOR, RenderingIntentFlag, AnnotationMode, AnnotationEditorPrefix, AnnotationEditorType, AnnotationEditorParamsType, PermissionFlag, MeshFigureType, TextRenderingMode, util_ImageKind, AnnotationType, AnnotationBorderStyleType, VerbosityLevel, OPS, DrawOPS, PasswordResponses, verbosity, BaseException, PasswordException, UnknownErrorException, InvalidPDFException, ResponseException, FormatError, AbortException, util_FeatureTest, hexNumbers, Util, NormalizeRegex, NormalizationMap, AnnotationPrefix, XfaText, XfaLayer, SVG_NS, PixelsPerInch, PageViewport, RenderingCancelledException, StatTimer, PDFDateString, OutputScale, SupportedImageMimeTypes, ColorScheme, CSSConstants, contrastCache, EditorToolbar, FloatingToolbar, CurrentPointers, IdManager, ImageManager, CommandManager, KeyboardManager, ColorManager, AnnotationEditorUIManager, AltText, Comment, TouchManager, AnnotationEditor, FakeEditor, SEED, MASK_HIGH, MASK_LOW, MurmurHash3_64, SerializableEmpty, AnnotationStorage, PrintAnnotationStorage, FontLoader, FontFaceObject, CssFontInfo, SystemFontInfo, FontInfo, PatternInfo, isRefProxy, isNameProxy, isValidExplicitDest, LoopbackPort, CallbackKind, StreamKind, MessageHandler, BaseCanvasFactory, DOMCanvasFactory, BaseCMapReaderFactory, DOMCMapReaderFactory, BaseFilterFactory, DOMFilterFactory, BaseStandardFontDataFactory, DOMStandardFontDataFactory, BaseWasmFactory, DOMWasmFactory, NodeFilterFactory, NodeCanvasFactory, NodeCMapReaderFactory, NodeStandardFontDataFactory, NodeWasmFactory, FORCED_DEPENDENCY_LABEL, floor, ceil, EMPTY_BBOX, BBoxReader, ensureDebugMetadata, CanvasDependencyTracker, CanvasNestedDependencyTracker, Dependencies, PathType, BaseShadingPattern, RadialAxialShadingPattern, MeshShadingPattern, DummyShadingPattern, PaintType, TilingPattern, MIN_FONT_SIZE, MAX_FONT_SIZE, EXECUTION_TIME, EXECUTION_STEPS, FULL_CHUNK_HEIGHT, SCALE_MATRIX, XY, MIN_MAX_INIT, CachedCanvases, CanvasExtraState, LINE_CAP_STYLES, LINE_JOIN_STYLES, NORMAL_CLIP, EO_CLIP, CanvasGraphics, GlobalWorkerOptions, Metadata, INTERNAL, OptionalContentGroup, OptionalContentConfig, PDFDataTransportStream, PDFDataTransportStreamReader, PDFDataTransportStreamRangeReader, PDFFetchStream, PDFFetchStreamReader, PDFFetchStreamRangeReader, OK_RESPONSE, PARTIAL_CONTENT_RESPONSE, NetworkManager, PDFNetworkStream, PDFNetworkStreamFullRequestReader, PDFNetworkStreamRangeRequestReader, urlRegex, PDFNodeStream, PDFNodeStreamFsFullReader, PDFNodeStreamFsRangeReader, INITIAL_DATA, PDFObjects, MAX_TEXT_DIVS_TO_RENDER, DEFAULT_FONT_SIZE, TextLayer, RENDERING_CANCELLED_TIMEOUT, PDFDocumentLoadingTask, PDFDataRangeTransport, PDFDocumentProxy, PDFPageProxy, PDFWorker, WorkerTransport, RenderTask, InternalRenderTask, version2, build, ColorPicker, BasicColorPicker, ColorConverters, BaseSVGFactory, DOMSVGFactory, annotation_layer_DEFAULT_FONT_SIZE, GetElementsByNameSet, TIMEZONE_OFFSET, AnnotationElementFactory, AnnotationElement, EditorAnnotationElement, LinkAnnotationElement, TextAnnotationElement, WidgetAnnotationElement, TextWidgetAnnotationElement, SignatureWidgetAnnotationElement, CheckboxWidgetAnnotationElement, RadioButtonWidgetAnnotationElement, PushButtonWidgetAnnotationElement, ChoiceWidgetAnnotationElement, PopupAnnotationElement, PopupElement, FreeTextAnnotationElement, LineAnnotationElement, SquareAnnotationElement, CircleAnnotationElement, PolylineAnnotationElement, PolygonAnnotationElement, CaretAnnotationElement, InkAnnotationElement, HighlightAnnotationElement, UnderlineAnnotationElement, SquigglyAnnotationElement, StrikeOutAnnotationElement, StampAnnotationElement, FileAttachmentAnnotationElement, AnnotationLayer, EOL_PATTERN, FreeTextEditor, Outline, FreeDrawOutliner, FreeDrawOutline, HighlightOutliner, HighlightOutline, FreeHighlightOutliner, FreeHighlightOutline, HighlightEditor, DrawingOptions, DrawingEditor, InkDrawOutliner, InkDrawOutline, InkDrawingOptions, InkEditor, ContourDrawOutline, BASE_HEADER_LENGTH, POINTS_PROPERTIES_NUMBER, SignatureExtractor, SignatureOptions, DrawnSignatureOptions, SignatureEditor, StampEditor, AnnotationEditorLayer, DrawLayer;
var init_pdf = __esm({
"../pi-mono/node_modules/pdfjs-dist/build/pdf.mjs"() {
init_process_shim();
__webpack_require__ = {};
(() => {
__webpack_require__.d = (exports, definition) => {
for (var key in definition) {
if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
}
}
};
})();
(() => {
__webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
})();
isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
FONT_IDENTITY_MATRIX = [1e-3, 0, 0, 1e-3, 0, 0];
LINE_FACTOR = 1.35;
LINE_DESCENT_FACTOR = 0.35;
BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
RenderingIntentFlag = {
ANY: 1,
DISPLAY: 2,
PRINT: 4,
SAVE: 8,
ANNOTATIONS_FORMS: 16,
ANNOTATIONS_STORAGE: 32,
ANNOTATIONS_DISABLE: 64,
IS_EDITING: 128,
OPLIST: 256
};
AnnotationMode = {
DISABLE: 0,
ENABLE: 1,
ENABLE_FORMS: 2,
ENABLE_STORAGE: 3
};
AnnotationEditorPrefix = "pdfjs_internal_editor_";
AnnotationEditorType = {
DISABLE: -1,
NONE: 0,
FREETEXT: 3,
HIGHLIGHT: 9,
STAMP: 13,
INK: 15,
POPUP: 16,
SIGNATURE: 101,
COMMENT: 102
};
AnnotationEditorParamsType = {
RESIZE: 1,
CREATE: 2,
FREETEXT_SIZE: 11,
FREETEXT_COLOR: 12,
FREETEXT_OPACITY: 13,
INK_COLOR: 21,
INK_THICKNESS: 22,
INK_OPACITY: 23,
HIGHLIGHT_COLOR: 31,
HIGHLIGHT_THICKNESS: 32,
HIGHLIGHT_FREE: 33,
HIGHLIGHT_SHOW_ALL: 34,
DRAW_STEP: 41
};
PermissionFlag = {
PRINT: 4,
MODIFY_CONTENTS: 8,
COPY: 16,
MODIFY_ANNOTATIONS: 32,
FILL_INTERACTIVE_FORMS: 256,
COPY_FOR_ACCESSIBILITY: 512,
ASSEMBLE: 1024,
PRINT_HIGH_QUALITY: 2048
};
MeshFigureType = {
TRIANGLES: 1,
LATTICE: 2,
PATCH: 3
};
TextRenderingMode = {
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
};
util_ImageKind = {
GRAYSCALE_1BPP: 1,
RGB_24BPP: 2,
RGBA_32BPP: 3
};
AnnotationType = {
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
};
AnnotationBorderStyleType = {
SOLID: 1,
DASHED: 2,
BEVELED: 3,
INSET: 4,
UNDERLINE: 5
};
VerbosityLevel = {
ERRORS: 0,
WARNINGS: 1,
INFOS: 5
};
OPS = {
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
};
DrawOPS = {
moveTo: 0,
lineTo: 1,
curveTo: 2,
quadraticCurveTo: 3,
closePath: 4
};
PasswordResponses = {
NEED_PASSWORD: 1,
INCORRECT_PASSWORD: 2
};
verbosity = VerbosityLevel.WARNINGS;
BaseException = (function BaseExceptionClosure() {
function BaseException2(message, name) {
this.message = message;
this.name = name;
}
BaseException2.prototype = new Error();
BaseException2.constructor = BaseException2;
return BaseException2;
})();
PasswordException = class extends BaseException {
constructor(msg, code) {
super(msg, "PasswordException");
this.code = code;
}
};
UnknownErrorException = class extends BaseException {
constructor(msg, details) {
super(msg, "UnknownErrorException");
this.details = details;
}
};
InvalidPDFException = class extends BaseException {
constructor(msg) {
super(msg, "InvalidPDFException");
}
};
ResponseException = class extends BaseException {
constructor(msg, status, missing) {
super(msg, "ResponseException");
this.status = status;
this.missing = missing;
}
};
FormatError = class extends BaseException {
constructor(msg) {
super(msg, "FormatError");
}
};
AbortException = class extends BaseException {
constructor(msg) {
super(msg, "AbortException");
}
};
util_FeatureTest = class {
static get isLittleEndian() {
return shadow(this, "isLittleEndian", isLittleEndian());
}
static get isEvalSupported() {
return shadow(this, "isEvalSupported", isEvalSupported());
}
static get isOffscreenCanvasSupported() {
return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
}
static get isImageDecoderSupported() {
return shadow(this, "isImageDecoderSupported", typeof ImageDecoder !== "undefined");
}
static get isFloat16ArraySupported() {
return shadow(this, "isFloat16ArraySupported", typeof Float16Array !== "undefined");
}
static get isSanitizerSupported() {
return shadow(this, "isSanitizerSupported", typeof Sanitizer !== "undefined");
}
static get platform() {
const {
platform,
userAgent
} = navigator;
return shadow(this, "platform", {
isAndroid: userAgent.includes("Android"),
isLinux: platform.includes("Linux"),
isMac: platform.includes("Mac"),
isWindows: platform.includes("Win"),
isFirefox: userAgent.includes("Firefox")
});
}
static get isCSSRoundSupported() {
return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));
}
};
hexNumbers = Array.from(Array(256).keys(), (n7) => n7.toString(16).padStart(2, "0"));
Util = class {
static makeHexColor(r8, g3, b4) {
return `#${hexNumbers[r8]}${hexNumbers[g3]}${hexNumbers[b4]}`;
}
static domMatrixToTransform(dm) {
return [dm.a, dm.b, dm.c, dm.d, dm.e, dm.f];
}
static scaleMinMax(transform, minMax) {
let temp;
if (transform[0]) {
if (transform[0] < 0) {
temp = minMax[0];
minMax[0] = minMax[2];
minMax[2] = temp;
}
minMax[0] *= transform[0];
minMax[2] *= transform[0];
if (transform[3] < 0) {
temp = minMax[1];
minMax[1] = minMax[3];
minMax[3] = temp;
}
minMax[1] *= transform[3];
minMax[3] *= transform[3];
} else {
temp = minMax[0];
minMax[0] = minMax[1];
minMax[1] = temp;
temp = minMax[2];
minMax[2] = minMax[3];
minMax[3] = temp;
if (transform[1] < 0) {
temp = minMax[1];
minMax[1] = minMax[3];
minMax[3] = temp;
}
minMax[1] *= transform[1];
minMax[3] *= transform[1];
if (transform[2] < 0) {
temp = minMax[0];
minMax[0] = minMax[2];
minMax[2] = temp;
}
minMax[0] *= transform[2];
minMax[2] *= transform[2];
}
minMax[0] += transform[4];
minMax[1] += transform[5];
minMax[2] += transform[4];
minMax[3] += transform[5];
}
static transform(m1, m22) {
return [m1[0] * m22[0] + m1[2] * m22[1], m1[1] * m22[0] + m1[3] * m22[1], m1[0] * m22[2] + m1[2] * m22[3], m1[1] * m22[2] + m1[3] * m22[3], m1[0] * m22[4] + m1[2] * m22[5] + m1[4], m1[1] * m22[4] + m1[3] * m22[5] + m1[5]];
}
static multiplyByDOMMatrix(m4, md) {
return [m4[0] * md.a + m4[2] * md.b, m4[1] * md.a + m4[3] * md.b, m4[0] * md.c + m4[2] * md.d, m4[1] * md.c + m4[3] * md.d, m4[0] * md.e + m4[2] * md.f + m4[4], m4[1] * md.e + m4[3] * md.f + m4[5]];
}
static applyTransform(p4, m4, pos = 0) {
const p0 = p4[pos];
const p1 = p4[pos + 1];
p4[pos] = p0 * m4[0] + p1 * m4[2] + m4[4];
p4[pos + 1] = p0 * m4[1] + p1 * m4[3] + m4[5];
}
static applyTransformToBezier(p4, transform, pos = 0) {
const m0 = transform[0];
const m1 = transform[1];
const m22 = transform[2];
const m32 = transform[3];
const m4 = transform[4];
const m5 = transform[5];
for (let i7 = 0; i7 < 6; i7 += 2) {
const pI = p4[pos + i7];
const pI1 = p4[pos + i7 + 1];
p4[pos + i7] = pI * m0 + pI1 * m22 + m4;
p4[pos + i7 + 1] = pI * m1 + pI1 * m32 + m5;
}
}
static applyInverseTransform(p4, m4) {
const p0 = p4[0];
const p1 = p4[1];
const d4 = m4[0] * m4[3] - m4[1] * m4[2];
p4[0] = (p0 * m4[3] - p1 * m4[2] + m4[2] * m4[5] - m4[4] * m4[3]) / d4;
p4[1] = (-p0 * m4[1] + p1 * m4[0] + m4[4] * m4[1] - m4[5] * m4[0]) / d4;
}
static axialAlignedBoundingBox(rect, transform, output) {
const m0 = transform[0];
const m1 = transform[1];
const m22 = transform[2];
const m32 = transform[3];
const m4 = transform[4];
const m5 = transform[5];
const r0 = rect[0];
const r1 = rect[1];
const r22 = rect[2];
const r32 = rect[3];
let a0 = m0 * r0 + m4;
let a22 = a0;
let a1 = m0 * r22 + m4;
let a3 = a1;
let b0 = m32 * r1 + m5;
let b22 = b0;
let b1 = m32 * r32 + m5;
let b32 = b1;
if (m1 !== 0 || m22 !== 0) {
const m1r0 = m1 * r0;
const m1r2 = m1 * r22;
const m2r1 = m22 * r1;
const m2r3 = m22 * r32;
a0 += m2r1;
a3 += m2r1;
a1 += m2r3;
a22 += m2r3;
b0 += m1r0;
b32 += m1r0;
b1 += m1r2;
b22 += m1r2;
}
output[0] = Math.min(output[0], a0, a1, a22, a3);
output[1] = Math.min(output[1], b0, b1, b22, b32);
output[2] = Math.max(output[2], a0, a1, a22, a3);
output[3] = Math.max(output[3], b0, b1, b22, b32);
}
static inverseTransform(m4) {
const d4 = m4[0] * m4[3] - m4[1] * m4[2];
return [m4[3] / d4, -m4[1] / d4, -m4[2] / d4, m4[0] / d4, (m4[2] * m4[5] - m4[4] * m4[3]) / d4, (m4[4] * m4[1] - m4[5] * m4[0]) / d4];
}
static singularValueDecompose2dScale(matrix, output) {
const m0 = matrix[0];
const m1 = matrix[1];
const m22 = matrix[2];
const m32 = matrix[3];
const a3 = m0 ** 2 + m1 ** 2;
const b4 = m0 * m22 + m1 * m32;
const c6 = m22 ** 2 + m32 ** 2;
const first = (a3 + c6) / 2;
const second = Math.sqrt(first ** 2 - (a3 * c6 - b4 ** 2));
output[0] = Math.sqrt(first + second || 1);
output[1] = Math.sqrt(first - second || 1);
}
static normalizeRect(rect) {
const r8 = rect.slice(0);
if (rect[0] > rect[2]) {
r8[0] = rect[2];
r8[2] = rect[0];
}
if (rect[1] > rect[3]) {
r8[1] = rect[3];
r8[3] = rect[1];
}
return r8;
}
static intersect(rect1, rect2) {
const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
if (xLow > xHigh) {
return null;
}
const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
if (yLow > yHigh) {
return null;
}
return [xLow, yLow, xHigh, yHigh];
}
static pointBoundingBox(x2, y4, minMax) {
minMax[0] = Math.min(minMax[0], x2);
minMax[1] = Math.min(minMax[1], y4);
minMax[2] = Math.max(minMax[2], x2);
minMax[3] = Math.max(minMax[3], y4);
}
static rectBoundingBox(x0, y0, x1, y1, minMax) {
minMax[0] = Math.min(minMax[0], x0, x1);
minMax[1] = Math.min(minMax[1], y0, y1);
minMax[2] = Math.max(minMax[2], x0, x1);
minMax[3] = Math.max(minMax[3], y0, y1);
}
static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, t6, minMax) {
if (t6 <= 0 || t6 >= 1) {
return;
}
const mt = 1 - t6;
const tt = t6 * t6;
const ttt = tt * t6;
const x4 = mt * (mt * (mt * x0 + 3 * t6 * x1) + 3 * tt * x2) + ttt * x3;
const y4 = mt * (mt * (mt * y0 + 3 * t6 * y1) + 3 * tt * y22) + ttt * y32;
minMax[0] = Math.min(minMax[0], x4);
minMax[1] = Math.min(minMax[1], y4);
minMax[2] = Math.max(minMax[2], x4);
minMax[3] = Math.max(minMax[3], y4);
}
static #getExtremum(x0, x1, x2, x3, y0, y1, y22, y32, a3, b4, c6, minMax) {
if (Math.abs(a3) < 1e-12) {
if (Math.abs(b4) >= 1e-12) {
this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, -c6 / b4, minMax);
}
return;
}
const delta = b4 ** 2 - 4 * c6 * a3;
if (delta < 0) {
return;
}
const sqrtDelta = Math.sqrt(delta);
const a22 = 2 * a3;
this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, (-b4 + sqrtDelta) / a22, minMax);
this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, (-b4 - sqrtDelta) / a22, minMax);
}
static bezierBoundingBox(x0, y0, x1, y1, x2, y22, x3, y32, minMax) {
minMax[0] = Math.min(minMax[0], x0, x3);
minMax[1] = Math.min(minMax[1], y0, y32);
minMax[2] = Math.max(minMax[2], x0, x3);
minMax[3] = Math.max(minMax[3], y0, y32);
this.#getExtremum(x0, x1, x2, x3, y0, y1, y22, y32, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax);
this.#getExtremum(x0, x1, x2, x3, y0, y1, y22, y32, 3 * (-y0 + 3 * (y1 - y22) + y32), 6 * (y0 - 2 * y1 + y22), 3 * (y1 - y0), minMax);
}
};
NormalizeRegex = null;
NormalizationMap = null;
AnnotationPrefix = "pdfjs_internal_id_";
if (typeof Promise.try !== "function") {
Promise.try = function(fn, ...args) {
return new Promise((resolve2) => {
resolve2(fn(...args));
});
};
}
if (typeof Math.sumPrecise !== "function") {
Math.sumPrecise = function(numbers2) {
return numbers2.reduce((a3, b4) => a3 + b4, 0);
};
}
XfaText = class _XfaText {
static textContent(xfa) {
const items = [];
const output = {
items,
styles: /* @__PURE__ */ Object.create(null)
};
function walk(node) {
if (!node) {
return;
}
let str2 = null;
const name = node.name;
if (name === "#text") {
str2 = node.value;
} else if (!_XfaText.shouldBuildText(name)) {
return;
} else if (node?.attributes?.textContent) {
str2 = node.attributes.textContent;
} else if (node.value) {
str2 = node.value;
}
if (str2 !== null) {
items.push({
str: str2
});
}
if (!node.children) {
return;
}
for (const child of node.children) {
walk(child);
}
}
walk(xfa);
return output;
}
static shouldBuildText(name) {
return !(name === "textarea" || name === "input" || name === "option" || name === "select");
}
};
XfaLayer = class {
static setupStorage(html, id, element, storage2, intent) {
const storedData = storage2.getValue(id, {
value: null
});
switch (element.name) {
case "textarea":
if (storedData.value !== null) {
html.textContent = storedData.value;
}
if (intent === "print") {
break;
}
html.addEventListener("input", (event) => {
storage2.setValue(id, {
value: event.target.value
});
});
break;
case "input":
if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
if (storedData.value === element.attributes.xfaOn) {
html.setAttribute("checked", true);
} else if (storedData.value === element.attributes.xfaOff) {
html.removeAttribute("checked");
}
if (intent === "print") {
break;
}
html.addEventListener("change", (event) => {
storage2.setValue(id, {
value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
});
});
} else {
if (storedData.value !== null) {
html.setAttribute("value", storedData.value);
}
if (intent === "print") {
break;
}
html.addEventListener("input", (event) => {
storage2.setValue(id, {
value: event.target.value
});
});
}
break;
case "select":
if (storedData.value !== null) {
html.setAttribute("value", storedData.value);
for (const option of element.children) {
if (option.attributes.value === storedData.value) {
option.attributes.selected = true;
} else if (option.attributes.hasOwnProperty("selected")) {
delete option.attributes.selected;
}
}
}
html.addEventListener("input", (event) => {
const options = event.target.options;
const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
storage2.setValue(id, {
value
});
});
break;
}
}
static setAttributes({
html,
element,
storage: storage2 = null,
intent,
linkService
}) {
const {
attributes
} = element;
const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
if (attributes.type === "radio") {
attributes.name = `${attributes.name}-${intent}`;
}
for (const [key, value] of Object.entries(attributes)) {
if (value === null || value === void 0) {
continue;
}
switch (key) {
case "class":
if (value.length) {
html.setAttribute(key, value.join(" "));
}
break;
case "dataId":
break;
case "id":
html.setAttribute("data-element-id", value);
break;
case "style":
Object.assign(html.style, value);
break;
case "textContent":
html.textContent = value;
break;
default:
if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
html.setAttribute(key, value);
}
}
}
if (isHTMLAnchorElement) {
linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
}
if (storage2 && attributes.dataId) {
this.setupStorage(html, attributes.dataId, element, storage2);
}
}
static render(parameters) {
const storage2 = parameters.annotationStorage;
const linkService = parameters.linkService;
const root = parameters.xfaHtml;
const intent = parameters.intent || "display";
const rootHtml = document.createElement(root.name);
if (root.attributes) {
this.setAttributes({
html: rootHtml,
element: root,
intent,
linkService
});
}
const isNotForRichText = intent !== "richText";
const rootDiv = parameters.div;
rootDiv.append(rootHtml);
if (parameters.viewport) {
const transform = `matrix(${parameters.viewport.transform.join(",")})`;
rootDiv.style.transform = transform;
}
if (isNotForRichText) {
rootDiv.setAttribute("class", "xfaLayer xfaFont");
}
const textDivs = [];
if (root.children.length === 0) {
if (root.value) {
const node = document.createTextNode(root.value);
rootHtml.append(node);
if (isNotForRichText && XfaText.shouldBuildText(root.name)) {
textDivs.push(node);
}
}
return {
textDivs
};
}
const stack = [[root, -1, rootHtml]];
while (stack.length > 0) {
const [parent, i7, html] = stack.at(-1);
if (i7 + 1 === parent.children.length) {
stack.pop();
continue;
}
const child = parent.children[++stack.at(-1)[1]];
if (child === null) {
continue;
}
const {
name
} = child;
if (name === "#text") {
const node = document.createTextNode(child.value);
textDivs.push(node);
html.append(node);
continue;
}
const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
html.append(childHtml);
if (child.attributes) {
this.setAttributes({
html: childHtml,
element: child,
storage: storage2,
intent,
linkService
});
}
if (child.children?.length > 0) {
stack.push([child, -1, childHtml]);
} else if (child.value) {
const node = document.createTextNode(child.value);
if (isNotForRichText && XfaText.shouldBuildText(name)) {
textDivs.push(node);
}
childHtml.append(node);
}
}
for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
el.setAttribute("readOnly", true);
}
return {
textDivs
};
}
static update(parameters) {
const transform = `matrix(${parameters.viewport.transform.join(",")})`;
parameters.div.style.transform = transform;
parameters.div.hidden = false;
}
};
SVG_NS = "http://www.w3.org/2000/svg";
PixelsPerInch = class {
static CSS = 96;
static PDF = 72;
static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
};
PageViewport = class _PageViewport {
constructor({
viewBox,
userUnit,
scale,
rotation,
offsetX = 0,
offsetY = 0,
dontFlip = false
}) {
this.viewBox = viewBox;
this.userUnit = userUnit;
this.scale = scale;
this.rotation = rotation;
this.offsetX = offsetX;
this.offsetY = offsetY;
scale *= userUnit;
const centerX = (viewBox[2] + viewBox[0]) / 2;
const centerY = (viewBox[3] + viewBox[1]) / 2;
let rotateA, rotateB, rotateC, rotateD;
rotation %= 360;
if (rotation < 0) {
rotation += 360;
}
switch (rotation) {
case 180:
rotateA = -1;
rotateB = 0;
rotateC = 0;
rotateD = 1;
break;
case 90:
rotateA = 0;
rotateB = 1;
rotateC = 1;
rotateD = 0;
break;
case 270:
rotateA = 0;
rotateB = -1;
rotateC = -1;
rotateD = 0;
break;
case 0:
rotateA = 1;
rotateB = 0;
rotateC = 0;
rotateD = -1;
break;
default:
throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
}
if (dontFlip) {
rotateC = -rotateC;
rotateD = -rotateD;
}
let offsetCanvasX, offsetCanvasY;
let width, height;
if (rotateA === 0) {
offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
width = (viewBox[3] - viewBox[1]) * scale;
height = (viewBox[2] - viewBox[0]) * scale;
} else {
offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
width = (viewBox[2] - viewBox[0]) * scale;
height = (viewBox[3] - viewBox[1]) * scale;
}
this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
this.width = width;
this.height = height;
}
get rawDims() {
const dims = this.viewBox;
return shadow(this, "rawDims", {
pageWidth: dims[2] - dims[0],
pageHeight: dims[3] - dims[1],
pageX: dims[0],
pageY: dims[1]
});
}
clone({
scale = this.scale,
rotation = this.rotation,
offsetX = this.offsetX,
offsetY = this.offsetY,
dontFlip = false
} = {}) {
return new _PageViewport({
viewBox: this.viewBox.slice(),
userUnit: this.userUnit,
scale,
rotation,
offsetX,
offsetY,
dontFlip
});
}
convertToViewportPoint(x2, y4) {
const p4 = [x2, y4];
Util.applyTransform(p4, this.transform);
return p4;
}
convertToViewportRectangle(rect) {
const topLeft = [rect[0], rect[1]];
Util.applyTransform(topLeft, this.transform);
const bottomRight = [rect[2], rect[3]];
Util.applyTransform(bottomRight, this.transform);
return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
}
convertToPdfPoint(x2, y4) {
const p4 = [x2, y4];
Util.applyInverseTransform(p4, this.transform);
return p4;
}
};
RenderingCancelledException = class extends BaseException {
constructor(msg, extraDelay = 0) {
super(msg, "RenderingCancelledException");
this.extraDelay = extraDelay;
}
};
StatTimer = class {
started = /* @__PURE__ */ Object.create(null);
times = [];
time(name) {
if (name in this.started) {
warn(`Timer is already running for ${name}`);
}
this.started[name] = Date.now();
}
timeEnd(name) {
if (!(name in this.started)) {
warn(`Timer has not been started for ${name}`);
}
this.times.push({
name,
start: this.started[name],
end: Date.now()
});
delete this.started[name];
}
toString() {
const outBuf = [];
let longest = 0;
for (const {
name
} of this.times) {
longest = Math.max(name.length, longest);
}
for (const {
name,
start,
end
} of this.times) {
outBuf.push(`${name.padEnd(longest)} ${end - start}ms
`);
}
return outBuf.join("");
}
};
PDFDateString = class {
static #regex;
static toDateObject(input) {
if (input instanceof Date) {
return input;
}
if (!input || typeof input !== "string") {
return null;
}
this.#regex ||= new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");
const matches = this.#regex.exec(input);
if (!matches) {
return null;
}
const year = parseInt(matches[1], 10);
let month = parseInt(matches[2], 10);
month = month >= 1 && month <= 12 ? month - 1 : 0;
let day = parseInt(matches[3], 10);
day = day >= 1 && day <= 31 ? day : 1;
let hour = parseInt(matches[4], 10);
hour = hour >= 0 && hour <= 23 ? hour : 0;
let minute = parseInt(matches[5], 10);
minute = minute >= 0 && minute <= 59 ? minute : 0;
let second = parseInt(matches[6], 10);
second = second >= 0 && second <= 59 ? second : 0;
const universalTimeRelation = matches[7] || "Z";
let offsetHour = parseInt(matches[8], 10);
offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
let offsetMinute = parseInt(matches[9], 10) || 0;
offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
if (universalTimeRelation === "-") {
hour += offsetHour;
minute += offsetMinute;
} else if (universalTimeRelation === "+") {
hour -= offsetHour;
minute -= offsetMinute;
}
return new Date(Date.UTC(year, month, day, hour, minute, second));
}
};
OutputScale = class _OutputScale {
constructor() {
const {
pixelRatio
} = _OutputScale;
this.sx = pixelRatio;
this.sy = pixelRatio;
}
get scaled() {
return this.sx !== 1 || this.sy !== 1;
}
get symmetric() {
return this.sx === this.sy;
}
limitCanvas(width, height, maxPixels, maxDim, capAreaFactor = -1) {
let maxAreaScale = Infinity, maxWidthScale = Infinity, maxHeightScale = Infinity;
maxPixels = _OutputScale.capPixels(maxPixels, capAreaFactor);
if (maxPixels > 0) {
maxAreaScale = Math.sqrt(maxPixels / (width * height));
}
if (maxDim !== -1) {
maxWidthScale = maxDim / width;
maxHeightScale = maxDim / height;
}
const maxScale = Math.min(maxAreaScale, maxWidthScale, maxHeightScale);
if (this.sx > maxScale || this.sy > maxScale) {
this.sx = maxScale;
this.sy = maxScale;
return true;
}
return false;
}
static get pixelRatio() {
return globalThis.devicePixelRatio || 1;
}
static capPixels(maxPixels, capAreaFactor) {
if (capAreaFactor >= 0) {
const winPixels = Math.ceil(window.screen.availWidth * window.screen.availHeight * this.pixelRatio ** 2 * (1 + capAreaFactor / 100));
return maxPixels > 0 ? Math.min(maxPixels, winPixels) : winPixels;
}
return maxPixels;
}
};
SupportedImageMimeTypes = ["image/apng", "image/avif", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/svg+xml", "image/webp", "image/x-icon"];
ColorScheme = class {
static get isDarkMode() {
return shadow(this, "isDarkMode", !!window?.matchMedia?.("(prefers-color-scheme: dark)").matches);
}
};
CSSConstants = class {
static get commentForegroundColor() {
const element = document.createElement("span");
element.classList.add("comment", "sidebar");
const {
style
} = element;
style.width = style.height = "0";
style.display = "none";
style.color = "var(--comment-fg-color)";
document.body.append(element);
const {
color: color2
} = window.getComputedStyle(element);
element.remove();
return shadow(this, "commentForegroundColor", getRGB(color2));
}
};
contrastCache = /* @__PURE__ */ new Map();
EditorToolbar = class _EditorToolbar {
#toolbar = null;
#colorPicker = null;
#editor;
#buttons = null;
#altText = null;
#comment = null;
#commentButtonDivider = null;
#signatureDescriptionButton = null;
static #l10nRemove = null;
constructor(editor) {
this.#editor = editor;
_EditorToolbar.#l10nRemove ||= Object.freeze({
freetext: "pdfjs-editor-remove-freetext-button",
highlight: "pdfjs-editor-remove-highlight-button",
ink: "pdfjs-editor-remove-ink-button",
stamp: "pdfjs-editor-remove-stamp-button",
signature: "pdfjs-editor-remove-signature-button"
});
}
render() {
const editToolbar = this.#toolbar = document.createElement("div");
editToolbar.classList.add("editToolbar", "hidden");
editToolbar.setAttribute("role", "toolbar");
const signal = this.#editor._uiManager._signal;
if (signal instanceof AbortSignal && !signal.aborted) {
editToolbar.addEventListener("contextmenu", noContextMenu, {
signal
});
editToolbar.addEventListener("pointerdown", _EditorToolbar.#pointerDown, {
signal
});
}
const buttons = this.#buttons = document.createElement("div");
buttons.className = "buttons";
editToolbar.append(buttons);
const position = this.#editor.toolbarPosition;
if (position) {
const {
style
} = editToolbar;
const x2 = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0];
style.insetInlineEnd = `${100 * x2}%`;
style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`;
}
return editToolbar;
}
get div() {
return this.#toolbar;
}
static #pointerDown(e9) {
e9.stopPropagation();
}
#focusIn(e9) {
this.#editor._focusEventsAllowed = false;
stopEvent(e9);
}
#focusOut(e9) {
this.#editor._focusEventsAllowed = true;
stopEvent(e9);
}
#addListenersToElement(element) {
const signal = this.#editor._uiManager._signal;
if (!(signal instanceof AbortSignal) || signal.aborted) {
return false;
}
element.addEventListener("focusin", this.#focusIn.bind(this), {
capture: true,
signal
});
element.addEventListener("focusout", this.#focusOut.bind(this), {
capture: true,
signal
});
element.addEventListener("contextmenu", noContextMenu, {
signal
});
return true;
}
hide() {
this.#toolbar.classList.add("hidden");
this.#colorPicker?.hideDropdown();
}
show() {
this.#toolbar.classList.remove("hidden");
this.#altText?.shown();
this.#comment?.shown();
}
addDeleteButton() {
const {
editorType,
_uiManager
} = this.#editor;
const button = document.createElement("button");
button.classList.add("basic", "deleteButton");
button.tabIndex = 0;
button.setAttribute("data-l10n-id", _EditorToolbar.#l10nRemove[editorType]);
if (this.#addListenersToElement(button)) {
button.addEventListener("click", (e9) => {
_uiManager.delete();
}, {
signal: _uiManager._signal
});
}
this.#buttons.append(button);
}
get #divider() {
const divider = document.createElement("div");
divider.className = "divider";
return divider;
}
async addAltText(altText) {
const button = await altText.render();
this.#addListenersToElement(button);
this.#buttons.append(button, this.#divider);
this.#altText = altText;
}
addComment(comment, beforeElement = null) {
if (this.#comment) {
return;
}
const button = comment.renderForToolbar();
if (!button) {
return;
}
this.#addListenersToElement(button);
const divider = this.#commentButtonDivider = this.#divider;
if (!beforeElement) {
this.#buttons.append(button, divider);
} else {
this.#buttons.insertBefore(button, beforeElement);
this.#buttons.insertBefore(divider, beforeElement);
}
this.#comment = comment;
comment.toolbar = this;
}
addColorPicker(colorPicker) {
if (this.#colorPicker) {
return;
}
this.#colorPicker = colorPicker;
const button = colorPicker.renderButton();
this.#addListenersToElement(button);
this.#buttons.append(button, this.#divider);
}
async addEditSignatureButton(signatureManager) {
const button = this.#signatureDescriptionButton = await signatureManager.renderEditButton(this.#editor);
this.#addListenersToElement(button);
this.#buttons.append(button, this.#divider);
}
removeButton(name) {
switch (name) {
case "comment":
this.#comment?.removeToolbarCommentButton();
this.#comment = null;
this.#commentButtonDivider?.remove();
this.#commentButtonDivider = null;
break;
}
}
async addButton(name, tool) {
switch (name) {
case "colorPicker":
if (tool) {
this.addColorPicker(tool);
}
break;
case "altText":
if (tool) {
await this.addAltText(tool);
}
break;
case "editSignature":
if (tool) {
await this.addEditSignatureButton(tool);
}
break;
case "delete":
this.addDeleteButton();
break;
case "comment":
if (tool) {
this.addComment(tool);
}
break;
}
}
async addButtonBefore(name, tool, beforeSelector) {
if (!tool && name === "comment") {
return;
}
const beforeElement = this.#buttons.querySelector(beforeSelector);
if (!beforeElement) {
return;
}
if (name === "comment") {
this.addComment(tool, beforeElement);
}
}
updateEditSignatureButton(description) {
if (this.#signatureDescriptionButton) {
this.#signatureDescriptionButton.title = description;
}
}
remove() {
this.#toolbar.remove();
this.#colorPicker?.destroy();
this.#colorPicker = null;
}
};
FloatingToolbar = class {
#buttons = null;
#toolbar = null;
#uiManager;
constructor(uiManager) {
this.#uiManager = uiManager;
}
#render() {
const editToolbar = this.#toolbar = document.createElement("div");
editToolbar.className = "editToolbar";
editToolbar.setAttribute("role", "toolbar");
const signal = this.#uiManager._signal;
if (signal instanceof AbortSignal && !signal.aborted) {
editToolbar.addEventListener("contextmenu", noContextMenu, {
signal
});
}
const buttons = this.#buttons = document.createElement("div");
buttons.className = "buttons";
editToolbar.append(buttons);
if (this.#uiManager.hasCommentManager()) {
this.#makeButton("commentButton", `pdfjs-comment-floating-button`, "pdfjs-comment-floating-button-label", () => {
this.#uiManager.commentSelection("floating_button");
});
}
this.#makeButton("highlightButton", `pdfjs-highlight-floating-button1`, "pdfjs-highlight-floating-button-label", () => {
this.#uiManager.highlightSelection("floating_button");
});
return editToolbar;
}
#getLastPoint(boxes, isLTR) {
let lastY = 0;
let lastX = 0;
for (const box of boxes) {
const y4 = box.y + box.height;
if (y4 < lastY) {
continue;
}
const x2 = box.x + (isLTR ? box.width : 0);
if (y4 > lastY) {
lastX = x2;
lastY = y4;
continue;
}
if (isLTR) {
if (x2 > lastX) {
lastX = x2;
}
} else if (x2 < lastX) {
lastX = x2;
}
}
return [isLTR ? 1 - lastX : lastX, lastY];
}
show(parent, boxes, isLTR) {
const [x2, y4] = this.#getLastPoint(boxes, isLTR);
const {
style
} = this.#toolbar ||= this.#render();
parent.append(this.#toolbar);
style.insetInlineEnd = `${100 * x2}%`;
style.top = `calc(${100 * y4}% + var(--editor-toolbar-vert-offset))`;
}
hide() {
this.#toolbar.remove();
}
#makeButton(buttonClass, l10nId, labelL10nId, clickHandler) {
const button = document.createElement("button");
button.classList.add("basic", buttonClass);
button.tabIndex = 0;
button.setAttribute("data-l10n-id", l10nId);
const span = document.createElement("span");
button.append(span);
span.className = "visuallyHidden";
span.setAttribute("data-l10n-id", labelL10nId);
const signal = this.#uiManager._signal;
if (signal instanceof AbortSignal && !signal.aborted) {
button.addEventListener("contextmenu", noContextMenu, {
signal
});
button.addEventListener("click", clickHandler, {
signal
});
}
this.#buttons.append(button);
}
};
CurrentPointers = class _CurrentPointers {
static #pointerId = NaN;
static #pointerIds = null;
static #moveTimestamp = NaN;
static #pointerType = null;
static initializeAndAddPointerId(pointerId) {
(_CurrentPointers.#pointerIds ||= /* @__PURE__ */ new Set()).add(pointerId);
}
static setPointer(pointerType, pointerId) {
_CurrentPointers.#pointerId ||= pointerId;
_CurrentPointers.#pointerType ??= pointerType;
}
static setTimeStamp(timeStamp) {
_CurrentPointers.#moveTimestamp = timeStamp;
}
static isSamePointerId(pointerId) {
return _CurrentPointers.#pointerId === pointerId;
}
static isSamePointerIdOrRemove(pointerId) {
if (_CurrentPointers.#pointerId === pointerId) {
return true;
}
_CurrentPointers.#pointerIds?.delete(pointerId);
return false;
}
static isSamePointerType(pointerType) {
return _CurrentPointers.#pointerType === pointerType;
}
static isInitializedAndDifferentPointerType(pointerType) {
return _CurrentPointers.#pointerType !== null && !_CurrentPointers.isSamePointerType(pointerType);
}
static isSameTimeStamp(timeStamp) {
return _CurrentPointers.#moveTimestamp === timeStamp;
}
static isUsingMultiplePointers() {
return _CurrentPointers.#pointerIds?.size >= 1;
}
static clearPointerType() {
_CurrentPointers.#pointerType = null;
}
static clearPointerIds() {
_CurrentPointers.#pointerId = NaN;
_CurrentPointers.#pointerIds = null;
}
static clearTimeStamp() {
_CurrentPointers.#moveTimestamp = NaN;
}
};
IdManager = class {
#id = 0;
get id() {
return `${AnnotationEditorPrefix}${this.#id++}`;
}
};
ImageManager = class _ImageManager {
#baseId = getUuid();
#id = 0;
#cache = null;
static get _isSVGFittingCanvas() {
const svg = `data:image/svg+xml;charset=UTF-8,`;
const canvas = new OffscreenCanvas(1, 3);
const ctx = canvas.getContext("2d", {
willReadFrequently: true
});
const image = new Image();
image.src = svg;
const promise = image.decode().then(() => {
ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);
return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;
});
return shadow(this, "_isSVGFittingCanvas", promise);
}
async #get(key, rawData) {
this.#cache ||= /* @__PURE__ */ new Map();
let data = this.#cache.get(key);
if (data === null) {
return null;
}
if (data?.bitmap) {
data.refCounter += 1;
return data;
}
try {
data ||= {
bitmap: null,
id: `image_${this.#baseId}_${this.#id++}`,
refCounter: 0,
isSvg: false
};
let image;
if (typeof rawData === "string") {
data.url = rawData;
image = await fetchData(rawData, "blob");
} else if (rawData instanceof File) {
image = data.file = rawData;
} else if (rawData instanceof Blob) {
image = rawData;
}
if (image.type === "image/svg+xml") {
const mustRemoveAspectRatioPromise = _ImageManager._isSVGFittingCanvas;
const fileReader = new FileReader();
const imageElement = new Image();
const imagePromise = new Promise((resolve2, reject) => {
imageElement.onload = () => {
data.bitmap = imageElement;
data.isSvg = true;
resolve2();
};
fileReader.onload = async () => {
const url = data.svgUrl = fileReader.result;
imageElement.src = await mustRemoveAspectRatioPromise ? `${url}#svgView(preserveAspectRatio(none))` : url;
};
imageElement.onerror = fileReader.onerror = reject;
});
fileReader.readAsDataURL(image);
await imagePromise;
} else {
data.bitmap = await createImageBitmap(image);
}
data.refCounter = 1;
} catch (e9) {
warn(e9);
data = null;
}
this.#cache.set(key, data);
if (data) {
this.#cache.set(data.id, data);
}
return data;
}
async getFromFile(file) {
const {
lastModified,
name,
size,
type
} = file;
return this.#get(`${lastModified}_${name}_${size}_${type}`, file);
}
async getFromUrl(url) {
return this.#get(url, url);
}
async getFromBlob(id, blobPromise) {
const blob = await blobPromise;
return this.#get(id, blob);
}
async getFromId(id) {
this.#cache ||= /* @__PURE__ */ new Map();
const data = this.#cache.get(id);
if (!data) {
return null;
}
if (data.bitmap) {
data.refCounter += 1;
return data;
}
if (data.file) {
return this.getFromFile(data.file);
}
if (data.blobPromise) {
const {
blobPromise
} = data;
delete data.blobPromise;
return this.getFromBlob(data.id, blobPromise);
}
return this.getFromUrl(data.url);
}
getFromCanvas(id, canvas) {
this.#cache ||= /* @__PURE__ */ new Map();
let data = this.#cache.get(id);
if (data?.bitmap) {
data.refCounter += 1;
return data;
}
const offscreen = new OffscreenCanvas(canvas.width, canvas.height);
const ctx = offscreen.getContext("2d");
ctx.drawImage(canvas, 0, 0);
data = {
bitmap: offscreen.transferToImageBitmap(),
id: `image_${this.#baseId}_${this.#id++}`,
refCounter: 1,
isSvg: false
};
this.#cache.set(id, data);
this.#cache.set(data.id, data);
return data;
}
getSvgUrl(id) {
const data = this.#cache.get(id);
if (!data?.isSvg) {
return null;
}
return data.svgUrl;
}
deleteId(id) {
this.#cache ||= /* @__PURE__ */ new Map();
const data = this.#cache.get(id);
if (!data) {
return;
}
data.refCounter -= 1;
if (data.refCounter !== 0) {
return;
}
const {
bitmap
} = data;
if (!data.url && !data.file) {
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
const ctx = canvas.getContext("bitmaprenderer");
ctx.transferFromImageBitmap(bitmap);
data.blobPromise = canvas.convertToBlob();
}
bitmap.close?.();
data.bitmap = null;
}
isValidId(id) {
return id.startsWith(`image_${this.#baseId}_`);
}
};
CommandManager = class {
#commands = [];
#locked = false;
#maxSize;
#position = -1;
constructor(maxSize = 128) {
this.#maxSize = maxSize;
}
add({
cmd,
undo,
post: post2,
mustExec,
type = NaN,
overwriteIfSameType = false,
keepUndo = false
}) {
if (mustExec) {
cmd();
}
if (this.#locked) {
return;
}
const save = {
cmd,
undo,
post: post2,
type
};
if (this.#position === -1) {
if (this.#commands.length > 0) {
this.#commands.length = 0;
}
this.#position = 0;
this.#commands.push(save);
return;
}
if (overwriteIfSameType && this.#commands[this.#position].type === type) {
if (keepUndo) {
save.undo = this.#commands[this.#position].undo;
}
this.#commands[this.#position] = save;
return;
}
const next = this.#position + 1;
if (next === this.#maxSize) {
this.#commands.splice(0, 1);
} else {
this.#position = next;
if (next < this.#commands.length) {
this.#commands.splice(next);
}
}
this.#commands.push(save);
}
undo() {
if (this.#position === -1) {
return;
}
this.#locked = true;
const {
undo,
post: post2
} = this.#commands[this.#position];
undo();
post2?.();
this.#locked = false;
this.#position -= 1;
}
redo() {
if (this.#position < this.#commands.length - 1) {
this.#position += 1;
this.#locked = true;
const {
cmd,
post: post2
} = this.#commands[this.#position];
cmd();
post2?.();
this.#locked = false;
}
}
hasSomethingToUndo() {
return this.#position !== -1;
}
hasSomethingToRedo() {
return this.#position < this.#commands.length - 1;
}
cleanType(type) {
if (this.#position === -1) {
return;
}
for (let i7 = this.#position; i7 >= 0; i7--) {
if (this.#commands[i7].type !== type) {
this.#commands.splice(i7 + 1, this.#position - i7);
this.#position = i7;
return;
}
}
this.#commands.length = 0;
this.#position = -1;
}
destroy() {
this.#commands = null;
}
};
KeyboardManager = class {
constructor(callbacks) {
this.buffer = [];
this.callbacks = /* @__PURE__ */ new Map();
this.allKeys = /* @__PURE__ */ new Set();
const {
isMac
} = util_FeatureTest.platform;
for (const [keys2, callback2, options = {}] of callbacks) {
for (const key of keys2) {
const isMacKey = key.startsWith("mac+");
if (isMac && isMacKey) {
this.callbacks.set(key.slice(4), {
callback: callback2,
options
});
this.allKeys.add(key.split("+").at(-1));
} else if (!isMac && !isMacKey) {
this.callbacks.set(key, {
callback: callback2,
options
});
this.allKeys.add(key.split("+").at(-1));
}
}
}
}
#serialize(event) {
if (event.altKey) {
this.buffer.push("alt");
}
if (event.ctrlKey) {
this.buffer.push("ctrl");
}
if (event.metaKey) {
this.buffer.push("meta");
}
if (event.shiftKey) {
this.buffer.push("shift");
}
this.buffer.push(event.key);
const str2 = this.buffer.join("+");
this.buffer.length = 0;
return str2;
}
exec(self2, event) {
if (!this.allKeys.has(event.key)) {
return;
}
const info2 = this.callbacks.get(this.#serialize(event));
if (!info2) {
return;
}
const {
callback: callback2,
options: {
bubbles = false,
args = [],
checker = null
}
} = info2;
if (checker && !checker(self2, event)) {
return;
}
callback2.bind(self2, ...args, event)();
if (!bubbles) {
stopEvent(event);
}
}
};
ColorManager = class _ColorManager {
static _colorsMapping = /* @__PURE__ */ new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
get _colors() {
const colors2 = /* @__PURE__ */ new Map([["CanvasText", null], ["Canvas", null]]);
getColorValues(colors2);
return shadow(this, "_colors", colors2);
}
convert(color2) {
const rgb = getRGB(color2);
if (!window.matchMedia("(forced-colors: active)").matches) {
return rgb;
}
for (const [name, RGB] of this._colors) {
if (RGB.every((x2, i7) => x2 === rgb[i7])) {
return _ColorManager._colorsMapping.get(name);
}
}
return rgb;
}
getHexCode(name) {
const rgb = this._colors.get(name);
if (!rgb) {
return name;
}
return Util.makeHexColor(...rgb);
}
};
AnnotationEditorUIManager = class _AnnotationEditorUIManager {
#abortController = new AbortController();
#activeEditor = null;
#allEditableAnnotations = null;
#allEditors = /* @__PURE__ */ new Map();
#allLayers = /* @__PURE__ */ new Map();
#altTextManager = null;
#annotationStorage = null;
#changedExistingAnnotations = null;
#commandManager = new CommandManager();
#commentManager = null;
#copyPasteAC = null;
#currentDrawingSession = null;
#currentPageIndex = 0;
#deletedAnnotationsElementIds = /* @__PURE__ */ new Set();
#draggingEditors = null;
#editorTypes = null;
#editorsToRescale = /* @__PURE__ */ new Set();
_editorUndoBar = null;
#enableHighlightFloatingButton = false;
#enableUpdatedAddImage = false;
#enableNewAltTextWhenAddingImage = false;
#filterFactory = null;
#focusMainContainerTimeoutId = null;
#focusManagerAC = null;
#highlightColors = null;
#highlightWhenShiftUp = false;
#floatingToolbar = null;
#idManager = new IdManager();
#isEnabled = false;
#isPointerDown = false;
#isWaiting = false;
#keyboardManagerAC = null;
#lastActiveElement = null;
#mainHighlightColorPicker = null;
#missingCanvases = null;
#mlManager = null;
#mode = AnnotationEditorType.NONE;
#selectedEditors = /* @__PURE__ */ new Set();
#selectedTextNode = null;
#signatureManager = null;
#pageColors = null;
#showAllStates = null;
#pdfDocument = null;
#previousStates = {
isEditing: false,
isEmpty: true,
hasSomethingToUndo: false,
hasSomethingToRedo: false,
hasSelectedEditor: false,
hasSelectedText: false
};
#translation = [0, 0];
#translationTimeoutId = null;
#container = null;
#viewer = null;
#viewerAlert = null;
#updateModeCapability = null;
static TRANSLATE_SMALL = 1;
static TRANSLATE_BIG = 10;
static get _keyboardManager() {
const proto = _AnnotationEditorUIManager.prototype;
const arrowChecker = (self2) => self2.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self2.hasSomethingToControl();
const textInputChecker = (_self, {
target: el
}) => {
if (el instanceof HTMLInputElement) {
const {
type
} = el;
return type !== "text" && type !== "number";
}
return true;
};
const small = this.TRANSLATE_SMALL;
const big = this.TRANSLATE_BIG;
return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, {
checker: textInputChecker
}], [["ctrl+z", "mac+meta+z"], proto.undo, {
checker: textInputChecker
}], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, {
checker: textInputChecker
}], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, {
checker: textInputChecker
}], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, {
checker: (self2, {
target: el
}) => !(el instanceof HTMLButtonElement) && self2.#container.contains(el) && !self2.isEnterHandled
}], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, {
checker: (self2, {
target: el
}) => !(el instanceof HTMLButtonElement) && self2.#container.contains(document.activeElement)
}], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, {
args: [-small, 0],
checker: arrowChecker
}], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, {
args: [-big, 0],
checker: arrowChecker
}], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, {
args: [small, 0],
checker: arrowChecker
}], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, {
args: [big, 0],
checker: arrowChecker
}], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, {
args: [0, -small],
checker: arrowChecker
}], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, {
args: [0, -big],
checker: arrowChecker
}], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, {
args: [0, small],
checker: arrowChecker
}], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, {
args: [0, big],
checker: arrowChecker
}]]));
}
constructor(container, viewer, viewerAlert, altTextManager, commentManager, signatureManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager, editorUndoBar, supportsPinchToZoom) {
const signal = this._signal = this.#abortController.signal;
this.#container = container;
this.#viewer = viewer;
this.#viewerAlert = viewerAlert;
this.#altTextManager = altTextManager;
this.#commentManager = commentManager;
this.#signatureManager = signatureManager;
this.#pdfDocument = pdfDocument;
this._eventBus = eventBus;
eventBus._on("editingaction", this.onEditingAction.bind(this), {
signal
});
eventBus._on("pagechanging", this.onPageChanging.bind(this), {
signal
});
eventBus._on("scalechanging", this.onScaleChanging.bind(this), {
signal
});
eventBus._on("rotationchanging", this.onRotationChanging.bind(this), {
signal
});
eventBus._on("setpreference", this.onSetPreference.bind(this), {
signal
});
eventBus._on("switchannotationeditorparams", (evt) => this.updateParams(evt.type, evt.value), {
signal
});
window.addEventListener("pointerdown", () => {
this.#isPointerDown = true;
}, {
capture: true,
signal
});
window.addEventListener("pointerup", () => {
this.#isPointerDown = false;
}, {
capture: true,
signal
});
this.#addSelectionListener();
this.#addDragAndDropListeners();
this.#addKeyboardManager();
this.#annotationStorage = pdfDocument.annotationStorage;
this.#filterFactory = pdfDocument.filterFactory;
this.#pageColors = pageColors;
this.#highlightColors = highlightColors || null;
this.#enableHighlightFloatingButton = enableHighlightFloatingButton;
this.#enableUpdatedAddImage = enableUpdatedAddImage;
this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage;
this.#mlManager = mlManager || null;
this.viewParameters = {
realScale: PixelsPerInch.PDF_TO_CSS_UNITS,
rotation: 0
};
this.isShiftKeyDown = false;
this._editorUndoBar = editorUndoBar || null;
this._supportsPinchToZoom = supportsPinchToZoom !== false;
commentManager?.setSidebarUiManager(this);
}
destroy() {
this.#updateModeCapability?.resolve();
this.#updateModeCapability = null;
this.#abortController?.abort();
this.#abortController = null;
this._signal = null;
for (const layer of this.#allLayers.values()) {
layer.destroy();
}
this.#allLayers.clear();
this.#allEditors.clear();
this.#editorsToRescale.clear();
this.#missingCanvases?.clear();
this.#activeEditor = null;
this.#selectedEditors.clear();
this.#commandManager.destroy();
this.#altTextManager?.destroy();
this.#commentManager?.destroy();
this.#signatureManager?.destroy();
this.#floatingToolbar?.hide();
this.#floatingToolbar = null;
this.#mainHighlightColorPicker?.destroy();
this.#mainHighlightColorPicker = null;
this.#allEditableAnnotations = null;
if (this.#focusMainContainerTimeoutId) {
clearTimeout(this.#focusMainContainerTimeoutId);
this.#focusMainContainerTimeoutId = null;
}
if (this.#translationTimeoutId) {
clearTimeout(this.#translationTimeoutId);
this.#translationTimeoutId = null;
}
this._editorUndoBar?.destroy();
this.#pdfDocument = null;
}
combinedSignal(ac) {
return AbortSignal.any([this._signal, ac.signal]);
}
get mlManager() {
return this.#mlManager;
}
get useNewAltTextFlow() {
return this.#enableUpdatedAddImage;
}
get useNewAltTextWhenAddingImage() {
return this.#enableNewAltTextWhenAddingImage;
}
get hcmFilter() {
return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none");
}
get direction() {
return shadow(this, "direction", getComputedStyle(this.#container).direction);
}
get _highlightColors() {
return shadow(this, "_highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map((pair) => {
pair = pair.split("=").map((x2) => x2.trim());
pair[1] = pair[1].toUpperCase();
return pair;
})) : null);
}
get highlightColors() {
const {
_highlightColors
} = this;
if (!_highlightColors) {
return shadow(this, "highlightColors", null);
}
const map3 = /* @__PURE__ */ new Map();
const hasHCM = !!this.#pageColors;
for (const [name, color2] of _highlightColors) {
const isNameForHCM = name.endsWith("_HCM");
if (hasHCM && isNameForHCM) {
map3.set(name.replace("_HCM", ""), color2);
continue;
}
if (!hasHCM && !isNameForHCM) {
map3.set(name, color2);
}
}
return shadow(this, "highlightColors", map3);
}
get highlightColorNames() {
return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, (e9) => e9.reverse())) : null);
}
getNonHCMColor(color2) {
if (!this._highlightColors) {
return color2;
}
const colorName2 = this.highlightColorNames.get(color2);
return this._highlightColors.get(colorName2) || color2;
}
getNonHCMColorName(color2) {
return this.highlightColorNames.get(color2) || color2;
}
setCurrentDrawingSession(layer) {
if (layer) {
this.unselectAll();
this.disableUserSelect(true);
} else {
this.disableUserSelect(false);
}
this.#currentDrawingSession = layer;
}
setMainHighlightColorPicker(colorPicker) {
this.#mainHighlightColorPicker = colorPicker;
}
editAltText(editor, firstTime = false) {
this.#altTextManager?.editAltText(this, editor, firstTime);
}
hasCommentManager() {
return !!this.#commentManager;
}
editComment(editor, posX, posY, options) {
this.#commentManager?.showDialog(this, editor, posX, posY, options);
}
selectComment(pageIndex, uid2) {
const layer = this.#allLayers.get(pageIndex);
const editor = layer?.getEditorByUID(uid2);
editor?.toggleComment(true, true);
}
updateComment(editor) {
this.#commentManager?.updateComment(editor.getData());
}
updatePopupColor(editor) {
this.#commentManager?.updatePopupColor(editor);
}
removeComment(editor) {
this.#commentManager?.removeComments([editor.uid]);
}
toggleComment(editor, isSelected, visibility = void 0) {
this.#commentManager?.toggleCommentPopup(editor, isSelected, visibility);
}
makeCommentColor(color2, opacity) {
return color2 && this.#commentManager?.makeCommentColor(color2, opacity) || null;
}
getCommentDialogElement() {
return this.#commentManager?.dialogElement || null;
}
async waitForEditorsRendered(pageNumber) {
if (this.#allLayers.has(pageNumber - 1)) {
return;
}
const {
resolve: resolve2,
promise
} = Promise.withResolvers();
const onEditorsRendered = (evt) => {
if (evt.pageNumber === pageNumber) {
this._eventBus._off("editorsrendered", onEditorsRendered);
resolve2();
}
};
this._eventBus.on("editorsrendered", onEditorsRendered);
await promise;
}
getSignature(editor) {
this.#signatureManager?.getSignature({
uiManager: this,
editor
});
}
get signatureManager() {
return this.#signatureManager;
}
switchToMode(mode, callback2) {
this._eventBus.on("annotationeditormodechanged", callback2, {
once: true,
signal: this._signal
});
this._eventBus.dispatch("showannotationeditorui", {
source: this,
mode
});
}
setPreference(name, value) {
this._eventBus.dispatch("setpreference", {
source: this,
name,
value
});
}
onSetPreference({
name,
value
}) {
switch (name) {
case "enableNewAltTextWhenAddingImage":
this.#enableNewAltTextWhenAddingImage = value;
break;
}
}
onPageChanging({
pageNumber
}) {
this.#currentPageIndex = pageNumber - 1;
}
focusMainContainer() {
this.#container.focus();
}
findParent(x2, y4) {
for (const layer of this.#allLayers.values()) {
const {
x: layerX,
y: layerY,
width,
height
} = layer.div.getBoundingClientRect();
if (x2 >= layerX && x2 <= layerX + width && y4 >= layerY && y4 <= layerY + height) {
return layer;
}
}
return null;
}
disableUserSelect(value = false) {
this.#viewer.classList.toggle("noUserSelect", value);
}
addShouldRescale(editor) {
this.#editorsToRescale.add(editor);
}
removeShouldRescale(editor) {
this.#editorsToRescale.delete(editor);
}
onScaleChanging({
scale
}) {
this.commitOrRemove();
this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;
for (const editor of this.#editorsToRescale) {
editor.onScaleChanging();
}
this.#currentDrawingSession?.onScaleChanging();
}
onRotationChanging({
pagesRotation
}) {
this.commitOrRemove();
this.viewParameters.rotation = pagesRotation;
}
#getAnchorElementForSelection({
anchorNode
}) {
return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode;
}
#getLayerForTextLayer(textLayer) {
const {
currentLayer
} = this;
if (currentLayer.hasTextLayer(textLayer)) {
return currentLayer;
}
for (const layer of this.#allLayers.values()) {
if (layer.hasTextLayer(textLayer)) {
return layer;
}
}
return null;
}
highlightSelection(methodOfCreation = "", comment = false) {
const selection = document.getSelection();
if (!selection || selection.isCollapsed) {
return;
}
const {
anchorNode,
anchorOffset,
focusNode,
focusOffset
} = selection;
const text3 = selection.toString();
const anchorElement = this.#getAnchorElementForSelection(selection);
const textLayer = anchorElement.closest(".textLayer");
const boxes = this.getSelectionBoxes(textLayer);
if (!boxes) {
return;
}
selection.empty();
const layer = this.#getLayerForTextLayer(textLayer);
const isNoneMode = this.#mode === AnnotationEditorType.NONE;
const callback2 = () => {
const editor = layer?.createAndAddNewEditor({
x: 0,
y: 0
}, false, {
methodOfCreation,
boxes,
anchorNode,
anchorOffset,
focusNode,
focusOffset,
text: text3
});
if (isNoneMode) {
this.showAllEditors("highlight", true, true);
}
if (comment) {
editor?.editComment();
}
};
if (isNoneMode) {
this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback2);
return;
}
callback2();
}
commentSelection(methodOfCreation = "") {
this.highlightSelection(methodOfCreation, true);
}
#displayFloatingToolbar() {
const selection = document.getSelection();
if (!selection || selection.isCollapsed) {
return;
}
const anchorElement = this.#getAnchorElementForSelection(selection);
const textLayer = anchorElement.closest(".textLayer");
const boxes = this.getSelectionBoxes(textLayer);
if (!boxes) {
return;
}
this.#floatingToolbar ||= new FloatingToolbar(this);
this.#floatingToolbar.show(textLayer, boxes, this.direction === "ltr");
}
getAndRemoveDataFromAnnotationStorage(annotationId) {
if (!this.#annotationStorage) {
return null;
}
const key = `${AnnotationEditorPrefix}${annotationId}`;
const storedValue = this.#annotationStorage.getRawValue(key);
if (storedValue) {
this.#annotationStorage.remove(key);
}
return storedValue;
}
addToAnnotationStorage(editor) {
if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
this.#annotationStorage.setValue(editor.id, editor);
}
}
a11yAlert(messageId, args = null) {
const viewerAlert = this.#viewerAlert;
if (!viewerAlert) {
return;
}
viewerAlert.setAttribute("data-l10n-id", messageId);
if (args) {
viewerAlert.setAttribute("data-l10n-args", JSON.stringify(args));
} else {
viewerAlert.removeAttribute("data-l10n-args");
}
}
#selectionChange() {
const selection = document.getSelection();
if (!selection || selection.isCollapsed) {
if (this.#selectedTextNode) {
this.#floatingToolbar?.hide();
this.#selectedTextNode = null;
this.#dispatchUpdateStates({
hasSelectedText: false
});
}
return;
}
const {
anchorNode
} = selection;
if (anchorNode === this.#selectedTextNode) {
return;
}
const anchorElement = this.#getAnchorElementForSelection(selection);
const textLayer = anchorElement.closest(".textLayer");
if (!textLayer) {
if (this.#selectedTextNode) {
this.#floatingToolbar?.hide();
this.#selectedTextNode = null;
this.#dispatchUpdateStates({
hasSelectedText: false
});
}
return;
}
this.#floatingToolbar?.hide();
this.#selectedTextNode = anchorNode;
this.#dispatchUpdateStates({
hasSelectedText: true
});
if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) {
return;
}
if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
this.showAllEditors("highlight", true, true);
}
this.#highlightWhenShiftUp = this.isShiftKeyDown;
if (!this.isShiftKeyDown) {
const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null;
activeLayer?.toggleDrawing();
if (this.#isPointerDown) {
const ac = new AbortController();
const signal = this.combinedSignal(ac);
const pointerup = (e9) => {
if (e9.type === "pointerup" && e9.button !== 0) {
return;
}
ac.abort();
activeLayer?.toggleDrawing(true);
if (e9.type === "pointerup") {
this.#onSelectEnd("main_toolbar");
}
};
window.addEventListener("pointerup", pointerup, {
signal
});
window.addEventListener("blur", pointerup, {
signal
});
} else {
activeLayer?.toggleDrawing(true);
this.#onSelectEnd("main_toolbar");
}
}
}
#onSelectEnd(methodOfCreation = "") {
if (this.#mode === AnnotationEditorType.HIGHLIGHT) {
this.highlightSelection(methodOfCreation);
} else if (this.#enableHighlightFloatingButton) {
this.#displayFloatingToolbar();
}
}
#addSelectionListener() {
document.addEventListener("selectionchange", this.#selectionChange.bind(this), {
signal: this._signal
});
}
#addFocusManager() {
if (this.#focusManagerAC) {
return;
}
this.#focusManagerAC = new AbortController();
const signal = this.combinedSignal(this.#focusManagerAC);
window.addEventListener("focus", this.focus.bind(this), {
signal
});
window.addEventListener("blur", this.blur.bind(this), {
signal
});
}
#removeFocusManager() {
this.#focusManagerAC?.abort();
this.#focusManagerAC = null;
}
blur() {
this.isShiftKeyDown = false;
if (this.#highlightWhenShiftUp) {
this.#highlightWhenShiftUp = false;
this.#onSelectEnd("main_toolbar");
}
if (!this.hasSelection) {
return;
}
const {
activeElement
} = document;
for (const editor of this.#selectedEditors) {
if (editor.div.contains(activeElement)) {
this.#lastActiveElement = [editor, activeElement];
editor._focusEventsAllowed = false;
break;
}
}
}
focus() {
if (!this.#lastActiveElement) {
return;
}
const [lastEditor, lastActiveElement] = this.#lastActiveElement;
this.#lastActiveElement = null;
lastActiveElement.addEventListener("focusin", () => {
lastEditor._focusEventsAllowed = true;
}, {
once: true,
signal: this._signal
});
lastActiveElement.focus();
}
#addKeyboardManager() {
if (this.#keyboardManagerAC) {
return;
}
this.#keyboardManagerAC = new AbortController();
const signal = this.combinedSignal(this.#keyboardManagerAC);
window.addEventListener("keydown", this.keydown.bind(this), {
signal
});
window.addEventListener("keyup", this.keyup.bind(this), {
signal
});
}
#removeKeyboardManager() {
this.#keyboardManagerAC?.abort();
this.#keyboardManagerAC = null;
}
#addCopyPasteListeners() {
if (this.#copyPasteAC) {
return;
}
this.#copyPasteAC = new AbortController();
const signal = this.combinedSignal(this.#copyPasteAC);
document.addEventListener("copy", this.copy.bind(this), {
signal
});
document.addEventListener("cut", this.cut.bind(this), {
signal
});
document.addEventListener("paste", this.paste.bind(this), {
signal
});
}
#removeCopyPasteListeners() {
this.#copyPasteAC?.abort();
this.#copyPasteAC = null;
}
#addDragAndDropListeners() {
const signal = this._signal;
document.addEventListener("dragover", this.dragOver.bind(this), {
signal
});
document.addEventListener("drop", this.drop.bind(this), {
signal
});
}
addEditListeners() {
this.#addKeyboardManager();
this.setEditingState(true);
}
removeEditListeners() {
this.#removeKeyboardManager();
this.setEditingState(false);
}
dragOver(event) {
for (const {
type
} of event.dataTransfer.items) {
for (const editorType of this.#editorTypes) {
if (editorType.isHandlingMimeForPasting(type)) {
event.dataTransfer.dropEffect = "copy";
event.preventDefault();
return;
}
}
}
}
drop(event) {
for (const item of event.dataTransfer.items) {
for (const editorType of this.#editorTypes) {
if (editorType.isHandlingMimeForPasting(item.type)) {
editorType.paste(item, this.currentLayer);
event.preventDefault();
return;
}
}
}
}
copy(event) {
event.preventDefault();
this.#activeEditor?.commitOrRemove();
if (!this.hasSelection) {
return;
}
const editors = [];
for (const editor of this.#selectedEditors) {
const serialized = editor.serialize(true);
if (serialized) {
editors.push(serialized);
}
}
if (editors.length === 0) {
return;
}
event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
}
cut(event) {
this.copy(event);
this.delete();
}
async paste(event) {
event.preventDefault();
const {
clipboardData
} = event;
for (const item of clipboardData.items) {
for (const editorType of this.#editorTypes) {
if (editorType.isHandlingMimeForPasting(item.type)) {
editorType.paste(item, this.currentLayer);
return;
}
}
}
let data = clipboardData.getData("application/pdfjs");
if (!data) {
return;
}
try {
data = JSON.parse(data);
} catch (ex) {
warn(`paste: "${ex.message}".`);
return;
}
if (!Array.isArray(data)) {
return;
}
this.unselectAll();
const layer = this.currentLayer;
try {
const newEditors = [];
for (const editor of data) {
const deserializedEditor = await layer.deserialize(editor);
if (!deserializedEditor) {
return;
}
newEditors.push(deserializedEditor);
}
const cmd = () => {
for (const editor of newEditors) {
this.#addEditorToLayer(editor);
}
this.#selectEditors(newEditors);
};
const undo = () => {
for (const editor of newEditors) {
editor.remove();
}
};
this.addCommands({
cmd,
undo,
mustExec: true
});
} catch (ex) {
warn(`paste: "${ex.message}".`);
}
}
keydown(event) {
if (!this.isShiftKeyDown && event.key === "Shift") {
this.isShiftKeyDown = true;
}
if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) {
_AnnotationEditorUIManager._keyboardManager.exec(this, event);
}
}
keyup(event) {
if (this.isShiftKeyDown && event.key === "Shift") {
this.isShiftKeyDown = false;
if (this.#highlightWhenShiftUp) {
this.#highlightWhenShiftUp = false;
this.#onSelectEnd("main_toolbar");
}
}
}
onEditingAction({
name
}) {
switch (name) {
case "undo":
case "redo":
case "delete":
case "selectAll":
this[name]();
break;
case "highlightSelection":
this.highlightSelection("context_menu");
break;
case "commentSelection":
this.commentSelection("context_menu");
break;
}
}
#dispatchUpdateStates(details) {
const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
if (hasChanged) {
this._eventBus.dispatch("annotationeditorstateschanged", {
source: this,
details: Object.assign(this.#previousStates, details)
});
if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) {
this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]);
}
}
}
#dispatchUpdateUI(details) {
this._eventBus.dispatch("annotationeditorparamschanged", {
source: this,
details
});
}
setEditingState(isEditing) {
if (isEditing) {
this.#addFocusManager();
this.#addCopyPasteListeners();
this.#dispatchUpdateStates({
isEditing: this.#mode !== AnnotationEditorType.NONE,
isEmpty: this.#isEmpty(),
hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
hasSelectedEditor: false
});
} else {
this.#removeFocusManager();
this.#removeCopyPasteListeners();
this.#dispatchUpdateStates({
isEditing: false
});
this.disableUserSelect(false);
}
}
registerEditorTypes(types2) {
if (this.#editorTypes) {
return;
}
this.#editorTypes = types2;
for (const editorType of this.#editorTypes) {
this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
}
}
getId() {
return this.#idManager.id;
}
get currentLayer() {
return this.#allLayers.get(this.#currentPageIndex);
}
getLayer(pageIndex) {
return this.#allLayers.get(pageIndex);
}
get currentPageIndex() {
return this.#currentPageIndex;
}
addLayer(layer) {
this.#allLayers.set(layer.pageIndex, layer);
if (this.#isEnabled) {
layer.enable();
} else {
layer.disable();
}
}
removeLayer(layer) {
this.#allLayers.delete(layer.pageIndex);
}
async updateMode(mode, editId = null, isFromKeyboard = false, mustEnterInEditMode = false, editComment = false) {
if (this.#mode === mode) {
return;
}
if (this.#updateModeCapability) {
await this.#updateModeCapability.promise;
if (!this.#updateModeCapability) {
return;
}
}
this.#updateModeCapability = Promise.withResolvers();
this.#currentDrawingSession?.commitOrRemove();
if (this.#mode === AnnotationEditorType.POPUP) {
this.#commentManager?.hideSidebar();
}
this.#commentManager?.destroyPopup();
this.#mode = mode;
if (mode === AnnotationEditorType.NONE) {
this.setEditingState(false);
this.#disableAll();
for (const editor of this.#allEditors.values()) {
editor.hideStandaloneCommentButton();
}
this._editorUndoBar?.hide();
this.toggleComment(null);
this.#updateModeCapability.resolve();
return;
}
for (const editor of this.#allEditors.values()) {
editor.addStandaloneCommentButton();
}
if (mode === AnnotationEditorType.SIGNATURE) {
await this.#signatureManager?.loadSignatures();
}
this.setEditingState(true);
await this.#enableAll();
this.unselectAll();
for (const layer of this.#allLayers.values()) {
layer.updateMode(mode);
}
if (mode === AnnotationEditorType.POPUP) {
this.#allEditableAnnotations ||= await this.#pdfDocument.getAnnotationsByType(new Set(this.#editorTypes.map((editorClass) => editorClass._editorType)));
const elementIds = /* @__PURE__ */ new Set();
const allComments = [];
for (const editor of this.#allEditors.values()) {
const {
annotationElementId,
hasComment,
deleted
} = editor;
if (annotationElementId) {
elementIds.add(annotationElementId);
}
if (hasComment && !deleted) {
allComments.push(editor.getData());
}
}
for (const annotation of this.#allEditableAnnotations) {
const {
id,
popupRef,
contentsObj
} = annotation;
if (popupRef && contentsObj?.str && !elementIds.has(id) && !this.#deletedAnnotationsElementIds.has(id)) {
allComments.push(annotation);
}
}
this.#commentManager?.showSidebar(allComments);
}
if (!editId) {
if (isFromKeyboard) {
this.addNewEditorFromKeyboard();
}
this.#updateModeCapability.resolve();
return;
}
for (const editor of this.#allEditors.values()) {
if (editor.uid === editId) {
this.setSelected(editor);
if (editComment) {
editor.editComment();
} else if (mustEnterInEditMode) {
editor.enterInEditMode();
} else {
editor.focus();
}
} else {
editor.unselect();
}
}
this.#updateModeCapability.resolve();
}
addNewEditorFromKeyboard() {
if (this.currentLayer.canCreateNewEmptyEditor()) {
this.currentLayer.addNewEditor();
}
}
updateToolbar(options) {
if (options.mode === this.#mode) {
return;
}
this._eventBus.dispatch("switchannotationeditormode", {
source: this,
...options
});
}
updateParams(type, value) {
if (!this.#editorTypes) {
return;
}
switch (type) {
case AnnotationEditorParamsType.CREATE:
this.currentLayer.addNewEditor(value);
return;
case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:
this._eventBus.dispatch("reporttelemetry", {
source: this,
details: {
type: "editing",
data: {
type: "highlight",
action: "toggle_visibility"
}
}
});
(this.#showAllStates ||= /* @__PURE__ */ new Map()).set(type, value);
this.showAllEditors("highlight", value);
break;
}
if (this.hasSelection) {
for (const editor of this.#selectedEditors) {
editor.updateParams(type, value);
}
} else {
for (const editorType of this.#editorTypes) {
editorType.updateDefaultParams(type, value);
}
}
}
showAllEditors(type, visible, updateButton = false) {
for (const editor of this.#allEditors.values()) {
if (editor.editorType === type) {
editor.show(visible);
}
}
const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true;
if (state !== visible) {
this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]);
}
}
enableWaiting(mustWait = false) {
if (this.#isWaiting === mustWait) {
return;
}
this.#isWaiting = mustWait;
for (const layer of this.#allLayers.values()) {
if (mustWait) {
layer.disableClick();
} else {
layer.enableClick();
}
layer.div.classList.toggle("waiting", mustWait);
}
}
async #enableAll() {
if (!this.#isEnabled) {
this.#isEnabled = true;
const promises = [];
for (const layer of this.#allLayers.values()) {
promises.push(layer.enable());
}
await Promise.all(promises);
for (const editor of this.#allEditors.values()) {
editor.enable();
}
}
}
#disableAll() {
this.unselectAll();
if (this.#isEnabled) {
this.#isEnabled = false;
for (const layer of this.#allLayers.values()) {
layer.disable();
}
for (const editor of this.#allEditors.values()) {
editor.disable();
}
}
}
*getEditors(pageIndex) {
for (const editor of this.#allEditors.values()) {
if (editor.pageIndex === pageIndex) {
yield editor;
}
}
}
getEditor(id) {
return this.#allEditors.get(id);
}
addEditor(editor) {
this.#allEditors.set(editor.id, editor);
}
removeEditor(editor) {
if (editor.div.contains(document.activeElement)) {
if (this.#focusMainContainerTimeoutId) {
clearTimeout(this.#focusMainContainerTimeoutId);
}
this.#focusMainContainerTimeoutId = setTimeout(() => {
this.focusMainContainer();
this.#focusMainContainerTimeoutId = null;
}, 0);
}
this.#allEditors.delete(editor.id);
if (editor.annotationElementId) {
this.#missingCanvases?.delete(editor.annotationElementId);
}
this.unselect(editor);
if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) {
this.#annotationStorage?.remove(editor.id);
}
}
addDeletedAnnotationElement(editor) {
this.#deletedAnnotationsElementIds.add(editor.annotationElementId);
this.addChangedExistingAnnotation(editor);
editor.deleted = true;
}
isDeletedAnnotationElement(annotationElementId) {
return this.#deletedAnnotationsElementIds.has(annotationElementId);
}
removeDeletedAnnotationElement(editor) {
this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);
this.removeChangedExistingAnnotation(editor);
editor.deleted = false;
}
#addEditorToLayer(editor) {
const layer = this.#allLayers.get(editor.pageIndex);
if (layer) {
layer.addOrRebuild(editor);
} else {
this.addEditor(editor);
this.addToAnnotationStorage(editor);
}
}
setActiveEditor(editor) {
if (this.#activeEditor === editor) {
return;
}
this.#activeEditor = editor;
if (editor) {
this.#dispatchUpdateUI(editor.propertiesToUpdate);
}
}
get #lastSelectedEditor() {
let ed = null;
for (ed of this.#selectedEditors) {
}
return ed;
}
updateUI(editor) {
if (this.#lastSelectedEditor === editor) {
this.#dispatchUpdateUI(editor.propertiesToUpdate);
}
}
updateUIForDefaultProperties(editorType) {
this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
}
toggleSelected(editor) {
if (this.#selectedEditors.has(editor)) {
this.#selectedEditors.delete(editor);
editor.unselect();
this.#dispatchUpdateStates({
hasSelectedEditor: this.hasSelection
});
return;
}
this.#selectedEditors.add(editor);
editor.select();
this.#dispatchUpdateUI(editor.propertiesToUpdate);
this.#dispatchUpdateStates({
hasSelectedEditor: true
});
}
setSelected(editor) {
this.updateToolbar({
mode: editor.mode,
editId: editor.uid
});
this.#currentDrawingSession?.commitOrRemove();
for (const ed of this.#selectedEditors) {
if (ed !== editor) {
ed.unselect();
}
}
this.#selectedEditors.clear();
this.#selectedEditors.add(editor);
editor.select();
this.#dispatchUpdateUI(editor.propertiesToUpdate);
this.#dispatchUpdateStates({
hasSelectedEditor: true
});
}
isSelected(editor) {
return this.#selectedEditors.has(editor);
}
get firstSelectedEditor() {
return this.#selectedEditors.values().next().value;
}
unselect(editor) {
editor.unselect();
this.#selectedEditors.delete(editor);
this.#dispatchUpdateStates({
hasSelectedEditor: this.hasSelection
});
}
get hasSelection() {
return this.#selectedEditors.size !== 0;
}
get isEnterHandled() {
return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled;
}
undo() {
this.#commandManager.undo();
this.#dispatchUpdateStates({
hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
hasSomethingToRedo: true,
isEmpty: this.#isEmpty()
});
this._editorUndoBar?.hide();
}
redo() {
this.#commandManager.redo();
this.#dispatchUpdateStates({
hasSomethingToUndo: true,
hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
isEmpty: this.#isEmpty()
});
}
addCommands(params) {
this.#commandManager.add(params);
this.#dispatchUpdateStates({
hasSomethingToUndo: true,
hasSomethingToRedo: false,
isEmpty: this.#isEmpty()
});
}
cleanUndoStack(type) {
this.#commandManager.cleanType(type);
}
#isEmpty() {
if (this.#allEditors.size === 0) {
return true;
}
if (this.#allEditors.size === 1) {
for (const editor of this.#allEditors.values()) {
return editor.isEmpty();
}
}
return false;
}
delete() {
this.commitOrRemove();
const drawingEditor = this.currentLayer?.endDrawingSession(true);
if (!this.hasSelection && !drawingEditor) {
return;
}
const editors = drawingEditor ? [drawingEditor] : [...this.#selectedEditors];
const cmd = () => {
this._editorUndoBar?.show(undo, editors.length === 1 ? editors[0].editorType : editors.length);
for (const editor of editors) {
editor.remove();
}
};
const undo = () => {
for (const editor of editors) {
this.#addEditorToLayer(editor);
}
};
this.addCommands({
cmd,
undo,
mustExec: true
});
}
commitOrRemove() {
this.#activeEditor?.commitOrRemove();
}
hasSomethingToControl() {
return this.#activeEditor || this.hasSelection;
}
#selectEditors(editors) {
for (const editor of this.#selectedEditors) {
editor.unselect();
}
this.#selectedEditors.clear();
for (const editor of editors) {
if (editor.isEmpty()) {
continue;
}
this.#selectedEditors.add(editor);
editor.select();
}
this.#dispatchUpdateStates({
hasSelectedEditor: this.hasSelection
});
}
selectAll() {
for (const editor of this.#selectedEditors) {
editor.commit();
}
this.#selectEditors(this.#allEditors.values());
}
unselectAll() {
if (this.#activeEditor) {
this.#activeEditor.commitOrRemove();
if (this.#mode !== AnnotationEditorType.NONE) {
return;
}
}
if (this.#currentDrawingSession?.commitOrRemove()) {
return;
}
if (!this.hasSelection) {
return;
}
for (const editor of this.#selectedEditors) {
editor.unselect();
}
this.#selectedEditors.clear();
this.#dispatchUpdateStates({
hasSelectedEditor: false
});
}
translateSelectedEditors(x2, y4, noCommit = false) {
if (!noCommit) {
this.commitOrRemove();
}
if (!this.hasSelection) {
return;
}
this.#translation[0] += x2;
this.#translation[1] += y4;
const [totalX, totalY] = this.#translation;
const editors = [...this.#selectedEditors];
const TIME_TO_WAIT = 1e3;
if (this.#translationTimeoutId) {
clearTimeout(this.#translationTimeoutId);
}
this.#translationTimeoutId = setTimeout(() => {
this.#translationTimeoutId = null;
this.#translation[0] = this.#translation[1] = 0;
this.addCommands({
cmd: () => {
for (const editor of editors) {
if (this.#allEditors.has(editor.id)) {
editor.translateInPage(totalX, totalY);
editor.translationDone();
}
}
},
undo: () => {
for (const editor of editors) {
if (this.#allEditors.has(editor.id)) {
editor.translateInPage(-totalX, -totalY);
editor.translationDone();
}
}
},
mustExec: false
});
}, TIME_TO_WAIT);
for (const editor of editors) {
editor.translateInPage(x2, y4);
editor.translationDone();
}
}
setUpDragSession() {
if (!this.hasSelection) {
return;
}
this.disableUserSelect(true);
this.#draggingEditors = /* @__PURE__ */ new Map();
for (const editor of this.#selectedEditors) {
this.#draggingEditors.set(editor, {
savedX: editor.x,
savedY: editor.y,
savedPageIndex: editor.pageIndex,
newX: 0,
newY: 0,
newPageIndex: -1
});
}
}
endDragSession() {
if (!this.#draggingEditors) {
return false;
}
this.disableUserSelect(false);
const map3 = this.#draggingEditors;
this.#draggingEditors = null;
let mustBeAddedInUndoStack = false;
for (const [{
x: x2,
y: y4,
pageIndex
}, value] of map3) {
value.newX = x2;
value.newY = y4;
value.newPageIndex = pageIndex;
mustBeAddedInUndoStack ||= x2 !== value.savedX || y4 !== value.savedY || pageIndex !== value.savedPageIndex;
}
if (!mustBeAddedInUndoStack) {
return false;
}
const move = (editor, x2, y4, pageIndex) => {
if (this.#allEditors.has(editor.id)) {
const parent = this.#allLayers.get(pageIndex);
if (parent) {
editor._setParentAndPosition(parent, x2, y4);
} else {
editor.pageIndex = pageIndex;
editor.x = x2;
editor.y = y4;
}
}
};
this.addCommands({
cmd: () => {
for (const [editor, {
newX,
newY,
newPageIndex
}] of map3) {
move(editor, newX, newY, newPageIndex);
}
},
undo: () => {
for (const [editor, {
savedX,
savedY,
savedPageIndex
}] of map3) {
move(editor, savedX, savedY, savedPageIndex);
}
},
mustExec: true
});
return true;
}
dragSelectedEditors(tx, ty) {
if (!this.#draggingEditors) {
return;
}
for (const editor of this.#draggingEditors.keys()) {
editor.drag(tx, ty);
}
}
rebuild(editor) {
if (editor.parent === null) {
const parent = this.getLayer(editor.pageIndex);
if (parent) {
parent.changeParent(editor);
parent.addOrRebuild(editor);
} else {
this.addEditor(editor);
this.addToAnnotationStorage(editor);
editor.rebuild();
}
} else {
editor.parent.addOrRebuild(editor);
}
}
get isEditorHandlingKeyboard() {
return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents();
}
isActive(editor) {
return this.#activeEditor === editor;
}
getActive() {
return this.#activeEditor;
}
getMode() {
return this.#mode;
}
isEditingMode() {
return this.#mode !== AnnotationEditorType.NONE;
}
get imageManager() {
return shadow(this, "imageManager", new ImageManager());
}
getSelectionBoxes(textLayer) {
if (!textLayer) {
return null;
}
const selection = document.getSelection();
for (let i7 = 0, ii = selection.rangeCount; i7 < ii; i7++) {
if (!textLayer.contains(selection.getRangeAt(i7).commonAncestorContainer)) {
return null;
}
}
const {
x: layerX,
y: layerY,
width: parentWidth,
height: parentHeight
} = textLayer.getBoundingClientRect();
let rotator;
switch (textLayer.getAttribute("data-main-rotation")) {
case "90":
rotator = (x2, y4, w3, h7) => ({
x: (y4 - layerY) / parentHeight,
y: 1 - (x2 + w3 - layerX) / parentWidth,
width: h7 / parentHeight,
height: w3 / parentWidth
});
break;
case "180":
rotator = (x2, y4, w3, h7) => ({
x: 1 - (x2 + w3 - layerX) / parentWidth,
y: 1 - (y4 + h7 - layerY) / parentHeight,
width: w3 / parentWidth,
height: h7 / parentHeight
});
break;
case "270":
rotator = (x2, y4, w3, h7) => ({
x: 1 - (y4 + h7 - layerY) / parentHeight,
y: (x2 - layerX) / parentWidth,
width: h7 / parentHeight,
height: w3 / parentWidth
});
break;
default:
rotator = (x2, y4, w3, h7) => ({
x: (x2 - layerX) / parentWidth,
y: (y4 - layerY) / parentHeight,
width: w3 / parentWidth,
height: h7 / parentHeight
});
break;
}
const boxes = [];
for (let i7 = 0, ii = selection.rangeCount; i7 < ii; i7++) {
const range2 = selection.getRangeAt(i7);
if (range2.collapsed) {
continue;
}
for (const {
x: x2,
y: y4,
width,
height
} of range2.getClientRects()) {
if (width === 0 || height === 0) {
continue;
}
boxes.push(rotator(x2, y4, width, height));
}
}
return boxes.length === 0 ? null : boxes;
}
addChangedExistingAnnotation({
annotationElementId,
id
}) {
(this.#changedExistingAnnotations ||= /* @__PURE__ */ new Map()).set(annotationElementId, id);
}
removeChangedExistingAnnotation({
annotationElementId
}) {
this.#changedExistingAnnotations?.delete(annotationElementId);
}
renderAnnotationElement(annotation) {
const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);
if (!editorId) {
return;
}
const editor = this.#annotationStorage.getRawValue(editorId);
if (!editor) {
return;
}
if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {
return;
}
editor.renderAnnotationElement(annotation);
}
setMissingCanvas(annotationId, annotationElementId, canvas) {
const editor = this.#missingCanvases?.get(annotationId);
if (!editor) {
return;
}
editor.setCanvas(annotationElementId, canvas);
this.#missingCanvases.delete(annotationId);
}
addMissingCanvas(annotationId, editor) {
(this.#missingCanvases ||= /* @__PURE__ */ new Map()).set(annotationId, editor);
}
};
AltText = class _AltText {
#altText = null;
#altTextDecorative = false;
#altTextButton = null;
#altTextButtonLabel = null;
#altTextTooltip = null;
#altTextTooltipTimeout = null;
#altTextWasFromKeyBoard = false;
#badge = null;
#editor = null;
#guessedText = null;
#textWithDisclaimer = null;
#useNewAltTextFlow = false;
static #l10nNewButton = null;
static _l10n = null;
constructor(editor) {
this.#editor = editor;
this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;
_AltText.#l10nNewButton ||= Object.freeze({
added: "pdfjs-editor-new-alt-text-added-button",
"added-label": "pdfjs-editor-new-alt-text-added-button-label",
missing: "pdfjs-editor-new-alt-text-missing-button",
"missing-label": "pdfjs-editor-new-alt-text-missing-button-label",
review: "pdfjs-editor-new-alt-text-to-review-button",
"review-label": "pdfjs-editor-new-alt-text-to-review-button-label"
});
}
static initialize(l10n) {
_AltText._l10n ??= l10n;
}
async render() {
const altText = this.#altTextButton = document.createElement("button");
altText.className = "altText";
altText.tabIndex = "0";
const label = this.#altTextButtonLabel = document.createElement("span");
altText.append(label);
if (this.#useNewAltTextFlow) {
altText.classList.add("new");
altText.setAttribute("data-l10n-id", _AltText.#l10nNewButton.missing);
label.setAttribute("data-l10n-id", _AltText.#l10nNewButton["missing-label"]);
} else {
altText.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button");
label.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button-label");
}
const signal = this.#editor._uiManager._signal;
altText.addEventListener("contextmenu", noContextMenu, {
signal
});
altText.addEventListener("pointerdown", (event) => event.stopPropagation(), {
signal
});
const onClick = (event) => {
event.preventDefault();
this.#editor._uiManager.editAltText(this.#editor);
if (this.#useNewAltTextFlow) {
this.#editor._reportTelemetry({
action: "pdfjs.image.alt_text.image_status_label_clicked",
data: {
label: this.#label
}
});
}
};
altText.addEventListener("click", onClick, {
capture: true,
signal
});
altText.addEventListener("keydown", (event) => {
if (event.target === altText && event.key === "Enter") {
this.#altTextWasFromKeyBoard = true;
onClick(event);
}
}, {
signal
});
await this.#setState();
return altText;
}
get #label() {
return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing";
}
finish() {
if (!this.#altTextButton) {
return;
}
this.#altTextButton.focus({
focusVisible: this.#altTextWasFromKeyBoard
});
this.#altTextWasFromKeyBoard = false;
}
isEmpty() {
if (this.#useNewAltTextFlow) {
return this.#altText === null;
}
return !this.#altText && !this.#altTextDecorative;
}
hasData() {
if (this.#useNewAltTextFlow) {
return this.#altText !== null || !!this.#guessedText;
}
return this.isEmpty();
}
get guessedText() {
return this.#guessedText;
}
async setGuessedText(guessedText) {
if (this.#altText !== null) {
return;
}
this.#guessedText = guessedText;
this.#textWithDisclaimer = await _AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer", {
generatedAltText: guessedText
});
this.#setState();
}
toggleAltTextBadge(visibility = false) {
if (!this.#useNewAltTextFlow || this.#altText) {
this.#badge?.remove();
this.#badge = null;
return;
}
if (!this.#badge) {
const badge = this.#badge = document.createElement("div");
badge.className = "noAltTextBadge";
this.#editor.div.append(badge);
}
this.#badge.classList.toggle("hidden", !visibility);
}
serialize(isForCopying) {
let altText = this.#altText;
if (!isForCopying && this.#guessedText === altText) {
altText = this.#textWithDisclaimer;
}
return {
altText,
decorative: this.#altTextDecorative,
guessedText: this.#guessedText,
textWithDisclaimer: this.#textWithDisclaimer
};
}
get data() {
return {
altText: this.#altText,
decorative: this.#altTextDecorative
};
}
set data({
altText,
decorative,
guessedText,
textWithDisclaimer,
cancel = false
}) {
if (guessedText) {
this.#guessedText = guessedText;
this.#textWithDisclaimer = textWithDisclaimer;
}
if (this.#altText === altText && this.#altTextDecorative === decorative) {
return;
}
if (!cancel) {
this.#altText = altText;
this.#altTextDecorative = decorative;
}
this.#setState();
}
toggle(enabled = false) {
if (!this.#altTextButton) {
return;
}
if (!enabled && this.#altTextTooltipTimeout) {
clearTimeout(this.#altTextTooltipTimeout);
this.#altTextTooltipTimeout = null;
}
this.#altTextButton.disabled = !enabled;
}
shown() {
this.#editor._reportTelemetry({
action: "pdfjs.image.alt_text.image_status_label_displayed",
data: {
label: this.#label
}
});
}
destroy() {
this.#altTextButton?.remove();
this.#altTextButton = null;
this.#altTextButtonLabel = null;
this.#altTextTooltip = null;
this.#badge?.remove();
this.#badge = null;
}
async #setState() {
const button = this.#altTextButton;
if (!button) {
return;
}
if (this.#useNewAltTextFlow) {
button.classList.toggle("done", !!this.#altText);
button.setAttribute("data-l10n-id", _AltText.#l10nNewButton[this.#label]);
this.#altTextButtonLabel?.setAttribute("data-l10n-id", _AltText.#l10nNewButton[`${this.#label}-label`]);
if (!this.#altText) {
this.#altTextTooltip?.remove();
return;
}
} else {
if (!this.#altText && !this.#altTextDecorative) {
button.classList.remove("done");
this.#altTextTooltip?.remove();
return;
}
button.classList.add("done");
button.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-edit-button");
}
let tooltip = this.#altTextTooltip;
if (!tooltip) {
this.#altTextTooltip = tooltip = document.createElement("span");
tooltip.className = "tooltip";
tooltip.setAttribute("role", "tooltip");
tooltip.id = `alt-text-tooltip-${this.#editor.id}`;
const DELAY_TO_SHOW_TOOLTIP = 100;
const signal = this.#editor._uiManager._signal;
signal.addEventListener("abort", () => {
clearTimeout(this.#altTextTooltipTimeout);
this.#altTextTooltipTimeout = null;
}, {
once: true
});
button.addEventListener("mouseenter", () => {
this.#altTextTooltipTimeout = setTimeout(() => {
this.#altTextTooltipTimeout = null;
this.#altTextTooltip.classList.add("show");
this.#editor._reportTelemetry({
action: "alt_text_tooltip"
});
}, DELAY_TO_SHOW_TOOLTIP);
}, {
signal
});
button.addEventListener("mouseleave", () => {
if (this.#altTextTooltipTimeout) {
clearTimeout(this.#altTextTooltipTimeout);
this.#altTextTooltipTimeout = null;
}
this.#altTextTooltip?.classList.remove("show");
}, {
signal
});
}
if (this.#altTextDecorative) {
tooltip.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-decorative-tooltip");
} else {
tooltip.removeAttribute("data-l10n-id");
tooltip.textContent = this.#altText;
}
if (!tooltip.parentNode) {
button.append(tooltip);
}
const element = this.#editor.getElementForAltText();
element?.setAttribute("aria-describedby", tooltip.id);
}
};
Comment = class {
#commentStandaloneButton = null;
#commentToolbarButton = null;
#commentWasFromKeyBoard = false;
#editor = null;
#initialText = null;
#richText = null;
#text = null;
#date = null;
#deleted = false;
#popupPosition = null;
constructor(editor) {
this.#editor = editor;
}
renderForToolbar() {
const button = this.#commentToolbarButton = document.createElement("button");
button.className = "comment";
return this.#render(button, false);
}
renderForStandalone() {
const button = this.#commentStandaloneButton = document.createElement("button");
button.className = "annotationCommentButton";
const position = this.#editor.commentButtonPosition;
if (position) {
const {
style
} = button;
style.insetInlineEnd = `calc(${100 * (this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0])}% - var(--comment-button-dim))`;
style.top = `calc(${100 * position[1]}% - var(--comment-button-dim))`;
const color2 = this.#editor.commentButtonColor;
if (color2) {
style.backgroundColor = color2;
}
}
return this.#render(button, true);
}
focusButton() {
setTimeout(() => {
(this.#commentStandaloneButton ?? this.#commentToolbarButton)?.focus();
}, 0);
}
onUpdatedColor() {
if (!this.#commentStandaloneButton) {
return;
}
const color2 = this.#editor.commentButtonColor;
if (color2) {
this.#commentStandaloneButton.style.backgroundColor = color2;
}
this.#editor._uiManager.updatePopupColor(this.#editor);
}
get commentButtonWidth() {
return (this.#commentStandaloneButton?.getBoundingClientRect().width ?? 0) / this.#editor.parent.boundingClientRect.width;
}
get commentPopupPositionInLayer() {
if (this.#popupPosition) {
return this.#popupPosition;
}
if (!this.#commentStandaloneButton) {
return null;
}
const {
x: x2,
y: y4,
height
} = this.#commentStandaloneButton.getBoundingClientRect();
const {
x: parentX,
y: parentY,
width: parentWidth,
height: parentHeight
} = this.#editor.parent.boundingClientRect;
return [(x2 - parentX) / parentWidth, (y4 + height - parentY) / parentHeight];
}
set commentPopupPositionInLayer(pos) {
this.#popupPosition = pos;
}
hasDefaultPopupPosition() {
return this.#popupPosition === null;
}
removeStandaloneCommentButton() {
this.#commentStandaloneButton?.remove();
this.#commentStandaloneButton = null;
}
removeToolbarCommentButton() {
this.#commentToolbarButton?.remove();
this.#commentToolbarButton = null;
}
setCommentButtonStates({
selected,
hasPopup
}) {
if (!this.#commentStandaloneButton) {
return;
}
this.#commentStandaloneButton.classList.toggle("selected", selected);
this.#commentStandaloneButton.ariaExpanded = hasPopup;
}
#render(comment, isStandalone) {
if (!this.#editor._uiManager.hasCommentManager()) {
return null;
}
comment.tabIndex = "0";
comment.ariaHasPopup = "dialog";
if (isStandalone) {
comment.ariaControls = "commentPopup";
comment.setAttribute("data-l10n-id", "pdfjs-show-comment-button");
} else {
comment.ariaControlsElements = [this.#editor._uiManager.getCommentDialogElement()];
comment.setAttribute("data-l10n-id", "pdfjs-editor-add-comment-button");
}
const signal = this.#editor._uiManager._signal;
if (!(signal instanceof AbortSignal) || signal.aborted) {
return comment;
}
comment.addEventListener("contextmenu", noContextMenu, {
signal
});
if (isStandalone) {
comment.addEventListener("focusin", (e9) => {
this.#editor._focusEventsAllowed = false;
stopEvent(e9);
}, {
capture: true,
signal
});
comment.addEventListener("focusout", (e9) => {
this.#editor._focusEventsAllowed = true;
stopEvent(e9);
}, {
capture: true,
signal
});
}
comment.addEventListener("pointerdown", (event) => event.stopPropagation(), {
signal
});
const onClick = (event) => {
event.preventDefault();
if (comment === this.#commentToolbarButton) {
this.edit();
} else {
this.#editor.toggleComment(true);
}
};
comment.addEventListener("click", onClick, {
capture: true,
signal
});
comment.addEventListener("keydown", (event) => {
if (event.target === comment && event.key === "Enter") {
this.#commentWasFromKeyBoard = true;
onClick(event);
}
}, {
signal
});
comment.addEventListener("pointerenter", () => {
this.#editor.toggleComment(false, true);
}, {
signal
});
comment.addEventListener("pointerleave", () => {
this.#editor.toggleComment(false, false);
}, {
signal
});
return comment;
}
edit(options) {
const position = this.commentPopupPositionInLayer;
let posX, posY;
if (position) {
[posX, posY] = position;
} else {
[posX, posY] = this.#editor.commentButtonPosition;
const {
width,
height,
x: x2,
y: y4
} = this.#editor;
posX = x2 + posX * width;
posY = y4 + posY * height;
}
const parentDimensions = this.#editor.parent.boundingClientRect;
const {
x: parentX,
y: parentY,
width: parentWidth,
height: parentHeight
} = parentDimensions;
this.#editor._uiManager.editComment(this.#editor, parentX + posX * parentWidth, parentY + posY * parentHeight, {
...options,
parentDimensions
});
}
finish() {
if (!this.#commentToolbarButton) {
return;
}
this.#commentToolbarButton.focus({
focusVisible: this.#commentWasFromKeyBoard
});
this.#commentWasFromKeyBoard = false;
}
isDeleted() {
return this.#deleted || this.#text === "";
}
isEmpty() {
return this.#text === null;
}
hasBeenEdited() {
return this.isDeleted() || this.#text !== this.#initialText;
}
serialize() {
return this.data;
}
get data() {
return {
text: this.#text,
richText: this.#richText,
date: this.#date,
deleted: this.isDeleted()
};
}
set data(text3) {
if (text3 !== this.#text) {
this.#richText = null;
}
if (text3 === null) {
this.#text = "";
this.#deleted = true;
return;
}
this.#text = text3;
this.#date = /* @__PURE__ */ new Date();
this.#deleted = false;
}
setInitialText(text3, richText = null) {
this.#initialText = text3;
this.data = text3;
this.#date = null;
this.#richText = richText;
}
shown() {
}
destroy() {
this.#commentToolbarButton?.remove();
this.#commentToolbarButton = null;
this.#commentStandaloneButton?.remove();
this.#commentStandaloneButton = null;
this.#text = "";
this.#richText = null;
this.#date = null;
this.#editor = null;
this.#commentWasFromKeyBoard = false;
this.#deleted = false;
}
};
TouchManager = class _TouchManager {
#container;
#isPinching = false;
#isPinchingStopped = null;
#isPinchingDisabled;
#onPinchStart;
#onPinching;
#onPinchEnd;
#pointerDownAC = null;
#signal;
#touchInfo = null;
#touchManagerAC;
#touchMoveAC = null;
constructor({
container,
isPinchingDisabled = null,
isPinchingStopped = null,
onPinchStart = null,
onPinching = null,
onPinchEnd = null,
signal
}) {
this.#container = container;
this.#isPinchingStopped = isPinchingStopped;
this.#isPinchingDisabled = isPinchingDisabled;
this.#onPinchStart = onPinchStart;
this.#onPinching = onPinching;
this.#onPinchEnd = onPinchEnd;
this.#touchManagerAC = new AbortController();
this.#signal = AbortSignal.any([signal, this.#touchManagerAC.signal]);
container.addEventListener("touchstart", this.#onTouchStart.bind(this), {
passive: false,
signal: this.#signal
});
}
get MIN_TOUCH_DISTANCE_TO_PINCH() {
return 35 / OutputScale.pixelRatio;
}
#onTouchStart(evt) {
if (this.#isPinchingDisabled?.()) {
return;
}
if (evt.touches.length === 1) {
if (this.#pointerDownAC) {
return;
}
const pointerDownAC = this.#pointerDownAC = new AbortController();
const signal = AbortSignal.any([this.#signal, pointerDownAC.signal]);
const container = this.#container;
const opts = {
capture: true,
signal,
passive: false
};
const cancelPointerDown = (e9) => {
if (e9.pointerType === "touch") {
this.#pointerDownAC?.abort();
this.#pointerDownAC = null;
}
};
container.addEventListener("pointerdown", (e9) => {
if (e9.pointerType === "touch") {
stopEvent(e9);
cancelPointerDown(e9);
}
}, opts);
container.addEventListener("pointerup", cancelPointerDown, opts);
container.addEventListener("pointercancel", cancelPointerDown, opts);
return;
}
if (!this.#touchMoveAC) {
this.#touchMoveAC = new AbortController();
const signal = AbortSignal.any([this.#signal, this.#touchMoveAC.signal]);
const container = this.#container;
const opt = {
signal,
capture: false,
passive: false
};
container.addEventListener("touchmove", this.#onTouchMove.bind(this), opt);
const onTouchEnd = this.#onTouchEnd.bind(this);
container.addEventListener("touchend", onTouchEnd, opt);
container.addEventListener("touchcancel", onTouchEnd, opt);
opt.capture = true;
container.addEventListener("pointerdown", stopEvent, opt);
container.addEventListener("pointermove", stopEvent, opt);
container.addEventListener("pointercancel", stopEvent, opt);
container.addEventListener("pointerup", stopEvent, opt);
this.#onPinchStart?.();
}
stopEvent(evt);
if (evt.touches.length !== 2 || this.#isPinchingStopped?.()) {
this.#touchInfo = null;
return;
}
let [touch0, touch1] = evt.touches;
if (touch0.identifier > touch1.identifier) {
[touch0, touch1] = [touch1, touch0];
}
this.#touchInfo = {
touch0X: touch0.screenX,
touch0Y: touch0.screenY,
touch1X: touch1.screenX,
touch1Y: touch1.screenY
};
}
#onTouchMove(evt) {
if (!this.#touchInfo || evt.touches.length !== 2) {
return;
}
stopEvent(evt);
let [touch0, touch1] = evt.touches;
if (touch0.identifier > touch1.identifier) {
[touch0, touch1] = [touch1, touch0];
}
const {
screenX: screen0X,
screenY: screen0Y
} = touch0;
const {
screenX: screen1X,
screenY: screen1Y
} = touch1;
const touchInfo = this.#touchInfo;
const {
touch0X: pTouch0X,
touch0Y: pTouch0Y,
touch1X: pTouch1X,
touch1Y: pTouch1Y
} = touchInfo;
const prevGapX = pTouch1X - pTouch0X;
const prevGapY = pTouch1Y - pTouch0Y;
const currGapX = screen1X - screen0X;
const currGapY = screen1Y - screen0Y;
const distance = Math.hypot(currGapX, currGapY) || 1;
const pDistance = Math.hypot(prevGapX, prevGapY) || 1;
if (!this.#isPinching && Math.abs(pDistance - distance) <= _TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH) {
return;
}
touchInfo.touch0X = screen0X;
touchInfo.touch0Y = screen0Y;
touchInfo.touch1X = screen1X;
touchInfo.touch1Y = screen1Y;
if (!this.#isPinching) {
this.#isPinching = true;
return;
}
const origin = [(screen0X + screen1X) / 2, (screen0Y + screen1Y) / 2];
this.#onPinching?.(origin, pDistance, distance);
}
#onTouchEnd(evt) {
if (evt.touches.length >= 2) {
return;
}
if (this.#touchMoveAC) {
this.#touchMoveAC.abort();
this.#touchMoveAC = null;
this.#onPinchEnd?.();
}
if (!this.#touchInfo) {
return;
}
stopEvent(evt);
this.#touchInfo = null;
this.#isPinching = false;
}
destroy() {
this.#touchManagerAC?.abort();
this.#touchManagerAC = null;
this.#pointerDownAC?.abort();
this.#pointerDownAC = null;
}
};
AnnotationEditor = class _AnnotationEditor {
#accessibilityData = null;
#allResizerDivs = null;
#altText = null;
#comment = null;
#commentStandaloneButton = null;
#disabled = false;
#dragPointerId = null;
#dragPointerType = "";
#resizersDiv = null;
#lastPointerCoords = null;
#savedDimensions = null;
#fakeAnnotation = null;
#focusAC = null;
#focusedResizerName = "";
#hasBeenClicked = false;
#initialRect = null;
#isEditing = false;
#isInEditMode = false;
#isResizerEnabledForKeyboard = false;
#moveInDOMTimeout = null;
#prevDragX = 0;
#prevDragY = 0;
#telemetryTimeouts = null;
#touchManager = null;
isSelected = false;
_isCopy = false;
_editToolbar = null;
_initialOptions = /* @__PURE__ */ Object.create(null);
_initialData = null;
_isVisible = true;
_uiManager = null;
_focusEventsAllowed = true;
static _l10n = null;
static _l10nResizer = null;
#isDraggable = false;
#zIndex = _AnnotationEditor._zIndex++;
static _borderLineWidth = -1;
static _colorManager = new ColorManager();
static _zIndex = 1;
static _telemetryTimeout = 1e3;
static get _resizerKeyboardManager() {
const resize = _AnnotationEditor.prototype._resizeWithKeyboard;
const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
const big = AnnotationEditorUIManager.TRANSLATE_BIG;
return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, {
args: [-small, 0]
}], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, {
args: [-big, 0]
}], [["ArrowRight", "mac+ArrowRight"], resize, {
args: [small, 0]
}], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, {
args: [big, 0]
}], [["ArrowUp", "mac+ArrowUp"], resize, {
args: [0, -small]
}], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, {
args: [0, -big]
}], [["ArrowDown", "mac+ArrowDown"], resize, {
args: [0, small]
}], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, {
args: [0, big]
}], [["Escape", "mac+Escape"], _AnnotationEditor.prototype._stopResizingWithKeyboard]]));
}
constructor(parameters) {
this.parent = parameters.parent;
this.id = parameters.id;
this.width = this.height = null;
this.pageIndex = parameters.parent.pageIndex;
this.name = parameters.name;
this.div = null;
this._uiManager = parameters.uiManager;
this.annotationElementId = null;
this._willKeepAspectRatio = false;
this._initialOptions.isCentered = parameters.isCentered;
this._structTreeParentId = null;
this.annotationElementId = parameters.annotationElementId || null;
this.creationDate = parameters.creationDate || /* @__PURE__ */ new Date();
this.modificationDate = parameters.modificationDate || null;
this.canAddComment = true;
const {
rotation,
rawDims: {
pageWidth,
pageHeight,
pageX,
pageY
}
} = this.parent.viewport;
this.rotation = rotation;
this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360;
this.pageDimensions = [pageWidth, pageHeight];
this.pageTranslation = [pageX, pageY];
const [width, height] = this.parentDimensions;
this.x = parameters.x / width;
this.y = parameters.y / height;
this.isAttachedToDOM = false;
this.deleted = false;
}
get editorType() {
return Object.getPrototypeOf(this).constructor._type;
}
get mode() {
return Object.getPrototypeOf(this).constructor._editorType;
}
static get isDrawer() {
return false;
}
static get _defaultLineColor() {
return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
}
static deleteAnnotationElement(editor) {
const fakeEditor = new FakeEditor({
id: editor.parent.getNextId(),
parent: editor.parent,
uiManager: editor._uiManager
});
fakeEditor.annotationElementId = editor.annotationElementId;
fakeEditor.deleted = true;
fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);
}
static initialize(l10n, _uiManager) {
_AnnotationEditor._l10n ??= l10n;
_AnnotationEditor._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"
});
if (_AnnotationEditor._borderLineWidth !== -1) {
return;
}
const style = getComputedStyle(document.documentElement);
_AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0;
}
static updateDefaultParams(_type, _value) {
}
static get defaultPropertiesToUpdate() {
return [];
}
static isHandlingMimeForPasting(mime) {
return false;
}
static paste(item, parent) {
unreachable("Not implemented");
}
get propertiesToUpdate() {
return [];
}
get _isDraggable() {
return this.#isDraggable;
}
set _isDraggable(value) {
this.#isDraggable = value;
this.div?.classList.toggle("draggable", value);
}
get uid() {
return this.annotationElementId || this.id;
}
get isEnterHandled() {
return true;
}
center() {
const [pageWidth, pageHeight] = this.pageDimensions;
switch (this.parentRotation) {
case 90:
this.x -= this.height * pageHeight / (pageWidth * 2);
this.y += this.width * pageWidth / (pageHeight * 2);
break;
case 180:
this.x += this.width / 2;
this.y += this.height / 2;
break;
case 270:
this.x += this.height * pageHeight / (pageWidth * 2);
this.y -= this.width * pageWidth / (pageHeight * 2);
break;
default:
this.x -= this.width / 2;
this.y -= this.height / 2;
break;
}
this.fixAndSetPosition();
}
addCommands(params) {
this._uiManager.addCommands(params);
}
get currentLayer() {
return this._uiManager.currentLayer;
}
setInBackground() {
this.div.style.zIndex = 0;
}
setInForeground() {
this.div.style.zIndex = this.#zIndex;
}
setParent(parent) {
if (parent !== null) {
this.pageIndex = parent.pageIndex;
this.pageDimensions = parent.pageDimensions;
} else {
this.#stopResizing();
this.#fakeAnnotation?.remove();
this.#fakeAnnotation = null;
}
this.parent = parent;
}
focusin(event) {
if (!this._focusEventsAllowed) {
return;
}
if (!this.#hasBeenClicked) {
this.parent.setSelected(this);
} else {
this.#hasBeenClicked = false;
}
}
focusout(event) {
if (!this._focusEventsAllowed) {
return;
}
if (!this.isAttachedToDOM) {
return;
}
const target = event.relatedTarget;
if (target?.closest(`#${this.id}`)) {
return;
}
event.preventDefault();
if (!this.parent?.isMultipleSelection) {
this.commitOrRemove();
}
}
commitOrRemove() {
if (this.isEmpty()) {
this.remove();
} else {
this.commit();
}
}
commit() {
if (!this.isInEditMode()) {
return;
}
this.addToAnnotationStorage();
}
addToAnnotationStorage() {
this._uiManager.addToAnnotationStorage(this);
}
setAt(x2, y4, tx, ty) {
const [width, height] = this.parentDimensions;
[tx, ty] = this.screenToPageTranslation(tx, ty);
this.x = (x2 + tx) / width;
this.y = (y4 + ty) / height;
this.fixAndSetPosition();
}
_moveAfterPaste(baseX, baseY) {
const [parentWidth, parentHeight] = this.parentDimensions;
this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
this._onTranslated();
}
#translate([width, height], x2, y4) {
[x2, y4] = this.screenToPageTranslation(x2, y4);
this.x += x2 / width;
this.y += y4 / height;
this._onTranslating(this.x, this.y);
this.fixAndSetPosition();
}
translate(x2, y4) {
this.#translate(this.parentDimensions, x2, y4);
}
translateInPage(x2, y4) {
this.#initialRect ||= [this.x, this.y, this.width, this.height];
this.#translate(this.pageDimensions, x2, y4);
this.div.scrollIntoView({
block: "nearest"
});
}
translationDone() {
this._onTranslated(this.x, this.y);
}
drag(tx, ty) {
this.#initialRect ||= [this.x, this.y, this.width, this.height];
const {
div,
parentDimensions: [parentWidth, parentHeight]
} = this;
this.x += tx / parentWidth;
this.y += ty / parentHeight;
if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {
const {
x: x3,
y: y5
} = this.div.getBoundingClientRect();
if (this.parent.findNewParent(this, x3, y5)) {
this.x -= Math.floor(this.x);
this.y -= Math.floor(this.y);
}
}
let {
x: x2,
y: y4
} = this;
const [bx, by] = this.getBaseTranslation();
x2 += bx;
y4 += by;
const {
style
} = div;
style.left = `${(100 * x2).toFixed(2)}%`;
style.top = `${(100 * y4).toFixed(2)}%`;
this._onTranslating(x2, y4);
div.scrollIntoView({
block: "nearest"
});
}
_onTranslating(x2, y4) {
}
_onTranslated(x2, y4) {
}
get _hasBeenMoved() {
return !!this.#initialRect && (this.#initialRect[0] !== this.x || this.#initialRect[1] !== this.y);
}
get _hasBeenResized() {
return !!this.#initialRect && (this.#initialRect[2] !== this.width || this.#initialRect[3] !== this.height);
}
getBaseTranslation() {
const [parentWidth, parentHeight] = this.parentDimensions;
const {
_borderLineWidth
} = _AnnotationEditor;
const x2 = _borderLineWidth / parentWidth;
const y4 = _borderLineWidth / parentHeight;
switch (this.rotation) {
case 90:
return [-x2, y4];
case 180:
return [x2, y4];
case 270:
return [x2, -y4];
default:
return [-x2, -y4];
}
}
get _mustFixPosition() {
return true;
}
fixAndSetPosition(rotation = this.rotation) {
const {
div: {
style
},
pageDimensions: [pageWidth, pageHeight]
} = this;
let {
x: x2,
y: y4,
width,
height
} = this;
width *= pageWidth;
height *= pageHeight;
x2 *= pageWidth;
y4 *= pageHeight;
if (this._mustFixPosition) {
switch (rotation) {
case 0:
x2 = MathClamp(x2, 0, pageWidth - width);
y4 = MathClamp(y4, 0, pageHeight - height);
break;
case 90:
x2 = MathClamp(x2, 0, pageWidth - height);
y4 = MathClamp(y4, width, pageHeight);
break;
case 180:
x2 = MathClamp(x2, width, pageWidth);
y4 = MathClamp(y4, height, pageHeight);
break;
case 270:
x2 = MathClamp(x2, height, pageWidth);
y4 = MathClamp(y4, 0, pageHeight - width);
break;
}
}
this.x = x2 /= pageWidth;
this.y = y4 /= pageHeight;
const [bx, by] = this.getBaseTranslation();
x2 += bx;
y4 += by;
style.left = `${(100 * x2).toFixed(2)}%`;
style.top = `${(100 * y4).toFixed(2)}%`;
this.moveInDOM();
}
static #rotatePoint(x2, y4, angle) {
switch (angle) {
case 90:
return [y4, -x2];
case 180:
return [-x2, -y4];
case 270:
return [-y4, x2];
default:
return [x2, y4];
}
}
screenToPageTranslation(x2, y4) {
return _AnnotationEditor.#rotatePoint(x2, y4, this.parentRotation);
}
pageTranslationToScreen(x2, y4) {
return _AnnotationEditor.#rotatePoint(x2, y4, 360 - this.parentRotation);
}
#getRotationMatrix(rotation) {
switch (rotation) {
case 90: {
const [pageWidth, pageHeight] = this.pageDimensions;
return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];
}
case 180:
return [-1, 0, 0, -1];
case 270: {
const [pageWidth, pageHeight] = this.pageDimensions;
return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 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() {
const {
parentScale,
pageDimensions: [pageWidth, pageHeight]
} = this;
return [pageWidth * parentScale, pageHeight * parentScale];
}
setDims() {
const {
div: {
style
},
width,
height
} = this;
style.width = `${(100 * width).toFixed(2)}%`;
style.height = `${(100 * height).toFixed(2)}%`;
}
getInitialTranslation() {
return [0, 0];
}
#createResizers() {
if (this.#resizersDiv) {
return;
}
this.#resizersDiv = document.createElement("div");
this.#resizersDiv.classList.add("resizers");
const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"];
const signal = this._uiManager._signal;
for (const name of classes) {
const div = document.createElement("div");
this.#resizersDiv.append(div);
div.classList.add("resizer", name);
div.setAttribute("data-resizer-name", name);
div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), {
signal
});
div.addEventListener("contextmenu", noContextMenu, {
signal
});
div.tabIndex = -1;
}
this.div.prepend(this.#resizersDiv);
}
#resizerPointerdown(name, event) {
event.preventDefault();
const {
isMac
} = util_FeatureTest.platform;
if (event.button !== 0 || event.ctrlKey && isMac) {
return;
}
this.#altText?.toggle(false);
const savedDraggable = this._isDraggable;
this._isDraggable = false;
this.#lastPointerCoords = [event.screenX, event.screenY];
const ac = new AbortController();
const signal = this._uiManager.combinedSignal(ac);
this.parent.togglePointerEvents(false);
window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), {
passive: true,
capture: true,
signal
});
window.addEventListener("touchmove", stopEvent, {
passive: false,
signal
});
window.addEventListener("contextmenu", noContextMenu, {
signal
});
this.#savedDimensions = {
savedX: this.x,
savedY: this.y,
savedWidth: this.width,
savedHeight: this.height
};
const savedParentCursor = this.parent.div.style.cursor;
const savedCursor = this.div.style.cursor;
this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor;
const pointerUpCallback = () => {
ac.abort();
this.parent.togglePointerEvents(true);
this.#altText?.toggle(true);
this._isDraggable = savedDraggable;
this.parent.div.style.cursor = savedParentCursor;
this.div.style.cursor = savedCursor;
this.#addResizeToUndoStack();
};
window.addEventListener("pointerup", pointerUpCallback, {
signal
});
window.addEventListener("blur", pointerUpCallback, {
signal
});
}
#resize(x2, y4, width, height) {
this.width = width;
this.height = height;
this.x = x2;
this.y = y4;
this.setDims();
this.fixAndSetPosition();
this._onResized();
}
_onResized() {
}
#addResizeToUndoStack() {
if (!this.#savedDimensions) {
return;
}
const {
savedX,
savedY,
savedWidth,
savedHeight
} = this.#savedDimensions;
this.#savedDimensions = null;
const newX = this.x;
const newY = this.y;
const newWidth = this.width;
const newHeight = this.height;
if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) {
return;
}
this.addCommands({
cmd: this.#resize.bind(this, newX, newY, newWidth, newHeight),
undo: this.#resize.bind(this, savedX, savedY, savedWidth, savedHeight),
mustExec: true
});
}
static _round(x2) {
return Math.round(x2 * 1e4) / 1e4;
}
#resizerPointermove(name, event) {
const [parentWidth, parentHeight] = this.parentDimensions;
const savedX = this.x;
const savedY = this.y;
const savedWidth = this.width;
const savedHeight = this.height;
const minWidth = _AnnotationEditor.MIN_SIZE / parentWidth;
const minHeight = _AnnotationEditor.MIN_SIZE / parentHeight;
const rotationMatrix = this.#getRotationMatrix(this.rotation);
const transf = (x2, y4) => [rotationMatrix[0] * x2 + rotationMatrix[2] * y4, rotationMatrix[1] * x2 + rotationMatrix[3] * y4];
const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);
const invTransf = (x2, y4) => [invRotationMatrix[0] * x2 + invRotationMatrix[2] * y4, invRotationMatrix[1] * x2 + invRotationMatrix[3] * y4];
let getPoint2;
let getOpposite;
let isDiagonal = false;
let isHorizontal = false;
switch (name) {
case "topLeft":
isDiagonal = true;
getPoint2 = (w3, h7) => [0, 0];
getOpposite = (w3, h7) => [w3, h7];
break;
case "topMiddle":
getPoint2 = (w3, h7) => [w3 / 2, 0];
getOpposite = (w3, h7) => [w3 / 2, h7];
break;
case "topRight":
isDiagonal = true;
getPoint2 = (w3, h7) => [w3, 0];
getOpposite = (w3, h7) => [0, h7];
break;
case "middleRight":
isHorizontal = true;
getPoint2 = (w3, h7) => [w3, h7 / 2];
getOpposite = (w3, h7) => [0, h7 / 2];
break;
case "bottomRight":
isDiagonal = true;
getPoint2 = (w3, h7) => [w3, h7];
getOpposite = (w3, h7) => [0, 0];
break;
case "bottomMiddle":
getPoint2 = (w3, h7) => [w3 / 2, h7];
getOpposite = (w3, h7) => [w3 / 2, 0];
break;
case "bottomLeft":
isDiagonal = true;
getPoint2 = (w3, h7) => [0, h7];
getOpposite = (w3, h7) => [w3, 0];
break;
case "middleLeft":
isHorizontal = true;
getPoint2 = (w3, h7) => [0, h7 / 2];
getOpposite = (w3, h7) => [w3, h7 / 2];
break;
}
const point = getPoint2(savedWidth, savedHeight);
const oppositePoint = getOpposite(savedWidth, savedHeight);
let transfOppositePoint = transf(...oppositePoint);
const oppositeX = _AnnotationEditor._round(savedX + transfOppositePoint[0]);
const oppositeY = _AnnotationEditor._round(savedY + transfOppositePoint[1]);
let ratioX = 1;
let ratioY = 1;
let deltaX, deltaY;
if (!event.fromKeyboard) {
const {
screenX,
screenY
} = event;
const [lastScreenX, lastScreenY] = this.#lastPointerCoords;
[deltaX, deltaY] = this.screenToPageTranslation(screenX - lastScreenX, screenY - lastScreenY);
this.#lastPointerCoords[0] = screenX;
this.#lastPointerCoords[1] = screenY;
} else {
({
deltaX,
deltaY
} = event);
}
[deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);
if (isDiagonal) {
const oldDiag = Math.hypot(savedWidth, savedHeight);
ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);
} else if (isHorizontal) {
ratioX = MathClamp(Math.abs(oppositePoint[0] - point[0] - deltaX), minWidth, 1) / savedWidth;
} else {
ratioY = MathClamp(Math.abs(oppositePoint[1] - point[1] - deltaY), minHeight, 1) / savedHeight;
}
const newWidth = _AnnotationEditor._round(savedWidth * ratioX);
const newHeight = _AnnotationEditor._round(savedHeight * ratioY);
transfOppositePoint = transf(...getOpposite(newWidth, newHeight));
const newX = oppositeX - transfOppositePoint[0];
const newY = oppositeY - transfOppositePoint[1];
this.#initialRect ||= [this.x, this.y, this.width, this.height];
this.width = newWidth;
this.height = newHeight;
this.x = newX;
this.y = newY;
this.setDims();
this.fixAndSetPosition();
this._onResizing();
}
_onResizing() {
}
altTextFinish() {
this.#altText?.finish();
}
get toolbarButtons() {
return null;
}
async addEditToolbar() {
if (this._editToolbar || this.#isInEditMode) {
return this._editToolbar;
}
this._editToolbar = new EditorToolbar(this);
this.div.append(this._editToolbar.render());
const {
toolbarButtons
} = this;
if (toolbarButtons) {
for (const [name, tool] of toolbarButtons) {
await this._editToolbar.addButton(name, tool);
}
}
if (!this.hasComment) {
this._editToolbar.addButton("comment", this.addCommentButton());
}
this._editToolbar.addButton("delete");
return this._editToolbar;
}
addCommentButtonInToolbar() {
this._editToolbar?.addButtonBefore("comment", this.addCommentButton(), ".deleteButton");
}
removeCommentButtonFromToolbar() {
this._editToolbar?.removeButton("comment");
}
removeEditToolbar() {
this._editToolbar?.remove();
this._editToolbar = null;
this.#altText?.destroy();
}
addContainer(container) {
const editToolbarDiv = this._editToolbar?.div;
if (editToolbarDiv) {
editToolbarDiv.before(container);
} else {
this.div.append(container);
}
}
getClientDimensions() {
return this.div.getBoundingClientRect();
}
createAltText() {
if (!this.#altText) {
AltText.initialize(_AnnotationEditor._l10n);
this.#altText = new AltText(this);
if (this.#accessibilityData) {
this.#altText.data = this.#accessibilityData;
this.#accessibilityData = null;
}
}
return this.#altText;
}
get altTextData() {
return this.#altText?.data;
}
set altTextData(data) {
if (!this.#altText) {
return;
}
this.#altText.data = data;
}
get guessedAltText() {
return this.#altText?.guessedText;
}
async setGuessedAltText(text3) {
await this.#altText?.setGuessedText(text3);
}
serializeAltText(isForCopying) {
return this.#altText?.serialize(isForCopying);
}
hasAltText() {
return !!this.#altText && !this.#altText.isEmpty();
}
hasAltTextData() {
return this.#altText?.hasData() ?? false;
}
focusCommentButton() {
this.#comment?.focusButton();
}
addCommentButton() {
return this.canAddComment ? this.#comment ||= new Comment(this) : null;
}
addStandaloneCommentButton() {
if (!this._uiManager.hasCommentManager()) {
return;
}
if (this.#commentStandaloneButton) {
if (this._uiManager.isEditingMode()) {
this.#commentStandaloneButton.classList.remove("hidden");
}
return;
}
if (!this.hasComment) {
return;
}
this.#commentStandaloneButton = this.#comment.renderForStandalone();
this.div.append(this.#commentStandaloneButton);
}
removeStandaloneCommentButton() {
this.#comment.removeStandaloneCommentButton();
this.#commentStandaloneButton = null;
}
hideStandaloneCommentButton() {
this.#commentStandaloneButton?.classList.add("hidden");
}
get comment() {
const {
data: {
richText,
text: text3,
date,
deleted
}
} = this.#comment;
return {
text: text3,
richText,
date,
deleted,
color: this.getNonHCMColor(),
opacity: this.opacity ?? 1
};
}
set comment(text3) {
this.#comment ||= new Comment(this);
this.#comment.data = text3;
if (this.hasComment) {
this.removeCommentButtonFromToolbar();
this.addStandaloneCommentButton();
this._uiManager.updateComment(this);
} else {
this.addCommentButtonInToolbar();
this.removeStandaloneCommentButton();
this._uiManager.removeComment(this);
}
}
setCommentData({
comment,
popupRef,
richText
}) {
if (!popupRef) {
return;
}
this.#comment ||= new Comment(this);
this.#comment.setInitialText(comment, richText);
if (!this.annotationElementId) {
return;
}
const storedData = this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);
if (storedData) {
this.updateFromAnnotationLayer(storedData);
}
}
get hasEditedComment() {
return this.#comment?.hasBeenEdited();
}
get hasDeletedComment() {
return this.#comment?.isDeleted();
}
get hasComment() {
return !!this.#comment && !this.#comment.isEmpty() && !this.#comment.isDeleted();
}
async editComment(options) {
this.#comment ||= new Comment(this);
this.#comment.edit(options);
}
toggleComment(isSelected, visibility = void 0) {
if (this.hasComment) {
this._uiManager.toggleComment(this, isSelected, visibility);
}
}
setSelectedCommentButton(selected) {
this.#comment.setSelectedButton(selected);
}
addComment(serialized) {
if (this.hasEditedComment) {
const DEFAULT_POPUP_WIDTH = 180;
const DEFAULT_POPUP_HEIGHT = 100;
const [, , , trY] = serialized.rect;
const [pageWidth] = this.pageDimensions;
const [pageX] = this.pageTranslation;
const blX = pageX + pageWidth + 1;
const blY = trY - DEFAULT_POPUP_HEIGHT;
const trX = blX + DEFAULT_POPUP_WIDTH;
serialized.popup = {
contents: this.comment.text,
deleted: this.comment.deleted,
rect: [blX, blY, trX, trY]
};
}
}
updateFromAnnotationLayer({
popup: {
contents,
deleted
}
}) {
this.#comment.data = deleted ? null : contents;
}
get parentBoundingClientRect() {
return this.parent.boundingClientRect;
}
render() {
const div = this.div = document.createElement("div");
div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
div.className = this.name;
div.setAttribute("id", this.id);
div.tabIndex = this.#disabled ? -1 : 0;
div.setAttribute("role", "application");
if (this.defaultL10nId) {
div.setAttribute("data-l10n-id", this.defaultL10nId);
}
if (!this._isVisible) {
div.classList.add("hidden");
}
this.setInForeground();
this.#addFocusListeners();
const [parentWidth, parentHeight] = this.parentDimensions;
if (this.parentRotation % 180 !== 0) {
div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`;
div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`;
}
const [tx, ty] = this.getInitialTranslation();
this.translate(tx, ty);
bindEvents(this, div, ["keydown", "pointerdown", "dblclick"]);
if (this.isResizable && this._uiManager._supportsPinchToZoom) {
this.#touchManager ||= new TouchManager({
container: div,
isPinchingDisabled: () => !this.isSelected,
onPinchStart: this.#touchPinchStartCallback.bind(this),
onPinching: this.#touchPinchCallback.bind(this),
onPinchEnd: this.#touchPinchEndCallback.bind(this),
signal: this._uiManager._signal
});
}
this.addStandaloneCommentButton();
this._uiManager._editorUndoBar?.hide();
return div;
}
#touchPinchStartCallback() {
this.#savedDimensions = {
savedX: this.x,
savedY: this.y,
savedWidth: this.width,
savedHeight: this.height
};
this.#altText?.toggle(false);
this.parent.togglePointerEvents(false);
}
#touchPinchCallback(_origin2, prevDistance, distance) {
const slowDownFactor = 0.7;
let factor = slowDownFactor * (distance / prevDistance) + 1 - slowDownFactor;
if (factor === 1) {
return;
}
const rotationMatrix = this.#getRotationMatrix(this.rotation);
const transf = (x2, y4) => [rotationMatrix[0] * x2 + rotationMatrix[2] * y4, rotationMatrix[1] * x2 + rotationMatrix[3] * y4];
const [parentWidth, parentHeight] = this.parentDimensions;
const savedX = this.x;
const savedY = this.y;
const savedWidth = this.width;
const savedHeight = this.height;
const minWidth = _AnnotationEditor.MIN_SIZE / parentWidth;
const minHeight = _AnnotationEditor.MIN_SIZE / parentHeight;
factor = Math.max(Math.min(factor, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight);
const newWidth = _AnnotationEditor._round(savedWidth * factor);
const newHeight = _AnnotationEditor._round(savedHeight * factor);
if (newWidth === savedWidth && newHeight === savedHeight) {
return;
}
this.#initialRect ||= [savedX, savedY, savedWidth, savedHeight];
const transfCenterPoint = transf(savedWidth / 2, savedHeight / 2);
const centerX = _AnnotationEditor._round(savedX + transfCenterPoint[0]);
const centerY = _AnnotationEditor._round(savedY + transfCenterPoint[1]);
const newTransfCenterPoint = transf(newWidth / 2, newHeight / 2);
this.x = centerX - newTransfCenterPoint[0];
this.y = centerY - newTransfCenterPoint[1];
this.width = newWidth;
this.height = newHeight;
this.setDims();
this.fixAndSetPosition();
this._onResizing();
}
#touchPinchEndCallback() {
this.#altText?.toggle(true);
this.parent.togglePointerEvents(true);
this.#addResizeToUndoStack();
}
pointerdown(event) {
const {
isMac
} = util_FeatureTest.platform;
if (event.button !== 0 || event.ctrlKey && isMac) {
event.preventDefault();
return;
}
this.#hasBeenClicked = true;
if (this._isDraggable) {
this.#setUpDragSession(event);
return;
}
this.#selectOnPointerEvent(event);
}
#selectOnPointerEvent(event) {
const {
isMac
} = util_FeatureTest.platform;
if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
this.parent.toggleSelected(this);
} else {
this.parent.setSelected(this);
}
}
#setUpDragSession(event) {
const {
isSelected
} = this;
this._uiManager.setUpDragSession();
let hasDraggingStarted = false;
const ac = new AbortController();
const signal = this._uiManager.combinedSignal(ac);
const opts = {
capture: true,
passive: false,
signal
};
const cancelDrag = (e9) => {
ac.abort();
this.#dragPointerId = null;
this.#hasBeenClicked = false;
if (!this._uiManager.endDragSession()) {
this.#selectOnPointerEvent(e9);
}
if (hasDraggingStarted) {
this._onStopDragging();
}
};
if (isSelected) {
this.#prevDragX = event.clientX;
this.#prevDragY = event.clientY;
this.#dragPointerId = event.pointerId;
this.#dragPointerType = event.pointerType;
window.addEventListener("pointermove", (e9) => {
if (!hasDraggingStarted) {
hasDraggingStarted = true;
this._uiManager.toggleComment(this, true, false);
this._onStartDragging();
}
const {
clientX: x2,
clientY: y4,
pointerId
} = e9;
if (pointerId !== this.#dragPointerId) {
stopEvent(e9);
return;
}
const [tx, ty] = this.screenToPageTranslation(x2 - this.#prevDragX, y4 - this.#prevDragY);
this.#prevDragX = x2;
this.#prevDragY = y4;
this._uiManager.dragSelectedEditors(tx, ty);
}, opts);
window.addEventListener("touchmove", stopEvent, opts);
window.addEventListener("pointerdown", (e9) => {
if (e9.pointerType === this.#dragPointerType) {
if (this.#touchManager || e9.isPrimary) {
cancelDrag(e9);
}
}
stopEvent(e9);
}, opts);
}
const pointerUpCallback = (e9) => {
if (!this.#dragPointerId || this.#dragPointerId === e9.pointerId) {
cancelDrag(e9);
return;
}
stopEvent(e9);
};
window.addEventListener("pointerup", pointerUpCallback, {
signal
});
window.addEventListener("blur", pointerUpCallback, {
signal
});
}
_onStartDragging() {
}
_onStopDragging() {
}
moveInDOM() {
if (this.#moveInDOMTimeout) {
clearTimeout(this.#moveInDOMTimeout);
}
this.#moveInDOMTimeout = setTimeout(() => {
this.#moveInDOMTimeout = null;
this.parent?.moveEditorInDOM(this);
}, 0);
}
_setParentAndPosition(parent, x2, y4) {
parent.changeParent(this);
this.x = x2;
this.y = y4;
this.fixAndSetPosition();
this._onTranslated();
}
getRect(tx, ty, rotation = this.rotation) {
const scale = this.parentScale;
const [pageWidth, pageHeight] = this.pageDimensions;
const [pageX, pageY] = this.pageTranslation;
const shiftX = tx / scale;
const shiftY = ty / scale;
const x2 = this.x * pageWidth;
const y4 = this.y * pageHeight;
const width = this.width * pageWidth;
const height = this.height * pageHeight;
switch (rotation) {
case 0:
return [x2 + shiftX + pageX, pageHeight - y4 - shiftY - height + pageY, x2 + shiftX + width + pageX, pageHeight - y4 - shiftY + pageY];
case 90:
return [x2 + shiftY + pageX, pageHeight - y4 + shiftX + pageY, x2 + shiftY + height + pageX, pageHeight - y4 + shiftX + width + pageY];
case 180:
return [x2 - shiftX - width + pageX, pageHeight - y4 + shiftY + pageY, x2 - shiftX + pageX, pageHeight - y4 + shiftY + height + pageY];
case 270:
return [x2 - shiftY - height + pageX, pageHeight - y4 - shiftX - width + pageY, x2 - shiftY + pageX, pageHeight - y4 - shiftX + pageY];
default:
throw new Error("Invalid rotation");
}
}
getRectInCurrentCoords(rect, pageHeight) {
const [x1, y1, x2, y22] = rect;
const width = x2 - x1;
const height = y22 - y1;
switch (this.rotation) {
case 0:
return [x1, pageHeight - y22, width, height];
case 90:
return [x1, pageHeight - y1, height, width];
case 180:
return [x2, pageHeight - y1, width, height];
case 270:
return [x2, pageHeight - y22, height, width];
default:
throw new Error("Invalid rotation");
}
}
getPDFRect() {
return this.getRect(0, 0);
}
getNonHCMColor() {
return this.color && _AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color));
}
onUpdatedColor() {
this.#comment?.onUpdatedColor();
}
getData() {
const {
comment: {
text: str2,
color: color2,
date,
opacity,
deleted,
richText
},
uid: id,
pageIndex,
creationDate,
modificationDate
} = this;
return {
id,
pageIndex,
rect: this.getPDFRect(),
richText,
contentsObj: {
str: str2
},
creationDate,
modificationDate: date || modificationDate,
popupRef: !deleted,
color: color2,
opacity
};
}
onceAdded(focus) {
}
isEmpty() {
return false;
}
enableEditMode() {
if (this.isInEditMode()) {
return false;
}
this.parent.setEditingState(false);
this.#isInEditMode = true;
return true;
}
disableEditMode() {
if (!this.isInEditMode()) {
return false;
}
this.parent.setEditingState(true);
this.#isInEditMode = false;
return true;
}
isInEditMode() {
return this.#isInEditMode;
}
shouldGetKeyboardEvents() {
return this.#isResizerEnabledForKeyboard;
}
needsToBeRebuilt() {
return this.div && !this.isAttachedToDOM;
}
get isOnScreen() {
const {
top,
left,
bottom,
right
} = this.getClientDimensions();
const {
innerHeight,
innerWidth
} = window;
return left < innerWidth && right > 0 && top < innerHeight && bottom > 0;
}
#addFocusListeners() {
if (this.#focusAC || !this.div) {
return;
}
this.#focusAC = new AbortController();
const signal = this._uiManager.combinedSignal(this.#focusAC);
this.div.addEventListener("focusin", this.focusin.bind(this), {
signal
});
this.div.addEventListener("focusout", this.focusout.bind(this), {
signal
});
}
rebuild() {
this.#addFocusListeners();
}
rotate(_angle) {
}
resize() {
}
serializeDeleted() {
return {
id: this.annotationElementId,
deleted: true,
pageIndex: this.pageIndex,
popupRef: this._initialData?.popupRef || ""
};
}
serialize(isForCopying = false, context = null) {
return {
annotationType: this.mode,
pageIndex: this.pageIndex,
rect: this.getPDFRect(),
rotation: this.rotation,
structTreeParentId: this._structTreeParentId,
popupRef: this._initialData?.popupRef || ""
};
}
static async deserialize(data, parent, uiManager) {
const editor = new this.prototype.constructor({
parent,
id: parent.getNextId(),
uiManager,
annotationElementId: data.annotationElementId,
creationDate: data.creationDate,
modificationDate: data.modificationDate
});
editor.rotation = data.rotation;
editor.#accessibilityData = data.accessibilityData;
editor._isCopy = data.isCopy || false;
const [pageWidth, pageHeight] = editor.pageDimensions;
const [x2, y4, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
editor.x = x2 / pageWidth;
editor.y = y4 / pageHeight;
editor.width = width / pageWidth;
editor.height = height / pageHeight;
return editor;
}
get hasBeenModified() {
return !!this.annotationElementId && (this.deleted || this.serialize() !== null);
}
remove() {
this.#focusAC?.abort();
this.#focusAC = null;
if (!this.isEmpty()) {
this.commit();
}
if (this.parent) {
this.parent.remove(this);
} else {
this._uiManager.removeEditor(this);
}
this.hideCommentPopup();
if (this.#moveInDOMTimeout) {
clearTimeout(this.#moveInDOMTimeout);
this.#moveInDOMTimeout = null;
}
this.#stopResizing();
this.removeEditToolbar();
if (this.#telemetryTimeouts) {
for (const timeout of this.#telemetryTimeouts.values()) {
clearTimeout(timeout);
}
this.#telemetryTimeouts = null;
}
this.parent = null;
this.#touchManager?.destroy();
this.#touchManager = null;
this.#fakeAnnotation?.remove();
this.#fakeAnnotation = null;
}
get isResizable() {
return false;
}
makeResizable() {
if (this.isResizable) {
this.#createResizers();
this.#resizersDiv.classList.remove("hidden");
}
}
get toolbarPosition() {
return null;
}
get commentButtonPosition() {
return this._uiManager.direction === "ltr" ? [1, 0] : [0, 0];
}
get commentButtonPositionInPage() {
const {
commentButtonPosition: [posX, posY]
} = this;
const [blX, blY, trX, trY] = this.getPDFRect();
return [_AnnotationEditor._round(blX + (trX - blX) * posX), _AnnotationEditor._round(blY + (trY - blY) * (1 - posY))];
}
get commentButtonColor() {
return this._uiManager.makeCommentColor(this.getNonHCMColor(), this.opacity);
}
get commentPopupPosition() {
return this.#comment.commentPopupPositionInLayer;
}
set commentPopupPosition(pos) {
this.#comment.commentPopupPositionInLayer = pos;
}
hasDefaultPopupPosition() {
return this.#comment.hasDefaultPopupPosition();
}
get commentButtonWidth() {
return this.#comment.commentButtonWidth;
}
get elementBeforePopup() {
return this.div;
}
setCommentButtonStates(options) {
this.#comment?.setCommentButtonStates(options);
}
keydown(event) {
if (!this.isResizable || event.target !== this.div || event.key !== "Enter") {
return;
}
this._uiManager.setSelected(this);
this.#savedDimensions = {
savedX: this.x,
savedY: this.y,
savedWidth: this.width,
savedHeight: this.height
};
const children = this.#resizersDiv.children;
if (!this.#allResizerDivs) {
this.#allResizerDivs = Array.from(children);
const boundResizerKeydown = this.#resizerKeydown.bind(this);
const boundResizerBlur = this.#resizerBlur.bind(this);
const signal = this._uiManager._signal;
for (const div of this.#allResizerDivs) {
const name = div.getAttribute("data-resizer-name");
div.setAttribute("role", "spinbutton");
div.addEventListener("keydown", boundResizerKeydown, {
signal
});
div.addEventListener("blur", boundResizerBlur, {
signal
});
div.addEventListener("focus", this.#resizerFocus.bind(this, name), {
signal
});
div.setAttribute("data-l10n-id", _AnnotationEditor._l10nResizer[name]);
}
}
const first = this.#allResizerDivs[0];
let firstPosition = 0;
for (const div of children) {
if (div === first) {
break;
}
firstPosition++;
}
const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4);
if (nextFirstPosition !== firstPosition) {
if (nextFirstPosition < firstPosition) {
for (let i8 = 0; i8 < firstPosition - nextFirstPosition; i8++) {
this.#resizersDiv.append(this.#resizersDiv.firstChild);
}
} else if (nextFirstPosition > firstPosition) {
for (let i8 = 0; i8 < nextFirstPosition - firstPosition; i8++) {
this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild);
}
}
let i7 = 0;
for (const child of children) {
const div = this.#allResizerDivs[i7++];
const name = div.getAttribute("data-resizer-name");
child.setAttribute("data-l10n-id", _AnnotationEditor._l10nResizer[name]);
}
}
this.#setResizerTabIndex(0);
this.#isResizerEnabledForKeyboard = true;
this.#resizersDiv.firstChild.focus({
focusVisible: true
});
event.preventDefault();
event.stopImmediatePropagation();
}
#resizerKeydown(event) {
_AnnotationEditor._resizerKeyboardManager.exec(this, event);
}
#resizerBlur(event) {
if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) {
this.#stopResizing();
}
}
#resizerFocus(name) {
this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : "";
}
#setResizerTabIndex(value) {
if (!this.#allResizerDivs) {
return;
}
for (const div of this.#allResizerDivs) {
div.tabIndex = value;
}
}
_resizeWithKeyboard(x2, y4) {
if (!this.#isResizerEnabledForKeyboard) {
return;
}
this.#resizerPointermove(this.#focusedResizerName, {
deltaX: x2,
deltaY: y4,
fromKeyboard: true
});
}
#stopResizing() {
this.#isResizerEnabledForKeyboard = false;
this.#setResizerTabIndex(-1);
this.#addResizeToUndoStack();
}
_stopResizingWithKeyboard() {
this.#stopResizing();
this.div.focus();
}
select() {
if (this.isSelected && this._editToolbar) {
this._editToolbar.show();
return;
}
this.isSelected = true;
this.makeResizable();
this.div?.classList.add("selectedEditor");
if (!this._editToolbar) {
this.addEditToolbar().then(() => {
if (this.div?.classList.contains("selectedEditor")) {
this._editToolbar?.show();
}
});
return;
}
this._editToolbar?.show();
this.#altText?.toggleAltTextBadge(false);
}
focus() {
if (this.div && !this.div.contains(document.activeElement)) {
setTimeout(() => this.div?.focus({
preventScroll: true
}), 0);
}
}
unselect() {
if (!this.isSelected) {
return;
}
this.isSelected = false;
this.#resizersDiv?.classList.add("hidden");
this.div?.classList.remove("selectedEditor");
if (this.div?.contains(document.activeElement)) {
this._uiManager.currentLayer.div.focus({
preventScroll: true
});
}
this._editToolbar?.hide();
this.#altText?.toggleAltTextBadge(true);
this.hideCommentPopup();
}
hideCommentPopup() {
if (this.hasComment) {
this._uiManager.toggleComment(null);
}
}
updateParams(type, value) {
}
disableEditing() {
}
enableEditing() {
}
get canChangeContent() {
return false;
}
enterInEditMode() {
if (!this.canChangeContent) {
return;
}
this.enableEditMode();
this.div.focus();
}
dblclick(event) {
if (event.target.nodeName === "BUTTON") {
return;
}
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.#isEditing;
}
set isEditing(value) {
this.#isEditing = value;
if (!this.parent) {
return;
}
if (value) {
this.parent.setSelected(this);
this.parent.setActiveEditor(this);
} else {
this.parent.setActiveEditor(null);
}
}
static get MIN_SIZE() {
return 16;
}
static canCreateNewEmptyEditor() {
return true;
}
get telemetryInitialData() {
return {
action: "added"
};
}
get telemetryFinalData() {
return null;
}
_reportTelemetry(data, mustWait = false) {
if (mustWait) {
this.#telemetryTimeouts ||= /* @__PURE__ */ new Map();
const {
action
} = data;
let timeout = this.#telemetryTimeouts.get(action);
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
this._reportTelemetry(data);
this.#telemetryTimeouts.delete(action);
if (this.#telemetryTimeouts.size === 0) {
this.#telemetryTimeouts = null;
}
}, _AnnotationEditor._telemetryTimeout);
this.#telemetryTimeouts.set(action, timeout);
return;
}
data.type ||= this.editorType;
this._uiManager._eventBus.dispatch("reporttelemetry", {
source: this,
details: {
type: "editing",
data
}
});
}
show(visible = this._isVisible) {
this.div.classList.toggle("hidden", !visible);
this._isVisible = visible;
}
enable() {
if (this.div) {
this.div.tabIndex = 0;
}
this.#disabled = false;
}
disable() {
if (this.div) {
this.div.tabIndex = -1;
}
this.#disabled = true;
}
updateFakeAnnotationElement(annotationLayer) {
if (!this.#fakeAnnotation && !this.deleted) {
this.#fakeAnnotation = annotationLayer.addFakeAnnotation(this);
return;
}
if (this.deleted) {
this.#fakeAnnotation.remove();
this.#fakeAnnotation = null;
return;
}
if (this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized) {
this.#fakeAnnotation.updateEdited({
rect: this.getPDFRect(),
popup: this.comment
});
}
}
renderAnnotationElement(annotation) {
if (this.deleted) {
annotation.hide();
return null;
}
let content = annotation.container.querySelector(".annotationContent");
if (!content) {
content = document.createElement("div");
content.classList.add("annotationContent", this.editorType);
annotation.container.prepend(content);
} else if (content.nodeName === "CANVAS") {
const canvas = content;
content = document.createElement("div");
content.classList.add("annotationContent", this.editorType);
canvas.before(content);
}
return content;
}
resetAnnotationElement(annotation) {
const {
firstChild
} = annotation.container;
if (firstChild?.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) {
firstChild.remove();
}
}
};
FakeEditor = class extends AnnotationEditor {
constructor(params) {
super(params);
this.annotationElementId = params.annotationElementId;
this.deleted = true;
}
serialize() {
return this.serializeDeleted();
}
};
SEED = 3285377520;
MASK_HIGH = 4294901760;
MASK_LOW = 65535;
MurmurHash3_64 = class {
constructor(seed) {
this.h1 = seed ? seed & 4294967295 : SEED;
this.h2 = seed ? seed & 4294967295 : SEED;
}
update(input) {
let data, length;
if (typeof input === "string") {
data = new Uint8Array(input.length * 2);
length = 0;
for (let i7 = 0, ii = input.length; i7 < ii; i7++) {
const code = input.charCodeAt(i7);
if (code <= 255) {
data[length++] = code;
} else {
data[length++] = code >>> 8;
data[length++] = code & 255;
}
}
} else if (ArrayBuffer.isView(input)) {
data = input.slice();
length = data.byteLength;
} else {
throw new Error("Invalid data format, must be a string or TypedArray.");
}
const blockCounts = length >> 2;
const tailLength = length - blockCounts * 4;
const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
let k1 = 0, k2 = 0;
let h12 = this.h1, h23 = this.h2;
const C1 = 3432918353, C22 = 461845907;
const C1_LOW = C1 & MASK_LOW, C2_LOW = C22 & MASK_LOW;
for (let i7 = 0; i7 < blockCounts; i7++) {
if (i7 & 1) {
k1 = dataUint32[i7];
k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
k1 = k1 << 15 | k1 >>> 17;
k1 = k1 * C22 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
h12 ^= k1;
h12 = h12 << 13 | h12 >>> 19;
h12 = h12 * 5 + 3864292196;
} else {
k2 = dataUint32[i7];
k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
k2 = k2 << 15 | k2 >>> 17;
k2 = k2 * C22 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
h23 ^= k2;
h23 = h23 << 13 | h23 >>> 19;
h23 = h23 * 5 + 3864292196;
}
}
k1 = 0;
switch (tailLength) {
case 3:
k1 ^= data[blockCounts * 4 + 2] << 16;
case 2:
k1 ^= data[blockCounts * 4 + 1] << 8;
case 1:
k1 ^= data[blockCounts * 4];
k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
k1 = k1 << 15 | k1 >>> 17;
k1 = k1 * C22 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
if (blockCounts & 1) {
h12 ^= k1;
} else {
h23 ^= k1;
}
}
this.h1 = h12;
this.h2 = h23;
}
hexdigest() {
let h12 = this.h1, h23 = this.h2;
h12 ^= h23 >>> 1;
h12 = h12 * 3981806797 & MASK_HIGH | h12 * 36045 & MASK_LOW;
h23 = h23 * 4283543511 & MASK_HIGH | ((h23 << 16 | h12 >>> 16) * 2950163797 & MASK_HIGH) >>> 16;
h12 ^= h23 >>> 1;
h12 = h12 * 444984403 & MASK_HIGH | h12 * 60499 & MASK_LOW;
h23 = h23 * 3301882366 & MASK_HIGH | ((h23 << 16 | h12 >>> 16) * 3120437893 & MASK_HIGH) >>> 16;
h12 ^= h23 >>> 1;
return (h12 >>> 0).toString(16).padStart(8, "0") + (h23 >>> 0).toString(16).padStart(8, "0");
}
};
SerializableEmpty = Object.freeze({
map: null,
hash: "",
transfer: void 0
});
AnnotationStorage = class {
#modified = false;
#modifiedIds = null;
#editorsMap = null;
#storage = /* @__PURE__ */ new Map();
constructor() {
this.onSetModified = null;
this.onResetModified = null;
this.onAnnotationEditor = null;
}
getValue(key, defaultValue) {
const value = this.#storage.get(key);
if (value === void 0) {
return defaultValue;
}
return Object.assign(defaultValue, value);
}
getRawValue(key) {
return this.#storage.get(key);
}
remove(key) {
const storedValue = this.#storage.get(key);
if (storedValue === void 0) {
return;
}
if (storedValue instanceof AnnotationEditor) {
this.#editorsMap.delete(storedValue.annotationElementId);
}
this.#storage.delete(key);
if (this.#storage.size === 0) {
this.resetModified();
}
if (typeof this.onAnnotationEditor === "function") {
for (const value of this.#storage.values()) {
if (value instanceof AnnotationEditor) {
return;
}
}
this.onAnnotationEditor(null);
}
}
setValue(key, value) {
const obj = this.#storage.get(key);
let modified = false;
if (obj !== void 0) {
for (const [entry, val2] of Object.entries(value)) {
if (obj[entry] !== val2) {
modified = true;
obj[entry] = val2;
}
}
} else {
modified = true;
this.#storage.set(key, value);
}
if (modified) {
this.#setModified();
}
if (value instanceof AnnotationEditor) {
(this.#editorsMap ||= /* @__PURE__ */ new Map()).set(value.annotationElementId, value);
if (typeof this.onAnnotationEditor === "function") {
this.onAnnotationEditor(value.constructor._type);
}
}
}
has(key) {
return this.#storage.has(key);
}
get size() {
return this.#storage.size;
}
#setModified() {
if (!this.#modified) {
this.#modified = true;
if (typeof this.onSetModified === "function") {
this.onSetModified();
}
}
}
resetModified() {
if (this.#modified) {
this.#modified = false;
if (typeof this.onResetModified === "function") {
this.onResetModified();
}
}
}
get print() {
return new PrintAnnotationStorage(this);
}
get serializable() {
if (this.#storage.size === 0) {
return SerializableEmpty;
}
const map3 = /* @__PURE__ */ new Map(), hash = new MurmurHash3_64(), transfer = [];
const context = /* @__PURE__ */ Object.create(null);
let hasBitmap = false;
for (const [key, val2] of this.#storage) {
const serialized = val2 instanceof AnnotationEditor ? val2.serialize(false, context) : val2;
if (serialized) {
map3.set(key, serialized);
hash.update(`${key}:${JSON.stringify(serialized)}`);
hasBitmap ||= !!serialized.bitmap;
}
}
if (hasBitmap) {
for (const value of map3.values()) {
if (value.bitmap) {
transfer.push(value.bitmap);
}
}
}
return map3.size > 0 ? {
map: map3,
hash: hash.hexdigest(),
transfer
} : SerializableEmpty;
}
get editorStats() {
let stats = null;
const typeToEditor = /* @__PURE__ */ new Map();
let numberOfEditedComments = 0;
let numberOfDeletedComments = 0;
for (const value of this.#storage.values()) {
if (!(value instanceof AnnotationEditor)) {
if (value.popup) {
if (value.popup.deleted) {
numberOfDeletedComments += 1;
} else {
numberOfEditedComments += 1;
}
}
continue;
}
if (value.isCommentDeleted) {
numberOfDeletedComments += 1;
} else if (value.hasEditedComment) {
numberOfEditedComments += 1;
}
const editorStats = value.telemetryFinalData;
if (!editorStats) {
continue;
}
const {
type
} = editorStats;
if (!typeToEditor.has(type)) {
typeToEditor.set(type, Object.getPrototypeOf(value).constructor);
}
stats ||= /* @__PURE__ */ Object.create(null);
const map3 = stats[type] ||= /* @__PURE__ */ new Map();
for (const [key, val2] of Object.entries(editorStats)) {
if (key === "type") {
continue;
}
let counters = map3.get(key);
if (!counters) {
counters = /* @__PURE__ */ new Map();
map3.set(key, counters);
}
const count = counters.get(val2) ?? 0;
counters.set(val2, count + 1);
}
}
if (numberOfDeletedComments > 0 || numberOfEditedComments > 0) {
stats ||= /* @__PURE__ */ Object.create(null);
stats.comments = {
deleted: numberOfDeletedComments,
edited: numberOfEditedComments
};
}
if (!stats) {
return null;
}
for (const [type, editor] of typeToEditor) {
stats[type] = editor.computeTelemetryFinalData(stats[type]);
}
return stats;
}
resetModifiedIds() {
this.#modifiedIds = null;
}
updateEditor(annotationId, data) {
const value = this.#editorsMap?.get(annotationId);
if (value) {
value.updateFromAnnotationLayer(data);
return true;
}
return false;
}
getEditor(annotationId) {
return this.#editorsMap?.get(annotationId) || null;
}
get modifiedIds() {
if (this.#modifiedIds) {
return this.#modifiedIds;
}
const ids = [];
if (this.#editorsMap) {
for (const value of this.#editorsMap.values()) {
if (!value.serialize()) {
continue;
}
ids.push(value.annotationElementId);
}
}
return this.#modifiedIds = {
ids: new Set(ids),
hash: ids.join(",")
};
}
[Symbol.iterator]() {
return this.#storage.entries();
}
};
PrintAnnotationStorage = class extends AnnotationStorage {
#serializable;
constructor(parent) {
super();
const {
map: map3,
hash,
transfer
} = parent.serializable;
const clone3 = structuredClone(map3, transfer ? {
transfer
} : null);
this.#serializable = {
map: clone3,
hash,
transfer
};
}
get print() {
unreachable("Should not call PrintAnnotationStorage.print");
}
get serializable() {
return this.#serializable;
}
get modifiedIds() {
return shadow(this, "modifiedIds", {
ids: /* @__PURE__ */ new Set(),
hash: ""
});
}
};
FontLoader = class {
#systemFonts = /* @__PURE__ */ new Set();
constructor({
ownerDocument = globalThis.document,
styleElement = null
}) {
this._document = ownerDocument;
this.nativeFontFaces = /* @__PURE__ */ new Set();
this.styleElement = null;
this.loadingRequests = [];
this.loadTestFontId = 0;
}
addNativeFontFace(nativeFontFace) {
this.nativeFontFaces.add(nativeFontFace);
this._document.fonts.add(nativeFontFace);
}
removeNativeFontFace(nativeFontFace) {
this.nativeFontFaces.delete(nativeFontFace);
this._document.fonts.delete(nativeFontFace);
}
insertRule(rule) {
if (!this.styleElement) {
this.styleElement = this._document.createElement("style");
this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
}
const styleSheet = this.styleElement.sheet;
styleSheet.insertRule(rule, styleSheet.cssRules.length);
}
clear() {
for (const nativeFontFace of this.nativeFontFaces) {
this._document.fonts.delete(nativeFontFace);
}
this.nativeFontFaces.clear();
this.#systemFonts.clear();
if (this.styleElement) {
this.styleElement.remove();
this.styleElement = null;
}
}
async loadSystemFont({
systemFontInfo: info2,
disableFontFace,
_inspectFont
}) {
if (!info2 || this.#systemFonts.has(info2.loadedName)) {
return;
}
assert(!disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set.");
if (this.isFontLoadingAPISupported) {
const {
loadedName,
src,
style
} = info2;
const fontFace = new FontFace(loadedName, src, style);
this.addNativeFontFace(fontFace);
try {
await fontFace.load();
this.#systemFonts.add(loadedName);
_inspectFont?.(info2);
} catch {
warn(`Cannot load system font: ${info2.baseFontName}, installing it could help to improve PDF rendering.`);
this.removeNativeFontFace(fontFace);
}
return;
}
unreachable("Not implemented: loadSystemFont without the Font Loading API.");
}
async bind(font) {
if (font.attached || font.missingFile && !font.systemFontInfo) {
return;
}
font.attached = true;
if (font.systemFontInfo) {
await this.loadSystemFont(font);
return;
}
if (this.isFontLoadingAPISupported) {
const nativeFontFace = font.createNativeFontFace();
if (nativeFontFace) {
this.addNativeFontFace(nativeFontFace);
try {
await nativeFontFace.loaded;
} catch (ex) {
warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
font.disableFontFace = true;
throw ex;
}
}
return;
}
const rule = font.createFontFaceRule();
if (rule) {
this.insertRule(rule);
if (this.isSyncFontLoadingSupported) {
return;
}
await new Promise((resolve2) => {
const request = this._queueLoadingCallback(resolve2);
this._prepareFontLoadEvent(font, request);
});
}
}
get isFontLoadingAPISupported() {
const hasFonts = !!this._document?.fonts;
return shadow(this, "isFontLoadingAPISupported", hasFonts);
}
get isSyncFontLoadingSupported() {
return shadow(this, "isSyncFontLoadingSupported", isNodeJS || util_FeatureTest.platform.isFirefox);
}
_queueLoadingCallback(callback2) {
function completeRequest() {
assert(!request.done, "completeRequest() cannot be called twice.");
request.done = true;
while (loadingRequests.length > 0 && loadingRequests[0].done) {
const otherRequest = loadingRequests.shift();
setTimeout(otherRequest.callback, 0);
}
}
const {
loadingRequests
} = this;
const request = {
done: false,
complete: completeRequest,
callback: callback2
};
loadingRequests.push(request);
return request;
}
get _loadTestFont() {
const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
return shadow(this, "_loadTestFont", testFont);
}
_prepareFontLoadEvent(font, request) {
function int32(data2, offset) {
return data2.charCodeAt(offset) << 24 | data2.charCodeAt(offset + 1) << 16 | data2.charCodeAt(offset + 2) << 8 | data2.charCodeAt(offset + 3) & 255;
}
function spliceString(s6, offset, remove, insert) {
const chunk1 = s6.substring(0, offset);
const chunk2 = s6.substring(offset + remove);
return chunk1 + insert + chunk2;
}
let i7, ii;
const canvas = this._document.createElement("canvas");
canvas.width = 1;
canvas.height = 1;
const ctx = canvas.getContext("2d");
let called = 0;
function isFontReady(name, callback2) {
if (++called > 30) {
warn("Load test font never loaded.");
callback2();
return;
}
ctx.font = "30px " + name;
ctx.fillText(".", 0, 20);
const imageData = ctx.getImageData(0, 0, 1, 1);
if (imageData.data[3] > 0) {
callback2();
return;
}
setTimeout(isFontReady.bind(null, name, callback2));
}
const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
let data = this._loadTestFont;
const COMMENT_OFFSET = 976;
data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
const CFF_CHECKSUM_OFFSET = 16;
const XXXX_VALUE = 1482184792;
let checksum = int32(data, CFF_CHECKSUM_OFFSET);
for (i7 = 0, ii = loadTestFontId.length - 3; i7 < ii; i7 += 4) {
checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i7) | 0;
}
if (i7 < loadTestFontId.length) {
checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i7) | 0;
}
data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
const url = `url(data:font/opentype;base64,${btoa(data)});`;
const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
this.insertRule(rule);
const div = this._document.createElement("div");
div.style.visibility = "hidden";
div.style.width = div.style.height = "10px";
div.style.position = "absolute";
div.style.top = div.style.left = "0px";
for (const name of [font.loadedName, loadTestFontId]) {
const span = this._document.createElement("span");
span.textContent = "Hi";
span.style.fontFamily = name;
div.append(span);
}
this._document.body.append(div);
isFontReady(loadTestFontId, () => {
div.remove();
request.complete();
});
}
};
FontFaceObject = class {
#fontData;
constructor(translatedData, inspectFont = null, extra, charProcOperatorList) {
this.compiledGlyphs = /* @__PURE__ */ Object.create(null);
this.#fontData = translatedData;
this._inspectFont = inspectFont;
if (extra) {
Object.assign(this, extra);
}
if (charProcOperatorList) {
this.charProcOperatorList = charProcOperatorList;
}
}
createNativeFontFace() {
if (!this.data || this.disableFontFace) {
return null;
}
let nativeFontFace;
if (!this.cssFontInfo) {
nativeFontFace = new FontFace(this.loadedName, this.data, {});
} else {
const css2 = {
weight: this.cssFontInfo.fontWeight
};
if (this.cssFontInfo.italicAngle) {
css2.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
}
nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css2);
}
this._inspectFont?.(this);
return nativeFontFace;
}
createFontFaceRule() {
if (!this.data || this.disableFontFace) {
return null;
}
const url = `url(data:${this.mimetype};base64,${toBase64Util(this.data)});`;
let rule;
if (!this.cssFontInfo) {
rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
} else {
let css2 = `font-weight: ${this.cssFontInfo.fontWeight};`;
if (this.cssFontInfo.italicAngle) {
css2 += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
}
rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css2}src:${url}}`;
}
this._inspectFont?.(this, url);
return rule;
}
getPathGenerator(objs, character) {
if (this.compiledGlyphs[character] !== void 0) {
return this.compiledGlyphs[character];
}
const objId = this.loadedName + "_path_" + character;
let cmds;
try {
cmds = objs.get(objId);
} catch (ex) {
warn(`getPathGenerator - ignoring character: "${ex}".`);
}
const path6 = makePathFromDrawOPS(cmds);
if (!this.fontExtraProperties) {
objs.delete(objId);
}
return this.compiledGlyphs[character] = path6;
}
get black() {
return this.#fontData.black;
}
get bold() {
return this.#fontData.bold;
}
get disableFontFace() {
return this.#fontData.disableFontFace ?? false;
}
get fontExtraProperties() {
return this.#fontData.fontExtraProperties ?? false;
}
get isInvalidPDFjsFont() {
return this.#fontData.isInvalidPDFjsFont;
}
get isType3Font() {
return this.#fontData.isType3Font;
}
get italic() {
return this.#fontData.italic;
}
get missingFile() {
return this.#fontData.missingFile;
}
get remeasure() {
return this.#fontData.remeasure;
}
get vertical() {
return this.#fontData.vertical;
}
get ascent() {
return this.#fontData.ascent;
}
get defaultWidth() {
return this.#fontData.defaultWidth;
}
get descent() {
return this.#fontData.descent;
}
get bbox() {
return this.#fontData.bbox;
}
get fontMatrix() {
return this.#fontData.fontMatrix;
}
get fallbackName() {
return this.#fontData.fallbackName;
}
get loadedName() {
return this.#fontData.loadedName;
}
get mimetype() {
return this.#fontData.mimetype;
}
get name() {
return this.#fontData.name;
}
get data() {
return this.#fontData.data;
}
clearData() {
this.#fontData.clearData();
}
get cssFontInfo() {
return this.#fontData.cssFontInfo;
}
get systemFontInfo() {
return this.#fontData.systemFontInfo;
}
get defaultVMetrics() {
return this.#fontData.defaultVMetrics;
}
};
CssFontInfo = class _CssFontInfo {
#buffer;
#view;
#decoder;
static strings = ["fontFamily", "fontWeight", "italicAngle"];
static write(info2) {
const encoder = new TextEncoder();
const encodedStrings = {};
let stringsLength = 0;
for (const prop of _CssFontInfo.strings) {
const encoded = encoder.encode(info2[prop]);
encodedStrings[prop] = encoded;
stringsLength += 4 + encoded.length;
}
const buffer = new ArrayBuffer(stringsLength);
const data = new Uint8Array(buffer);
const view = new DataView(buffer);
let offset = 0;
for (const prop of _CssFontInfo.strings) {
const encoded = encodedStrings[prop];
const length = encoded.length;
view.setUint32(offset, length);
data.set(encoded, offset + 4);
offset += 4 + length;
}
assert(offset === buffer.byteLength, "CssFontInfo.write: Buffer overflow");
return buffer;
}
constructor(buffer) {
this.#buffer = buffer;
this.#view = new DataView(this.#buffer);
this.#decoder = new TextDecoder();
}
#readString(index2) {
assert(index2 < _CssFontInfo.strings.length, "Invalid string index");
let offset = 0;
for (let i7 = 0; i7 < index2; i7++) {
offset += this.#view.getUint32(offset) + 4;
}
const length = this.#view.getUint32(offset);
return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length));
}
get fontFamily() {
return this.#readString(0);
}
get fontWeight() {
return this.#readString(1);
}
get italicAngle() {
return this.#readString(2);
}
};
SystemFontInfo = class _SystemFontInfo {
#buffer;
#view;
#decoder;
static strings = ["css", "loadedName", "baseFontName", "src"];
static write(info2) {
const encoder = new TextEncoder();
const encodedStrings = {};
let stringsLength = 0;
for (const prop of _SystemFontInfo.strings) {
const encoded = encoder.encode(info2[prop]);
encodedStrings[prop] = encoded;
stringsLength += 4 + encoded.length;
}
stringsLength += 4;
let encodedStyleStyle, encodedStyleWeight, lengthEstimate = 1 + stringsLength;
if (info2.style) {
encodedStyleStyle = encoder.encode(info2.style.style);
encodedStyleWeight = encoder.encode(info2.style.weight);
lengthEstimate += 4 + encodedStyleStyle.length + 4 + encodedStyleWeight.length;
}
const buffer = new ArrayBuffer(lengthEstimate);
const data = new Uint8Array(buffer);
const view = new DataView(buffer);
let offset = 0;
view.setUint8(offset++, info2.guessFallback ? 1 : 0);
view.setUint32(offset, 0);
offset += 4;
stringsLength = 0;
for (const prop of _SystemFontInfo.strings) {
const encoded = encodedStrings[prop];
const length = encoded.length;
stringsLength += 4 + length;
view.setUint32(offset, length);
data.set(encoded, offset + 4);
offset += 4 + length;
}
view.setUint32(offset - stringsLength - 4, stringsLength);
if (info2.style) {
view.setUint32(offset, encodedStyleStyle.length);
data.set(encodedStyleStyle, offset + 4);
offset += 4 + encodedStyleStyle.length;
view.setUint32(offset, encodedStyleWeight.length);
data.set(encodedStyleWeight, offset + 4);
offset += 4 + encodedStyleWeight.length;
}
assert(offset <= buffer.byteLength, "SubstitionInfo.write: Buffer overflow");
return buffer.transferToFixedLength(offset);
}
constructor(buffer) {
this.#buffer = buffer;
this.#view = new DataView(this.#buffer);
this.#decoder = new TextDecoder();
}
get guessFallback() {
return this.#view.getUint8(0) !== 0;
}
#readString(index2) {
assert(index2 < _SystemFontInfo.strings.length, "Invalid string index");
let offset = 5;
for (let i7 = 0; i7 < index2; i7++) {
offset += this.#view.getUint32(offset) + 4;
}
const length = this.#view.getUint32(offset);
return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length));
}
get css() {
return this.#readString(0);
}
get loadedName() {
return this.#readString(1);
}
get baseFontName() {
return this.#readString(2);
}
get src() {
return this.#readString(3);
}
get style() {
let offset = 1;
offset += 4 + this.#view.getUint32(offset);
const styleLength = this.#view.getUint32(offset);
const style = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, styleLength));
offset += 4 + styleLength;
const weightLength = this.#view.getUint32(offset);
const weight = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, weightLength));
return {
style,
weight
};
}
};
FontInfo = class _FontInfo {
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 + 2 * 4;
static #OFFSET_DEFAULT_VMETRICS = this.#OFFSET_FONT_MATRIX + 1 + 8 * 6;
static #OFFSET_STRINGS = this.#OFFSET_DEFAULT_VMETRICS + 1 + 2 * 3;
#buffer;
#decoder;
#view;
constructor({
data,
extra
}) {
this.#buffer = data;
this.#decoder = new TextDecoder();
this.#view = new DataView(this.#buffer);
if (extra) {
Object.assign(this, extra);
}
}
#readBoolean(index2) {
assert(index2 < _FontInfo.bools.length, "Invalid boolean index");
const byteOffset = Math.floor(index2 / 4);
const bitOffset = index2 * 2 % 8;
const value = this.#view.getUint8(byteOffset) >> bitOffset & 3;
return value === 0 ? void 0 : value === 2;
}
get black() {
return this.#readBoolean(0);
}
get bold() {
return this.#readBoolean(1);
}
get disableFontFace() {
return this.#readBoolean(2);
}
get fontExtraProperties() {
return this.#readBoolean(3);
}
get isInvalidPDFjsFont() {
return this.#readBoolean(4);
}
get isType3Font() {
return this.#readBoolean(5);
}
get italic() {
return this.#readBoolean(6);
}
get missingFile() {
return this.#readBoolean(7);
}
get remeasure() {
return this.#readBoolean(8);
}
get vertical() {
return this.#readBoolean(9);
}
#readNumber(index2) {
assert(index2 < _FontInfo.numbers.length, "Invalid number index");
return this.#view.getFloat64(_FontInfo.#OFFSET_NUMBERS + index2 * 8);
}
get ascent() {
return this.#readNumber(0);
}
get defaultWidth() {
return this.#readNumber(1);
}
get descent() {
return this.#readNumber(2);
}
get bbox() {
let offset = _FontInfo.#OFFSET_BBOX;
const numCoords = this.#view.getUint8(offset);
if (numCoords === 0) {
return void 0;
}
offset += 1;
const bbox = [];
for (let i7 = 0; i7 < 4; i7++) {
bbox.push(this.#view.getInt16(offset, true));
offset += 2;
}
return bbox;
}
get fontMatrix() {
let offset = _FontInfo.#OFFSET_FONT_MATRIX;
const numPoints = this.#view.getUint8(offset);
if (numPoints === 0) {
return void 0;
}
offset += 1;
const fontMatrix = [];
for (let i7 = 0; i7 < 6; i7++) {
fontMatrix.push(this.#view.getFloat64(offset, true));
offset += 8;
}
return fontMatrix;
}
get defaultVMetrics() {
let offset = _FontInfo.#OFFSET_DEFAULT_VMETRICS;
const numMetrics = this.#view.getUint8(offset);
if (numMetrics === 0) {
return void 0;
}
offset += 1;
const defaultVMetrics = [];
for (let i7 = 0; i7 < 3; i7++) {
defaultVMetrics.push(this.#view.getInt16(offset, true));
offset += 2;
}
return defaultVMetrics;
}
#readString(index2) {
assert(index2 < _FontInfo.strings.length, "Invalid string index");
let offset = _FontInfo.#OFFSET_STRINGS + 4;
for (let i7 = 0; i7 < index2; i7++) {
offset += this.#view.getUint32(offset) + 4;
}
const length = this.#view.getUint32(offset);
const stringData = new Uint8Array(length);
stringData.set(new Uint8Array(this.#buffer, offset + 4, length));
return this.#decoder.decode(stringData);
}
get fallbackName() {
return this.#readString(0);
}
get loadedName() {
return this.#readString(1);
}
get mimetype() {
return this.#readString(2);
}
get name() {
return this.#readString(3);
}
get data() {
let offset = _FontInfo.#OFFSET_STRINGS;
const stringsLength = this.#view.getUint32(offset);
offset += 4 + stringsLength;
const systemFontInfoLength = this.#view.getUint32(offset);
offset += 4 + systemFontInfoLength;
const cssFontInfoLength = this.#view.getUint32(offset);
offset += 4 + cssFontInfoLength;
const length = this.#view.getUint32(offset);
if (length === 0) {
return void 0;
}
return new Uint8Array(this.#buffer, offset + 4, length);
}
clearData() {
let offset = _FontInfo.#OFFSET_STRINGS;
const stringsLength = this.#view.getUint32(offset);
offset += 4 + stringsLength;
const systemFontInfoLength = this.#view.getUint32(offset);
offset += 4 + systemFontInfoLength;
const cssFontInfoLength = this.#view.getUint32(offset);
offset += 4 + cssFontInfoLength;
const length = this.#view.getUint32(offset);
const data = new Uint8Array(this.#buffer, offset + 4, length);
data.fill(0);
this.#view.setUint32(offset, 0);
}
get cssFontInfo() {
let offset = _FontInfo.#OFFSET_STRINGS;
const stringsLength = this.#view.getUint32(offset);
offset += 4 + stringsLength;
const systemFontInfoLength = this.#view.getUint32(offset);
offset += 4 + systemFontInfoLength;
const cssFontInfoLength = this.#view.getUint32(offset);
if (cssFontInfoLength === 0) {
return null;
}
const cssFontInfoData = new Uint8Array(cssFontInfoLength);
cssFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, cssFontInfoLength));
return new CssFontInfo(cssFontInfoData.buffer);
}
get systemFontInfo() {
let offset = _FontInfo.#OFFSET_STRINGS;
const stringsLength = this.#view.getUint32(offset);
offset += 4 + stringsLength;
const systemFontInfoLength = this.#view.getUint32(offset);
if (systemFontInfoLength === 0) {
return null;
}
const systemFontInfoData = new Uint8Array(systemFontInfoLength);
systemFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, systemFontInfoLength));
return new SystemFontInfo(systemFontInfoData.buffer);
}
static write(font) {
const systemFontInfoBuffer = font.systemFontInfo ? SystemFontInfo.write(font.systemFontInfo) : null;
const cssFontInfoBuffer = font.cssFontInfo ? CssFontInfo.write(font.cssFontInfo) : null;
const encoder = new TextEncoder();
const encodedStrings = {};
let stringsLength = 0;
for (const prop of _FontInfo.strings) {
encodedStrings[prop] = encoder.encode(font[prop]);
stringsLength += 4 + encodedStrings[prop].length;
}
const lengthEstimate = _FontInfo.#OFFSET_STRINGS + 4 + stringsLength + 4 + (systemFontInfoBuffer ? systemFontInfoBuffer.byteLength : 0) + 4 + (cssFontInfoBuffer ? cssFontInfoBuffer.byteLength : 0) + 4 + (font.data ? font.data.length : 0);
const buffer = new ArrayBuffer(lengthEstimate);
const data = new Uint8Array(buffer);
const view = new DataView(buffer);
let offset = 0;
const numBools = _FontInfo.bools.length;
let boolByte = 0, boolBit = 0;
for (let i7 = 0; i7 < numBools; i7++) {
const value = font[_FontInfo.bools[i7]];
const bits = value === void 0 ? 0 : value ? 2 : 1;
boolByte |= bits << boolBit;
boolBit += 2;
if (boolBit === 8 || i7 === numBools - 1) {
view.setUint8(offset++, boolByte);
boolByte = 0;
boolBit = 0;
}
}
assert(offset === _FontInfo.#OFFSET_NUMBERS, "FontInfo.write: Boolean properties offset mismatch");
for (const prop of _FontInfo.numbers) {
view.setFloat64(offset, font[prop]);
offset += 8;
}
assert(offset === _FontInfo.#OFFSET_BBOX, "FontInfo.write: Number properties offset mismatch");
if (font.bbox) {
view.setUint8(offset++, 4);
for (const coord of font.bbox) {
view.setInt16(offset, coord, true);
offset += 2;
}
} else {
view.setUint8(offset++, 0);
offset += 2 * 4;
}
assert(offset === _FontInfo.#OFFSET_FONT_MATRIX, "FontInfo.write: BBox properties offset mismatch");
if (font.fontMatrix) {
view.setUint8(offset++, 6);
for (const point of font.fontMatrix) {
view.setFloat64(offset, point, true);
offset += 8;
}
} else {
view.setUint8(offset++, 0);
offset += 8 * 6;
}
assert(offset === _FontInfo.#OFFSET_DEFAULT_VMETRICS, "FontInfo.write: FontMatrix properties offset mismatch");
if (font.defaultVMetrics) {
view.setUint8(offset++, 1);
for (const metric of font.defaultVMetrics) {
view.setInt16(offset, metric, true);
offset += 2;
}
} else {
view.setUint8(offset++, 0);
offset += 3 * 2;
}
assert(offset === _FontInfo.#OFFSET_STRINGS, "FontInfo.write: DefaultVMetrics properties offset mismatch");
view.setUint32(_FontInfo.#OFFSET_STRINGS, 0);
offset += 4;
for (const prop of _FontInfo.strings) {
const encoded = encodedStrings[prop];
const length = encoded.length;
view.setUint32(offset, length);
data.set(encoded, offset + 4);
offset += 4 + length;
}
view.setUint32(_FontInfo.#OFFSET_STRINGS, offset - _FontInfo.#OFFSET_STRINGS - 4);
if (!systemFontInfoBuffer) {
view.setUint32(offset, 0);
offset += 4;
} else {
const length = systemFontInfoBuffer.byteLength;
view.setUint32(offset, length);
assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at systemFontInfo");
data.set(new Uint8Array(systemFontInfoBuffer), offset + 4);
offset += 4 + length;
}
if (!cssFontInfoBuffer) {
view.setUint32(offset, 0);
offset += 4;
} else {
const length = cssFontInfoBuffer.byteLength;
view.setUint32(offset, length);
assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at cssFontInfo");
data.set(new Uint8Array(cssFontInfoBuffer), offset + 4);
offset += 4 + length;
}
if (font.data === void 0) {
view.setUint32(offset, 0);
offset += 4;
} else {
view.setUint32(offset, font.data.length);
data.set(font.data, offset + 4);
offset += 4 + font.data.length;
}
assert(offset <= buffer.byteLength, "FontInfo.write: Buffer overflow");
return buffer.transferToFixedLength(offset);
}
};
PatternInfo = class _PatternInfo {
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;
constructor(buffer) {
this.buffer = buffer;
this.view = new DataView(buffer);
this.data = new Uint8Array(buffer);
}
static write(ir) {
let kind, bbox = null, coords = [], colors2 = [], colorStops = [], figures = [], shadingType = null, background = null;
switch (ir[0]) {
case "RadialAxial":
kind = ir[1] === "axial" ? 1 : 2;
bbox = ir[2];
colorStops = ir[3];
if (kind === 1) {
coords.push(...ir[4], ...ir[5]);
} else {
coords.push(ir[4][0], ir[4][1], ir[6], ir[5][0], ir[5][1], ir[7]);
}
break;
case "Mesh":
kind = 3;
shadingType = ir[1];
coords = ir[2];
colors2 = ir[3];
figures = ir[4] || [];
bbox = ir[6];
background = ir[7];
break;
default:
throw new Error(`Unsupported pattern type: ${ir[0]}`);
}
const nCoord = Math.floor(coords.length / 2);
const nColor = Math.floor(colors2.length / 3);
const nStop = colorStops.length;
const nFigures = figures.length;
let figuresSize = 0;
for (const figure of figures) {
figuresSize += 1;
figuresSize = Math.ceil(figuresSize / 4) * 4;
figuresSize += 4 + figure.coords.length * 4;
figuresSize += 4 + figure.colors.length * 4;
if (figure.verticesPerRow !== void 0) {
figuresSize += 4;
}
}
const byteLen = 20 + nCoord * 8 + nColor * 3 + nStop * 8 + (bbox ? 16 : 0) + (background ? 3 : 0) + figuresSize;
const buffer = new ArrayBuffer(byteLen);
const dataView = new DataView(buffer);
const u8data = new Uint8Array(buffer);
dataView.setUint8(_PatternInfo.#KIND, kind);
dataView.setUint8(_PatternInfo.#HAS_BBOX, bbox ? 1 : 0);
dataView.setUint8(_PatternInfo.#HAS_BACKGROUND, background ? 1 : 0);
dataView.setUint8(_PatternInfo.#SHADING_TYPE, shadingType);
dataView.setUint32(_PatternInfo.#N_COORD, nCoord, true);
dataView.setUint32(_PatternInfo.#N_COLOR, nColor, true);
dataView.setUint32(_PatternInfo.#N_STOP, nStop, true);
dataView.setUint32(_PatternInfo.#N_FIGURES, nFigures, true);
let offset = 20;
const coordsView = new Float32Array(buffer, offset, nCoord * 2);
coordsView.set(coords);
offset += nCoord * 8;
u8data.set(colors2, offset);
offset += nColor * 3;
for (const [pos, hex2] of colorStops) {
dataView.setFloat32(offset, pos, true);
offset += 4;
dataView.setUint32(offset, parseInt(hex2.slice(1), 16), true);
offset += 4;
}
if (bbox) {
for (const v4 of bbox) {
dataView.setFloat32(offset, v4, true);
offset += 4;
}
}
if (background) {
u8data.set(background, offset);
offset += 3;
}
for (let i7 = 0; i7 < figures.length; i7++) {
const figure = figures[i7];
dataView.setUint8(offset, figure.type);
offset += 1;
offset = Math.ceil(offset / 4) * 4;
dataView.setUint32(offset, figure.coords.length, true);
offset += 4;
const figureCoordsView = new Int32Array(buffer, offset, figure.coords.length);
figureCoordsView.set(figure.coords);
offset += figure.coords.length * 4;
dataView.setUint32(offset, figure.colors.length, true);
offset += 4;
const colorsView = new Int32Array(buffer, offset, figure.colors.length);
colorsView.set(figure.colors);
offset += figure.colors.length * 4;
if (figure.verticesPerRow !== void 0) {
dataView.setUint32(offset, figure.verticesPerRow, true);
offset += 4;
}
}
return buffer;
}
getIR() {
const dataView = this.view;
const kind = this.data[_PatternInfo.#KIND];
const hasBBox = !!this.data[_PatternInfo.#HAS_BBOX];
const hasBackground = !!this.data[_PatternInfo.#HAS_BACKGROUND];
const nCoord = dataView.getUint32(_PatternInfo.#N_COORD, true);
const nColor = dataView.getUint32(_PatternInfo.#N_COLOR, true);
const nStop = dataView.getUint32(_PatternInfo.#N_STOP, true);
const nFigures = dataView.getUint32(_PatternInfo.#N_FIGURES, true);
let offset = 20;
const coords = new Float32Array(this.buffer, offset, nCoord * 2);
offset += nCoord * 8;
const colors2 = new Uint8Array(this.buffer, offset, nColor * 3);
offset += nColor * 3;
const stops = [];
for (let i7 = 0; i7 < nStop; ++i7) {
const p4 = dataView.getFloat32(offset, true);
offset += 4;
const rgb = dataView.getUint32(offset, true);
offset += 4;
stops.push([p4, `#${rgb.toString(16).padStart(6, "0")}`]);
}
let bbox = null;
if (hasBBox) {
bbox = [];
for (let i7 = 0; i7 < 4; ++i7) {
bbox.push(dataView.getFloat32(offset, true));
offset += 4;
}
}
let background = null;
if (hasBackground) {
background = new Uint8Array(this.buffer, offset, 3);
offset += 3;
}
const figures = [];
for (let i7 = 0; i7 < nFigures; ++i7) {
const type = dataView.getUint8(offset);
offset += 1;
offset = Math.ceil(offset / 4) * 4;
const coordsLength = dataView.getUint32(offset, true);
offset += 4;
const figureCoords = new Int32Array(this.buffer, offset, coordsLength);
offset += coordsLength * 4;
const colorsLength = dataView.getUint32(offset, true);
offset += 4;
const figureColors = new Int32Array(this.buffer, offset, colorsLength);
offset += colorsLength * 4;
const figure = {
type,
coords: figureCoords,
colors: figureColors
};
if (type === MeshFigureType.LATTICE) {
figure.verticesPerRow = dataView.getUint32(offset, true);
offset += 4;
}
figures.push(figure);
}
if (kind === 1) {
return ["RadialAxial", "axial", bbox, stops, Array.from(coords.slice(0, 2)), Array.from(coords.slice(2, 4)), null, null];
}
if (kind === 2) {
return ["RadialAxial", "radial", bbox, stops, [coords[0], coords[1]], [coords[3], coords[4]], coords[2], coords[5]];
}
if (kind === 3) {
const shadingType = this.data[_PatternInfo.#SHADING_TYPE];
let bounds = null;
if (coords.length > 0) {
let minX = coords[0], maxX = coords[0];
let minY = coords[1], maxY = coords[1];
for (let i7 = 0; i7 < coords.length; i7 += 2) {
const x2 = coords[i7], y4 = coords[i7 + 1];
minX = minX > x2 ? x2 : minX;
minY = minY > y4 ? y4 : minY;
maxX = maxX < x2 ? x2 : maxX;
maxY = maxY < y4 ? y4 : maxY;
}
bounds = [minX, minY, maxX, maxY];
}
return ["Mesh", shadingType, coords, colors2, figures, bounds, bbox, background];
}
throw new Error(`Unsupported pattern kind: ${kind}`);
}
};
isRefProxy = (v4) => typeof v4 === "object" && Number.isInteger(v4?.num) && v4.num >= 0 && Number.isInteger(v4?.gen) && v4.gen >= 0;
isNameProxy = (v4) => typeof v4 === "object" && typeof v4?.name === "string";
isValidExplicitDest = _isValidExplicitDest.bind(null, isRefProxy, isNameProxy);
LoopbackPort = class {
#listeners = /* @__PURE__ */ new Map();
#deferred = Promise.resolve();
postMessage(obj, transfer) {
const event = {
data: structuredClone(obj, transfer ? {
transfer
} : null)
};
this.#deferred.then(() => {
for (const [listener] of this.#listeners) {
listener.call(this, event);
}
});
}
addEventListener(name, listener, options = null) {
let rmAbort = null;
if (options?.signal instanceof AbortSignal) {
const {
signal
} = options;
if (signal.aborted) {
warn("LoopbackPort - cannot use an `aborted` signal.");
return;
}
const onAbort = () => this.removeEventListener(name, listener);
rmAbort = () => signal.removeEventListener("abort", onAbort);
signal.addEventListener("abort", onAbort);
}
this.#listeners.set(listener, rmAbort);
}
removeEventListener(name, listener) {
const rmAbort = this.#listeners.get(listener);
rmAbort?.();
this.#listeners.delete(listener);
}
terminate() {
for (const [, rmAbort] of this.#listeners) {
rmAbort?.();
}
this.#listeners.clear();
}
};
CallbackKind = {
DATA: 1,
ERROR: 2
};
StreamKind = {
CANCEL: 1,
CANCEL_COMPLETE: 2,
CLOSE: 3,
ENQUEUE: 4,
ERROR: 5,
PULL: 6,
PULL_COMPLETE: 7,
START_COMPLETE: 8
};
MessageHandler = class {
#messageAC = new AbortController();
constructor(sourceName, targetName, comObj) {
this.sourceName = sourceName;
this.targetName = targetName;
this.comObj = comObj;
this.callbackId = 1;
this.streamId = 1;
this.streamSinks = /* @__PURE__ */ Object.create(null);
this.streamControllers = /* @__PURE__ */ Object.create(null);
this.callbackCapabilities = /* @__PURE__ */ Object.create(null);
this.actionHandler = /* @__PURE__ */ Object.create(null);
comObj.addEventListener("message", this.#onMessage.bind(this), {
signal: this.#messageAC.signal
});
}
#onMessage({
data
}) {
if (data.targetName !== this.sourceName) {
return;
}
if (data.stream) {
this.#processStreamMessage(data);
return;
}
if (data.callback) {
const callbackId = data.callbackId;
const capability = this.callbackCapabilities[callbackId];
if (!capability) {
throw new Error(`Cannot resolve callback ${callbackId}`);
}
delete this.callbackCapabilities[callbackId];
if (data.callback === CallbackKind.DATA) {
capability.resolve(data.data);
} else if (data.callback === CallbackKind.ERROR) {
capability.reject(wrapReason(data.reason));
} else {
throw new Error("Unexpected callback case");
}
return;
}
const action = this.actionHandler[data.action];
if (!action) {
throw new Error(`Unknown action from worker: ${data.action}`);
}
if (data.callbackId) {
const sourceName = this.sourceName, targetName = data.sourceName, comObj = this.comObj;
Promise.try(action, data.data).then(function(result) {
comObj.postMessage({
sourceName,
targetName,
callback: CallbackKind.DATA,
callbackId: data.callbackId,
data: result
});
}, function(reason) {
comObj.postMessage({
sourceName,
targetName,
callback: CallbackKind.ERROR,
callbackId: data.callbackId,
reason: wrapReason(reason)
});
});
return;
}
if (data.streamId) {
this.#createStreamSink(data);
return;
}
action(data.data);
}
on(actionName, handler) {
const ah = this.actionHandler;
if (ah[actionName]) {
throw new Error(`There is already an actionName called "${actionName}"`);
}
ah[actionName] = handler;
}
send(actionName, data, transfers) {
this.comObj.postMessage({
sourceName: this.sourceName,
targetName: this.targetName,
action: actionName,
data
}, transfers);
}
sendWithPromise(actionName, data, transfers) {
const callbackId = this.callbackId++;
const capability = Promise.withResolvers();
this.callbackCapabilities[callbackId] = capability;
try {
this.comObj.postMessage({
sourceName: this.sourceName,
targetName: this.targetName,
action: actionName,
callbackId,
data
}, transfers);
} catch (ex) {
capability.reject(ex);
}
return capability.promise;
}
sendWithStream(actionName, data, queueingStrategy, transfers) {
const streamId = this.streamId++, sourceName = this.sourceName, targetName = this.targetName, comObj = this.comObj;
return new ReadableStream({
start: (controller) => {
const startCapability = Promise.withResolvers();
this.streamControllers[streamId] = {
controller,
startCall: startCapability,
pullCall: null,
cancelCall: null,
isClosed: false
};
comObj.postMessage({
sourceName,
targetName,
action: actionName,
streamId,
data,
desiredSize: controller.desiredSize
}, transfers);
return startCapability.promise;
},
pull: (controller) => {
const pullCapability = Promise.withResolvers();
this.streamControllers[streamId].pullCall = pullCapability;
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.PULL,
streamId,
desiredSize: controller.desiredSize
});
return pullCapability.promise;
},
cancel: (reason) => {
assert(reason instanceof Error, "cancel must have a valid reason");
const cancelCapability = Promise.withResolvers();
this.streamControllers[streamId].cancelCall = cancelCapability;
this.streamControllers[streamId].isClosed = true;
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.CANCEL,
streamId,
reason: wrapReason(reason)
});
return cancelCapability.promise;
}
}, queueingStrategy);
}
#createStreamSink(data) {
const streamId = data.streamId, sourceName = this.sourceName, targetName = data.sourceName, comObj = this.comObj;
const self2 = this, action = this.actionHandler[data.action];
const streamSink = {
enqueue(chunk, size = 1, transfers) {
if (this.isCancelled) {
return;
}
const lastDesiredSize = this.desiredSize;
this.desiredSize -= size;
if (lastDesiredSize > 0 && this.desiredSize <= 0) {
this.sinkCapability = Promise.withResolvers();
this.ready = this.sinkCapability.promise;
}
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.ENQUEUE,
streamId,
chunk
}, transfers);
},
close() {
if (this.isCancelled) {
return;
}
this.isCancelled = true;
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.CLOSE,
streamId
});
delete self2.streamSinks[streamId];
},
error(reason) {
assert(reason instanceof Error, "error must have a valid reason");
if (this.isCancelled) {
return;
}
this.isCancelled = true;
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.ERROR,
streamId,
reason: wrapReason(reason)
});
},
sinkCapability: Promise.withResolvers(),
onPull: null,
onCancel: null,
isCancelled: false,
desiredSize: data.desiredSize,
ready: null
};
streamSink.sinkCapability.resolve();
streamSink.ready = streamSink.sinkCapability.promise;
this.streamSinks[streamId] = streamSink;
Promise.try(action, data.data, streamSink).then(function() {
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.START_COMPLETE,
streamId,
success: true
});
}, function(reason) {
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.START_COMPLETE,
streamId,
reason: wrapReason(reason)
});
});
}
#processStreamMessage(data) {
const streamId = data.streamId, sourceName = this.sourceName, targetName = data.sourceName, comObj = this.comObj;
const streamController = this.streamControllers[streamId], streamSink = this.streamSinks[streamId];
switch (data.stream) {
case StreamKind.START_COMPLETE:
if (data.success) {
streamController.startCall.resolve();
} else {
streamController.startCall.reject(wrapReason(data.reason));
}
break;
case StreamKind.PULL_COMPLETE:
if (data.success) {
streamController.pullCall.resolve();
} else {
streamController.pullCall.reject(wrapReason(data.reason));
}
break;
case StreamKind.PULL:
if (!streamSink) {
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.PULL_COMPLETE,
streamId,
success: true
});
break;
}
if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
streamSink.sinkCapability.resolve();
}
streamSink.desiredSize = data.desiredSize;
Promise.try(streamSink.onPull || onFn).then(function() {
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.PULL_COMPLETE,
streamId,
success: true
});
}, function(reason) {
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.PULL_COMPLETE,
streamId,
reason: wrapReason(reason)
});
});
break;
case StreamKind.ENQUEUE:
assert(streamController, "enqueue should have stream controller");
if (streamController.isClosed) {
break;
}
streamController.controller.enqueue(data.chunk);
break;
case StreamKind.CLOSE:
assert(streamController, "close should have stream controller");
if (streamController.isClosed) {
break;
}
streamController.isClosed = true;
streamController.controller.close();
this.#deleteStreamController(streamController, streamId);
break;
case StreamKind.ERROR:
assert(streamController, "error should have stream controller");
streamController.controller.error(wrapReason(data.reason));
this.#deleteStreamController(streamController, streamId);
break;
case StreamKind.CANCEL_COMPLETE:
if (data.success) {
streamController.cancelCall.resolve();
} else {
streamController.cancelCall.reject(wrapReason(data.reason));
}
this.#deleteStreamController(streamController, streamId);
break;
case StreamKind.CANCEL:
if (!streamSink) {
break;
}
const dataReason = wrapReason(data.reason);
Promise.try(streamSink.onCancel || onFn, dataReason).then(function() {
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.CANCEL_COMPLETE,
streamId,
success: true
});
}, function(reason) {
comObj.postMessage({
sourceName,
targetName,
stream: StreamKind.CANCEL_COMPLETE,
streamId,
reason: wrapReason(reason)
});
});
streamSink.sinkCapability.reject(dataReason);
streamSink.isCancelled = true;
delete this.streamSinks[streamId];
break;
default:
throw new Error("Unexpected stream case");
}
}
async #deleteStreamController(streamController, streamId) {
await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]);
delete this.streamControllers[streamId];
}
destroy() {
this.#messageAC?.abort();
this.#messageAC = null;
}
};
BaseCanvasFactory = class {
#enableHWA = false;
constructor({
enableHWA = false
}) {
this.#enableHWA = enableHWA;
}
create(width, height) {
if (width <= 0 || height <= 0) {
throw new Error("Invalid canvas size");
}
const canvas = this._createCanvas(width, height);
return {
canvas,
context: canvas.getContext("2d", {
willReadFrequently: !this.#enableHWA
})
};
}
reset(canvasAndContext, width, height) {
if (!canvasAndContext.canvas) {
throw new Error("Canvas is not specified");
}
if (width <= 0 || height <= 0) {
throw new Error("Invalid canvas size");
}
canvasAndContext.canvas.width = width;
canvasAndContext.canvas.height = height;
}
destroy(canvasAndContext) {
if (!canvasAndContext.canvas) {
throw new Error("Canvas is not specified");
}
canvasAndContext.canvas.width = 0;
canvasAndContext.canvas.height = 0;
canvasAndContext.canvas = null;
canvasAndContext.context = null;
}
_createCanvas(width, height) {
unreachable("Abstract method `_createCanvas` called.");
}
};
DOMCanvasFactory = class extends BaseCanvasFactory {
constructor({
ownerDocument = globalThis.document,
enableHWA = false
}) {
super({
enableHWA
});
this._document = ownerDocument;
}
_createCanvas(width, height) {
const canvas = this._document.createElement("canvas");
canvas.width = width;
canvas.height = height;
return canvas;
}
};
BaseCMapReaderFactory = class {
constructor({
baseUrl = null,
isCompressed = true
}) {
this.baseUrl = baseUrl;
this.isCompressed = isCompressed;
}
async fetch({
name
}) {
if (!this.baseUrl) {
throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");
}
if (!name) {
throw new Error("CMap name must be specified.");
}
const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
return this._fetch(url).then((cMapData) => ({
cMapData,
isCompressed: this.isCompressed
})).catch((reason) => {
throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
});
}
async _fetch(url) {
unreachable("Abstract method `_fetch` called.");
}
};
DOMCMapReaderFactory = class extends BaseCMapReaderFactory {
async _fetch(url) {
const data = await fetchData(url, this.isCompressed ? "arraybuffer" : "text");
return data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data);
}
};
BaseFilterFactory = class {
addFilter(maps) {
return "none";
}
addHCMFilter(fgColor, bgColor) {
return "none";
}
addAlphaFilter(map3) {
return "none";
}
addLuminosityFilter(map3) {
return "none";
}
addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
return "none";
}
destroy(keepHCM = false) {
}
};
DOMFilterFactory = class extends BaseFilterFactory {
#baseUrl;
#_cache;
#_defs;
#docId;
#document;
#_hcmCache;
#id = 0;
constructor({
docId,
ownerDocument = globalThis.document
}) {
super();
this.#docId = docId;
this.#document = ownerDocument;
}
get #cache() {
return this.#_cache ||= /* @__PURE__ */ new Map();
}
get #hcmCache() {
return this.#_hcmCache ||= /* @__PURE__ */ new Map();
}
get #defs() {
if (!this.#_defs) {
const div = this.#document.createElement("div");
const {
style
} = div;
style.visibility = "hidden";
style.contain = "strict";
style.width = style.height = 0;
style.position = "absolute";
style.top = style.left = 0;
style.zIndex = -1;
const svg = this.#document.createElementNS(SVG_NS, "svg");
svg.setAttribute("width", 0);
svg.setAttribute("height", 0);
this.#_defs = this.#document.createElementNS(SVG_NS, "defs");
div.append(svg);
svg.append(this.#_defs);
this.#document.body.append(div);
}
return this.#_defs;
}
#createTables(maps) {
if (maps.length === 1) {
const mapR2 = maps[0];
const buffer = new Array(256);
for (let i7 = 0; i7 < 256; i7++) {
buffer[i7] = mapR2[i7] / 255;
}
const table = buffer.join(",");
return [table, table, table];
}
const [mapR, mapG, mapB] = maps;
const bufferR = new Array(256);
const bufferG = new Array(256);
const bufferB = new Array(256);
for (let i7 = 0; i7 < 256; i7++) {
bufferR[i7] = mapR[i7] / 255;
bufferG[i7] = mapG[i7] / 255;
bufferB[i7] = mapB[i7] / 255;
}
return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
}
#createUrl(id) {
if (this.#baseUrl === void 0) {
this.#baseUrl = "";
const url = this.#document.URL;
if (url !== this.#document.baseURI) {
if (isDataScheme(url)) {
warn('#createUrl: ignore "data:"-URL for performance reasons.');
} else {
this.#baseUrl = updateUrlHash(url, "");
}
}
}
return `url(${this.#baseUrl}#${id})`;
}
addFilter(maps) {
if (!maps) {
return "none";
}
let value = this.#cache.get(maps);
if (value) {
return value;
}
const [tableR, tableG, tableB] = this.#createTables(maps);
const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
value = this.#cache.get(key);
if (value) {
this.#cache.set(maps, value);
return value;
}
const id = `g_${this.#docId}_transfer_map_${this.#id++}`;
const url = this.#createUrl(id);
this.#cache.set(maps, url);
this.#cache.set(key, url);
const filter2 = this.#createFilter(id);
this.#addTransferMapConversion(tableR, tableG, tableB, filter2);
return url;
}
addHCMFilter(fgColor, bgColor) {
const key = `${fgColor}-${bgColor}`;
const filterName = "base";
let info2 = this.#hcmCache.get(filterName);
if (info2?.key === key) {
return info2.url;
}
if (info2) {
info2.filter?.remove();
info2.key = key;
info2.url = "none";
info2.filter = null;
} else {
info2 = {
key,
url: "none",
filter: null
};
this.#hcmCache.set(filterName, info2);
}
if (!fgColor || !bgColor) {
return info2.url;
}
const fgRGB = this.#getRGB(fgColor);
fgColor = Util.makeHexColor(...fgRGB);
const bgRGB = this.#getRGB(bgColor);
bgColor = Util.makeHexColor(...bgRGB);
this.#defs.style.color = "";
if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
return info2.url;
}
const map3 = new Array(256);
for (let i7 = 0; i7 <= 255; i7++) {
const x2 = i7 / 255;
map3[i7] = x2 <= 0.03928 ? x2 / 12.92 : ((x2 + 0.055) / 1.055) ** 2.4;
}
const table = map3.join(",");
const id = `g_${this.#docId}_hcm_filter`;
const filter2 = info2.filter = this.#createFilter(id);
this.#addTransferMapConversion(table, table, table, filter2);
this.#addGrayConversion(filter2);
const getSteps = (c6, n7) => {
const start = fgRGB[c6] / 255;
const end = bgRGB[c6] / 255;
const arr = new Array(n7 + 1);
for (let i7 = 0; i7 <= n7; i7++) {
arr[i7] = start + i7 / n7 * (end - start);
}
return arr.join(",");
};
this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter2);
info2.url = this.#createUrl(id);
return info2.url;
}
addAlphaFilter(map3) {
let value = this.#cache.get(map3);
if (value) {
return value;
}
const [tableA] = this.#createTables([map3]);
const key = `alpha_${tableA}`;
value = this.#cache.get(key);
if (value) {
this.#cache.set(map3, value);
return value;
}
const id = `g_${this.#docId}_alpha_map_${this.#id++}`;
const url = this.#createUrl(id);
this.#cache.set(map3, url);
this.#cache.set(key, url);
const filter2 = this.#createFilter(id);
this.#addTransferMapAlphaConversion(tableA, filter2);
return url;
}
addLuminosityFilter(map3) {
let value = this.#cache.get(map3 || "luminosity");
if (value) {
return value;
}
let tableA, key;
if (map3) {
[tableA] = this.#createTables([map3]);
key = `luminosity_${tableA}`;
} else {
key = "luminosity";
}
value = this.#cache.get(key);
if (value) {
this.#cache.set(map3, value);
return value;
}
const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;
const url = this.#createUrl(id);
this.#cache.set(map3, url);
this.#cache.set(key, url);
const filter2 = this.#createFilter(id);
this.#addLuminosityConversion(filter2);
if (map3) {
this.#addTransferMapAlphaConversion(tableA, filter2);
}
return url;
}
addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
let info2 = this.#hcmCache.get(filterName);
if (info2?.key === key) {
return info2.url;
}
if (info2) {
info2.filter?.remove();
info2.key = key;
info2.url = "none";
info2.filter = null;
} else {
info2 = {
key,
url: "none",
filter: null
};
this.#hcmCache.set(filterName, info2);
}
if (!fgColor || !bgColor) {
return info2.url;
}
const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));
let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]);
let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]);
let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this));
if (bgGray < fgGray) {
[fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB];
}
this.#defs.style.color = "";
const getSteps = (fg, bg, n7) => {
const arr = new Array(256);
const step = (bgGray - fgGray) / n7;
const newStart = fg / 255;
const newStep = (bg - fg) / (255 * n7);
let prev = 0;
for (let i7 = 0; i7 <= n7; i7++) {
const k2 = Math.round(fgGray + i7 * step);
const value = newStart + i7 * newStep;
for (let j3 = prev; j3 <= k2; j3++) {
arr[j3] = value;
}
prev = k2 + 1;
}
for (let i7 = prev; i7 < 256; i7++) {
arr[i7] = arr[prev - 1];
}
return arr.join(",");
};
const id = `g_${this.#docId}_hcm_${filterName}_filter`;
const filter2 = info2.filter = this.#createFilter(id);
this.#addGrayConversion(filter2);
this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter2);
info2.url = this.#createUrl(id);
return info2.url;
}
destroy(keepHCM = false) {
if (keepHCM && this.#_hcmCache?.size) {
return;
}
this.#_defs?.parentNode.parentNode.remove();
this.#_defs = null;
this.#_cache?.clear();
this.#_cache = null;
this.#_hcmCache?.clear();
this.#_hcmCache = null;
this.#id = 0;
}
#addLuminosityConversion(filter2) {
const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
feColorMatrix.setAttribute("type", "matrix");
feColorMatrix.setAttribute("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");
filter2.append(feColorMatrix);
}
#addGrayConversion(filter2) {
const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix");
feColorMatrix.setAttribute("type", "matrix");
feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");
filter2.append(feColorMatrix);
}
#createFilter(id) {
const filter2 = this.#document.createElementNS(SVG_NS, "filter");
filter2.setAttribute("color-interpolation-filters", "sRGB");
filter2.setAttribute("id", id);
this.#defs.append(filter2);
return filter2;
}
#appendFeFunc(feComponentTransfer, func, table) {
const feFunc = this.#document.createElementNS(SVG_NS, func);
feFunc.setAttribute("type", "discrete");
feFunc.setAttribute("tableValues", table);
feComponentTransfer.append(feFunc);
}
#addTransferMapConversion(rTable, gTable, bTable, filter2) {
const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
filter2.append(feComponentTransfer);
this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable);
this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable);
this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable);
}
#addTransferMapAlphaConversion(aTable, filter2) {
const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer");
filter2.append(feComponentTransfer);
this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable);
}
#getRGB(color2) {
this.#defs.style.color = color2;
return getRGB(getComputedStyle(this.#defs).getPropertyValue("color"));
}
};
BaseStandardFontDataFactory = class {
constructor({
baseUrl = null
}) {
this.baseUrl = baseUrl;
}
async fetch({
filename
}) {
if (!this.baseUrl) {
throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");
}
if (!filename) {
throw new Error("Font filename must be specified.");
}
const url = `${this.baseUrl}${filename}`;
return this._fetch(url).catch((reason) => {
throw new Error(`Unable to load font data at: ${url}`);
});
}
async _fetch(url) {
unreachable("Abstract method `_fetch` called.");
}
};
DOMStandardFontDataFactory = class extends BaseStandardFontDataFactory {
async _fetch(url) {
const data = await fetchData(url, "arraybuffer");
return new Uint8Array(data);
}
};
BaseWasmFactory = class {
constructor({
baseUrl = null
}) {
this.baseUrl = baseUrl;
}
async fetch({
filename
}) {
if (!this.baseUrl) {
throw new Error("Ensure that the `wasmUrl` API parameter is provided.");
}
if (!filename) {
throw new Error("Wasm filename must be specified.");
}
const url = `${this.baseUrl}${filename}`;
return this._fetch(url).catch((reason) => {
throw new Error(`Unable to load wasm data at: ${url}`);
});
}
async _fetch(url) {
unreachable("Abstract method `_fetch` called.");
}
};
DOMWasmFactory = class extends BaseWasmFactory {
async _fetch(url) {
const data = await fetchData(url, "arraybuffer");
return new Uint8Array(data);
}
};
if (isNodeJS) {
warn("Please use the `legacy` build in Node.js environments.");
}
NodeFilterFactory = class extends BaseFilterFactory {
};
NodeCanvasFactory = class extends BaseCanvasFactory {
_createCanvas(width, height) {
const require2 = process.getBuiltinModule("module").createRequire(import.meta.url);
const canvas = require2("@napi-rs/canvas");
return canvas.createCanvas(width, height);
}
};
NodeCMapReaderFactory = class extends BaseCMapReaderFactory {
async _fetch(url) {
return node_utils_fetchData(url);
}
};
NodeStandardFontDataFactory = class extends BaseStandardFontDataFactory {
async _fetch(url) {
return node_utils_fetchData(url);
}
};
NodeWasmFactory = class extends BaseWasmFactory {
async _fetch(url) {
return node_utils_fetchData(url);
}
};
FORCED_DEPENDENCY_LABEL = "__forcedDependency";
({
floor,
ceil
} = Math);
EMPTY_BBOX = new Uint32Array(new Uint8Array([255, 255, 0, 0]).buffer)[0];
BBoxReader = class {
#bboxes;
#coords;
constructor(bboxes, coords) {
this.#bboxes = bboxes;
this.#coords = coords;
}
get length() {
return this.#bboxes.length;
}
isEmpty(i7) {
return this.#bboxes[i7] === EMPTY_BBOX;
}
minX(i7) {
return this.#coords[i7 * 4 + 0] / 256;
}
minY(i7) {
return this.#coords[i7 * 4 + 1] / 256;
}
maxX(i7) {
return (this.#coords[i7 * 4 + 2] + 1) / 256;
}
maxY(i7) {
return (this.#coords[i7 * 4 + 3] + 1) / 256;
}
};
ensureDebugMetadata = (map3, key) => {
if (!map3) {
return void 0;
}
let value = map3.get(key);
if (!value) {
value = {
dependencies: /* @__PURE__ */ new Set(),
isRenderingOperation: false
};
map3.set(key, value);
}
return value;
};
CanvasDependencyTracker = class {
#simple = {
__proto__: null
};
#incremental = {
__proto__: null,
transform: [],
moveText: [],
sameLineText: [],
[FORCED_DEPENDENCY_LABEL]: []
};
#namedDependencies = /* @__PURE__ */ new Map();
#savesStack = [];
#markedContentStack = [];
#baseTransformStack = [[1, 0, 0, 1, 0, 0]];
#clipBox = [-Infinity, -Infinity, Infinity, Infinity];
#pendingBBox = new Float64Array([Infinity, Infinity, -Infinity, -Infinity]);
#pendingBBoxIdx = -1;
#pendingDependencies = /* @__PURE__ */ new Set();
#operations = /* @__PURE__ */ new Map();
#fontBBoxTrustworthy = /* @__PURE__ */ new Map();
#canvasWidth;
#canvasHeight;
#bboxesCoords;
#bboxes;
#debugMetadata;
constructor(canvas, operationsCount, recordDebugMetadata = false) {
this.#canvasWidth = canvas.width;
this.#canvasHeight = canvas.height;
this.#initializeBBoxes(operationsCount);
if (recordDebugMetadata) {
this.#debugMetadata = /* @__PURE__ */ new Map();
}
}
growOperationsCount(operationsCount) {
if (operationsCount >= this.#bboxes.length) {
this.#initializeBBoxes(operationsCount, this.#bboxes);
}
}
#initializeBBoxes(operationsCount, oldBBoxes) {
const buffer = new ArrayBuffer(operationsCount * 4);
this.#bboxesCoords = new Uint8ClampedArray(buffer);
this.#bboxes = new Uint32Array(buffer);
if (oldBBoxes && oldBBoxes.length > 0) {
this.#bboxes.set(oldBBoxes);
this.#bboxes.fill(EMPTY_BBOX, oldBBoxes.length);
} else {
this.#bboxes.fill(EMPTY_BBOX);
}
}
save(opIdx) {
this.#simple = {
__proto__: this.#simple
};
this.#incremental = {
__proto__: this.#incremental,
transform: {
__proto__: this.#incremental.transform
},
moveText: {
__proto__: this.#incremental.moveText
},
sameLineText: {
__proto__: this.#incremental.sameLineText
},
[FORCED_DEPENDENCY_LABEL]: {
__proto__: this.#incremental[FORCED_DEPENDENCY_LABEL]
}
};
this.#clipBox = {
__proto__: this.#clipBox
};
this.#savesStack.push(opIdx);
return this;
}
restore(opIdx) {
const previous = Object.getPrototypeOf(this.#simple);
if (previous === null) {
return this;
}
this.#simple = previous;
this.#incremental = Object.getPrototypeOf(this.#incremental);
this.#clipBox = Object.getPrototypeOf(this.#clipBox);
const lastSave = this.#savesStack.pop();
if (lastSave !== void 0) {
ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave);
this.#bboxes[opIdx] = this.#bboxes[lastSave];
}
return this;
}
recordOpenMarker(idx) {
this.#savesStack.push(idx);
return this;
}
getOpenMarker() {
if (this.#savesStack.length === 0) {
return null;
}
return this.#savesStack.at(-1);
}
recordCloseMarker(opIdx) {
const lastSave = this.#savesStack.pop();
if (lastSave !== void 0) {
ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave);
this.#bboxes[opIdx] = this.#bboxes[lastSave];
}
return this;
}
beginMarkedContent(opIdx) {
this.#markedContentStack.push(opIdx);
return this;
}
endMarkedContent(opIdx) {
const lastSave = this.#markedContentStack.pop();
if (lastSave !== void 0) {
ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave);
this.#bboxes[opIdx] = this.#bboxes[lastSave];
}
return this;
}
pushBaseTransform(ctx) {
this.#baseTransformStack.push(Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform()));
return this;
}
popBaseTransform() {
if (this.#baseTransformStack.length > 1) {
this.#baseTransformStack.pop();
}
return this;
}
recordSimpleData(name, idx) {
this.#simple[name] = idx;
return this;
}
recordIncrementalData(name, idx) {
this.#incremental[name].push(idx);
return this;
}
resetIncrementalData(name, idx) {
this.#incremental[name].length = 0;
return this;
}
recordNamedData(name, idx) {
this.#namedDependencies.set(name, idx);
return this;
}
recordSimpleDataFromNamed(name, depName, fallbackIdx) {
this.#simple[name] = this.#namedDependencies.get(depName) ?? fallbackIdx;
}
recordFutureForcedDependency(name, idx) {
this.recordIncrementalData(FORCED_DEPENDENCY_LABEL, idx);
return this;
}
inheritSimpleDataAsFutureForcedDependencies(names2) {
for (const name of names2) {
if (name in this.#simple) {
this.recordFutureForcedDependency(name, this.#simple[name]);
}
}
return this;
}
inheritPendingDependenciesAsFutureForcedDependencies() {
for (const dep of this.#pendingDependencies) {
this.recordFutureForcedDependency(FORCED_DEPENDENCY_LABEL, dep);
}
return this;
}
resetBBox(idx) {
if (this.#pendingBBoxIdx !== idx) {
this.#pendingBBoxIdx = idx;
this.#pendingBBox[0] = Infinity;
this.#pendingBBox[1] = Infinity;
this.#pendingBBox[2] = -Infinity;
this.#pendingBBox[3] = -Infinity;
}
return this;
}
recordClipBox(idx, ctx, minX, maxX, minY, maxY) {
const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform());
const clipBox = [Infinity, Infinity, -Infinity, -Infinity];
Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, clipBox);
const intersection = Util.intersect(this.#clipBox, clipBox);
if (intersection) {
this.#clipBox[0] = intersection[0];
this.#clipBox[1] = intersection[1];
this.#clipBox[2] = intersection[2];
this.#clipBox[3] = intersection[3];
} else {
this.#clipBox[0] = this.#clipBox[1] = Infinity;
this.#clipBox[2] = this.#clipBox[3] = -Infinity;
}
return this;
}
recordBBox(idx, ctx, minX, maxX, minY, maxY) {
const clipBox = this.#clipBox;
if (clipBox[0] === Infinity) {
return this;
}
const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform());
if (clipBox[0] === -Infinity) {
Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, this.#pendingBBox);
return this;
}
const bbox = [Infinity, Infinity, -Infinity, -Infinity];
Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, bbox);
this.#pendingBBox[0] = Math.min(this.#pendingBBox[0], Math.max(bbox[0], clipBox[0]));
this.#pendingBBox[1] = Math.min(this.#pendingBBox[1], Math.max(bbox[1], clipBox[1]));
this.#pendingBBox[2] = Math.max(this.#pendingBBox[2], Math.min(bbox[2], clipBox[2]));
this.#pendingBBox[3] = Math.max(this.#pendingBBox[3], Math.min(bbox[3], clipBox[3]));
return this;
}
recordCharacterBBox(idx, ctx, font, scale = 1, x2 = 0, y4 = 0, getMeasure) {
const fontBBox = font.bbox;
let isBBoxTrustworthy;
let computedBBox;
if (fontBBox) {
isBBoxTrustworthy = fontBBox[2] !== fontBBox[0] && fontBBox[3] !== fontBBox[1] && this.#fontBBoxTrustworthy.get(font);
if (isBBoxTrustworthy !== false) {
computedBBox = [0, 0, 0, 0];
Util.axialAlignedBoundingBox(fontBBox, font.fontMatrix, computedBBox);
if (scale !== 1 || x2 !== 0 || y4 !== 0) {
Util.scaleMinMax([scale, 0, 0, -scale, x2, y4], computedBBox);
}
if (isBBoxTrustworthy) {
return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]);
}
}
}
if (!getMeasure) {
return this.recordFullPageBBox(idx);
}
const measure = getMeasure();
if (fontBBox && computedBBox && isBBoxTrustworthy === void 0) {
isBBoxTrustworthy = computedBBox[0] <= x2 - measure.actualBoundingBoxLeft && computedBBox[2] >= x2 + measure.actualBoundingBoxRight && computedBBox[1] <= y4 - measure.actualBoundingBoxAscent && computedBBox[3] >= y4 + measure.actualBoundingBoxDescent;
this.#fontBBoxTrustworthy.set(font, isBBoxTrustworthy);
if (isBBoxTrustworthy) {
return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]);
}
}
return this.recordBBox(idx, ctx, x2 - measure.actualBoundingBoxLeft, x2 + measure.actualBoundingBoxRight, y4 - measure.actualBoundingBoxAscent, y4 + measure.actualBoundingBoxDescent);
}
recordFullPageBBox(idx) {
this.#pendingBBox[0] = Math.max(0, this.#clipBox[0]);
this.#pendingBBox[1] = Math.max(0, this.#clipBox[1]);
this.#pendingBBox[2] = Math.min(this.#canvasWidth, this.#clipBox[2]);
this.#pendingBBox[3] = Math.min(this.#canvasHeight, this.#clipBox[3]);
return this;
}
getSimpleIndex(dependencyName) {
return this.#simple[dependencyName];
}
recordDependencies(idx, dependencyNames) {
const pendingDependencies = this.#pendingDependencies;
const simple = this.#simple;
const incremental = this.#incremental;
for (const name of dependencyNames) {
if (name in this.#simple) {
pendingDependencies.add(simple[name]);
} else if (name in incremental) {
incremental[name].forEach(pendingDependencies.add, pendingDependencies);
}
}
return this;
}
recordNamedDependency(idx, name) {
if (this.#namedDependencies.has(name)) {
this.#pendingDependencies.add(this.#namedDependencies.get(name));
}
return this;
}
recordOperation(idx, preserve = false) {
this.recordDependencies(idx, [FORCED_DEPENDENCY_LABEL]);
if (this.#debugMetadata) {
const metadata = ensureDebugMetadata(this.#debugMetadata, idx);
const {
dependencies
} = metadata;
this.#pendingDependencies.forEach(dependencies.add, dependencies);
this.#savesStack.forEach(dependencies.add, dependencies);
this.#markedContentStack.forEach(dependencies.add, dependencies);
dependencies.delete(idx);
metadata.isRenderingOperation = true;
}
if (this.#pendingBBoxIdx === idx) {
const minX = floor(this.#pendingBBox[0] * 256 / this.#canvasWidth);
const minY = floor(this.#pendingBBox[1] * 256 / this.#canvasHeight);
const maxX = ceil(this.#pendingBBox[2] * 256 / this.#canvasWidth);
const maxY = ceil(this.#pendingBBox[3] * 256 / this.#canvasHeight);
expandBBox(this.#bboxesCoords, idx, minX, minY, maxX, maxY);
for (const depIdx of this.#pendingDependencies) {
if (depIdx !== idx) {
expandBBox(this.#bboxesCoords, depIdx, minX, minY, maxX, maxY);
}
}
for (const saveIdx of this.#savesStack) {
if (saveIdx !== idx) {
expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY);
}
}
for (const saveIdx of this.#markedContentStack) {
if (saveIdx !== idx) {
expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY);
}
}
if (!preserve) {
this.#pendingDependencies.clear();
this.#pendingBBoxIdx = -1;
}
}
return this;
}
recordShowTextOperation(idx, preserve = false) {
const deps = Array.from(this.#pendingDependencies);
this.recordOperation(idx, preserve);
this.recordIncrementalData("sameLineText", idx);
for (const dep of deps) {
this.recordIncrementalData("sameLineText", dep);
}
return this;
}
bboxToClipBoxDropOperation(idx, preserve = false) {
if (this.#pendingBBoxIdx === idx) {
this.#pendingBBoxIdx = -1;
this.#clipBox[0] = Math.max(this.#clipBox[0], this.#pendingBBox[0]);
this.#clipBox[1] = Math.max(this.#clipBox[1], this.#pendingBBox[1]);
this.#clipBox[2] = Math.min(this.#clipBox[2], this.#pendingBBox[2]);
this.#clipBox[3] = Math.min(this.#clipBox[3], this.#pendingBBox[3]);
if (!preserve) {
this.#pendingDependencies.clear();
}
}
return this;
}
_takePendingDependencies() {
const pendingDependencies = this.#pendingDependencies;
this.#pendingDependencies = /* @__PURE__ */ new Set();
return pendingDependencies;
}
_extractOperation(idx) {
const operation = this.#operations.get(idx);
this.#operations.delete(idx);
return operation;
}
_pushPendingDependencies(dependencies) {
for (const dep of dependencies) {
this.#pendingDependencies.add(dep);
}
}
take() {
this.#fontBBoxTrustworthy.clear();
return new BBoxReader(this.#bboxes, this.#bboxesCoords);
}
takeDebugMetadata() {
return this.#debugMetadata;
}
};
CanvasNestedDependencyTracker = class _CanvasNestedDependencyTracker {
#dependencyTracker;
#opIdx;
#ignoreBBoxes;
#nestingLevel = 0;
#savesLevel = 0;
constructor(dependencyTracker, opIdx, ignoreBBoxes) {
if (dependencyTracker instanceof _CanvasNestedDependencyTracker && dependencyTracker.#ignoreBBoxes === !!ignoreBBoxes) {
return dependencyTracker;
}
this.#dependencyTracker = dependencyTracker;
this.#opIdx = opIdx;
this.#ignoreBBoxes = !!ignoreBBoxes;
}
growOperationsCount() {
throw new Error("Unreachable");
}
save(opIdx) {
this.#savesLevel++;
this.#dependencyTracker.save(this.#opIdx);
return this;
}
restore(opIdx) {
if (this.#savesLevel > 0) {
this.#dependencyTracker.restore(this.#opIdx);
this.#savesLevel--;
}
return this;
}
recordOpenMarker(idx) {
this.#nestingLevel++;
return this;
}
getOpenMarker() {
return this.#nestingLevel > 0 ? this.#opIdx : this.#dependencyTracker.getOpenMarker();
}
recordCloseMarker(idx) {
this.#nestingLevel--;
return this;
}
beginMarkedContent(opIdx) {
return this;
}
endMarkedContent(opIdx) {
return this;
}
pushBaseTransform(ctx) {
this.#dependencyTracker.pushBaseTransform(ctx);
return this;
}
popBaseTransform() {
this.#dependencyTracker.popBaseTransform();
return this;
}
recordSimpleData(name, idx) {
this.#dependencyTracker.recordSimpleData(name, this.#opIdx);
return this;
}
recordIncrementalData(name, idx) {
this.#dependencyTracker.recordIncrementalData(name, this.#opIdx);
return this;
}
resetIncrementalData(name, idx) {
this.#dependencyTracker.resetIncrementalData(name, this.#opIdx);
return this;
}
recordNamedData(name, idx) {
return this;
}
recordSimpleDataFromNamed(name, depName, fallbackIdx) {
this.#dependencyTracker.recordSimpleDataFromNamed(name, depName, this.#opIdx);
return this;
}
recordFutureForcedDependency(name, idx) {
this.#dependencyTracker.recordFutureForcedDependency(name, this.#opIdx);
return this;
}
inheritSimpleDataAsFutureForcedDependencies(names2) {
this.#dependencyTracker.inheritSimpleDataAsFutureForcedDependencies(names2);
return this;
}
inheritPendingDependenciesAsFutureForcedDependencies() {
this.#dependencyTracker.inheritPendingDependenciesAsFutureForcedDependencies();
return this;
}
resetBBox(idx) {
if (!this.#ignoreBBoxes) {
this.#dependencyTracker.resetBBox(this.#opIdx);
}
return this;
}
recordClipBox(idx, ctx, minX, maxX, minY, maxY) {
if (!this.#ignoreBBoxes) {
this.#dependencyTracker.recordClipBox(this.#opIdx, ctx, minX, maxX, minY, maxY);
}
return this;
}
recordBBox(idx, ctx, minX, maxX, minY, maxY) {
if (!this.#ignoreBBoxes) {
this.#dependencyTracker.recordBBox(this.#opIdx, ctx, minX, maxX, minY, maxY);
}
return this;
}
recordCharacterBBox(idx, ctx, font, scale, x2, y4, getMeasure) {
if (!this.#ignoreBBoxes) {
this.#dependencyTracker.recordCharacterBBox(this.#opIdx, ctx, font, scale, x2, y4, getMeasure);
}
return this;
}
recordFullPageBBox(idx) {
if (!this.#ignoreBBoxes) {
this.#dependencyTracker.recordFullPageBBox(this.#opIdx);
}
return this;
}
getSimpleIndex(dependencyName) {
return this.#dependencyTracker.getSimpleIndex(dependencyName);
}
recordDependencies(idx, dependencyNames) {
this.#dependencyTracker.recordDependencies(this.#opIdx, dependencyNames);
return this;
}
recordNamedDependency(idx, name) {
this.#dependencyTracker.recordNamedDependency(this.#opIdx, name);
return this;
}
recordOperation(idx) {
this.#dependencyTracker.recordOperation(this.#opIdx, true);
return this;
}
recordShowTextOperation(idx) {
this.#dependencyTracker.recordShowTextOperation(this.#opIdx, true);
return this;
}
bboxToClipBoxDropOperation(idx) {
if (!this.#ignoreBBoxes) {
this.#dependencyTracker.bboxToClipBoxDropOperation(this.#opIdx, true);
}
return this;
}
take() {
throw new Error("Unreachable");
}
takeDebugMetadata() {
throw new Error("Unreachable");
}
};
Dependencies = {
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"]
};
PathType = {
FILL: "Fill",
STROKE: "Stroke",
SHADING: "Shading"
};
BaseShadingPattern = class {
isModifyingCurrentTransform() {
return false;
}
getPattern() {
unreachable("Abstract method `getPattern` called.");
}
};
RadialAxialShadingPattern = class extends BaseShadingPattern {
constructor(IR) {
super();
this._type = IR[1];
this._bbox = IR[2];
this._colorStops = IR[3];
this._p0 = IR[4];
this._p1 = IR[5];
this._r0 = IR[6];
this._r1 = IR[7];
this.matrix = null;
}
_createGradient(ctx) {
let grad;
if (this._type === "axial") {
grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
} else if (this._type === "radial") {
grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
}
for (const colorStop of this._colorStops) {
grad.addColorStop(colorStop[0], colorStop[1]);
}
return grad;
}
getPattern(ctx, owner, inverse, pathType) {
let pattern;
if (pathType === PathType.STROKE || pathType === PathType.FILL) {
const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0];
const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height);
const tmpCtx = tmpCanvas.context;
tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
tmpCtx.beginPath();
tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
tmpCtx.transform(...owner.baseTransform);
if (this.matrix) {
tmpCtx.transform(...this.matrix);
}
applyBoundingBox(tmpCtx, this._bbox);
tmpCtx.fillStyle = this._createGradient(tmpCtx);
tmpCtx.fill();
pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
const domMatrix = new DOMMatrix(inverse);
pattern.setTransform(domMatrix);
} else {
applyBoundingBox(ctx, this._bbox);
pattern = this._createGradient(ctx);
}
return pattern;
}
};
MeshShadingPattern = class extends BaseShadingPattern {
constructor(IR) {
super();
this._coords = IR[2];
this._colors = IR[3];
this._figures = IR[4];
this._bounds = IR[5];
this._bbox = IR[6];
this._background = IR[7];
this.matrix = null;
}
_createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
const EXPECTED_SCALE = 1.1;
const MAX_PATTERN_SIZE = 3e3;
const BORDER_SIZE = 2;
const offsetX = Math.floor(this._bounds[0]);
const offsetY = Math.floor(this._bounds[1]);
const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
const scaleX = boundsWidth / width;
const scaleY = boundsHeight / height;
const context = {
coords: this._coords,
colors: this._colors,
offsetX: -offsetX,
offsetY: -offsetY,
scaleX: 1 / scaleX,
scaleY: 1 / scaleY
};
const paddedWidth = width + BORDER_SIZE * 2;
const paddedHeight = height + BORDER_SIZE * 2;
const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight);
const tmpCtx = tmpCanvas.context;
const data = tmpCtx.createImageData(width, height);
if (backgroundColor) {
const bytes = data.data;
for (let i7 = 0, ii = bytes.length; i7 < ii; i7 += 4) {
bytes[i7] = backgroundColor[0];
bytes[i7 + 1] = backgroundColor[1];
bytes[i7 + 2] = backgroundColor[2];
bytes[i7 + 3] = 255;
}
}
for (const figure of this._figures) {
drawFigure(data, figure, context);
}
tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
const canvas = tmpCanvas.canvas;
return {
canvas,
offsetX: offsetX - BORDER_SIZE * scaleX,
offsetY: offsetY - BORDER_SIZE * scaleY,
scaleX,
scaleY
};
}
isModifyingCurrentTransform() {
return true;
}
getPattern(ctx, owner, inverse, pathType) {
applyBoundingBox(ctx, this._bbox);
const scale = new Float32Array(2);
if (pathType === PathType.SHADING) {
Util.singularValueDecompose2dScale(getCurrentTransform(ctx), scale);
} else if (this.matrix) {
Util.singularValueDecompose2dScale(this.matrix, scale);
const [matrixScaleX, matrixScaleY] = scale;
Util.singularValueDecompose2dScale(owner.baseTransform, scale);
scale[0] *= matrixScaleX;
scale[1] *= matrixScaleY;
} else {
Util.singularValueDecompose2dScale(owner.baseTransform, scale);
}
const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
if (pathType !== PathType.SHADING) {
ctx.setTransform(...owner.baseTransform);
if (this.matrix) {
ctx.transform(...this.matrix);
}
}
ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
}
};
DummyShadingPattern = class extends BaseShadingPattern {
getPattern() {
return "hotpink";
}
};
PaintType = {
COLORED: 1,
UNCOLORED: 2
};
TilingPattern = class _TilingPattern {
static MAX_PATTERN_SIZE = 3e3;
constructor(IR, ctx, canvasGraphicsFactory, baseTransform) {
this.color = IR[1];
this.operatorList = IR[2];
this.matrix = IR[3];
this.bbox = IR[4];
this.xstep = IR[5];
this.ystep = IR[6];
this.paintType = IR[7];
this.tilingType = IR[8];
this.ctx = ctx;
this.canvasGraphicsFactory = canvasGraphicsFactory;
this.baseTransform = baseTransform;
}
createPatternCanvas(owner, opIdx) {
const {
bbox,
operatorList,
paintType,
tilingType,
color: color2,
canvasGraphicsFactory
} = this;
let {
xstep,
ystep
} = this;
xstep = Math.abs(xstep);
ystep = Math.abs(ystep);
info("TilingType: " + tilingType);
const x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
const width = x1 - x0;
const height = y1 - y0;
const scale = new Float32Array(2);
Util.singularValueDecompose2dScale(this.matrix, scale);
const [matrixScaleX, matrixScaleY] = scale;
Util.singularValueDecompose2dScale(this.baseTransform, scale);
const combinedScaleX = matrixScaleX * scale[0];
const combinedScaleY = matrixScaleY * scale[1];
let canvasWidth = width, canvasHeight = height, redrawHorizontally = false, redrawVertically = false;
const xScaledStep = Math.ceil(xstep * combinedScaleX);
const yScaledStep = Math.ceil(ystep * combinedScaleY);
const xScaledWidth = Math.ceil(width * combinedScaleX);
const yScaledHeight = Math.ceil(height * combinedScaleY);
if (xScaledStep >= xScaledWidth) {
canvasWidth = xstep;
} else {
redrawHorizontally = true;
}
if (yScaledStep >= yScaledHeight) {
canvasHeight = ystep;
} else {
redrawVertically = true;
}
const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size);
const tmpCtx = tmpCanvas.context;
const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx, opIdx);
graphics.groupLevel = owner.groupLevel;
this.setFillAndStrokeStyleToContext(graphics, paintType, color2);
tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0);
graphics.transform(0, dimx.scale, 0, 0, dimy.scale, 0, 0);
tmpCtx.save();
graphics.dependencyTracker?.save();
this.clipBbox(graphics, x0, y0, x1, y1);
graphics.baseTransform = getCurrentTransform(graphics.ctx);
graphics.executeOperatorList(operatorList);
graphics.endDrawing();
graphics.dependencyTracker?.restore();
tmpCtx.restore();
if (redrawHorizontally || redrawVertically) {
const image = tmpCanvas.canvas;
if (redrawHorizontally) {
canvasWidth = xstep;
}
if (redrawVertically) {
canvasHeight = ystep;
}
const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX);
const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY);
const xSize = dimx2.size;
const ySize = dimy2.size;
const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize);
const tmpCtx2 = tmpCanvas2.context;
const ii = redrawHorizontally ? Math.floor(width / xstep) : 0;
const jj = redrawVertically ? Math.floor(height / ystep) : 0;
for (let i7 = 0; i7 <= ii; i7++) {
for (let j3 = 0; j3 <= jj; j3++) {
tmpCtx2.drawImage(image, xSize * i7, ySize * j3, xSize, ySize, 0, 0, xSize, ySize);
}
}
return {
canvas: tmpCanvas2.canvas,
scaleX: dimx2.scale,
scaleY: dimy2.scale,
offsetX: x0,
offsetY: y0
};
}
return {
canvas: tmpCanvas.canvas,
scaleX: dimx.scale,
scaleY: dimy.scale,
offsetX: x0,
offsetY: y0
};
}
getSizeAndScale(step, realOutputSize, scale) {
const maxSize = Math.max(_TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
let size = Math.ceil(step * scale);
if (size >= maxSize) {
size = maxSize;
} else {
scale = size / step;
}
return {
scale,
size
};
}
clipBbox(graphics, x0, y0, x1, y1) {
const bboxWidth = x1 - x0;
const bboxHeight = y1 - y0;
graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
Util.axialAlignedBoundingBox([x0, y0, x1, y1], getCurrentTransform(graphics.ctx), graphics.current.minMax);
graphics.clip();
graphics.endPath();
}
setFillAndStrokeStyleToContext(graphics, paintType, color2) {
const context = graphics.ctx, current2 = graphics.current;
switch (paintType) {
case PaintType.COLORED:
const {
fillStyle,
strokeStyle
} = this.ctx;
context.fillStyle = current2.fillColor = fillStyle;
context.strokeStyle = current2.strokeColor = strokeStyle;
break;
case PaintType.UNCOLORED:
context.fillStyle = context.strokeStyle = color2;
current2.fillColor = current2.strokeColor = color2;
break;
default:
throw new FormatError(`Unsupported paint type: ${paintType}`);
}
}
isModifyingCurrentTransform() {
return false;
}
getPattern(ctx, owner, inverse, pathType, opIdx) {
let matrix = inverse;
if (pathType !== PathType.SHADING) {
matrix = Util.transform(matrix, owner.baseTransform);
if (this.matrix) {
matrix = Util.transform(matrix, this.matrix);
}
}
const temporaryPatternCanvas = this.createPatternCanvas(owner, opIdx);
let domMatrix = new DOMMatrix(matrix);
domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
pattern.setTransform(domMatrix);
return pattern;
}
};
MIN_FONT_SIZE = 16;
MAX_FONT_SIZE = 100;
EXECUTION_TIME = 15;
EXECUTION_STEPS = 10;
FULL_CHUNK_HEIGHT = 16;
SCALE_MATRIX = new DOMMatrix();
XY = new Float32Array(2);
MIN_MAX_INIT = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
CachedCanvases = class {
constructor(canvasFactory) {
this.canvasFactory = canvasFactory;
this.cache = /* @__PURE__ */ Object.create(null);
}
getCanvas(id, width, height) {
let canvasEntry;
if (this.cache[id] !== void 0) {
canvasEntry = this.cache[id];
this.canvasFactory.reset(canvasEntry, width, height);
} else {
canvasEntry = this.canvasFactory.create(width, height);
this.cache[id] = canvasEntry;
}
return canvasEntry;
}
delete(id) {
delete this.cache[id];
}
clear() {
for (const id in this.cache) {
const canvasEntry = this.cache[id];
this.canvasFactory.destroy(canvasEntry);
delete this.cache[id];
}
}
};
CanvasExtraState = class {
alphaIsShape = false;
fontSize = 0;
fontSizeScale = 1;
textMatrix = null;
textMatrixScale = 1;
fontMatrix = FONT_IDENTITY_MATRIX;
leading = 0;
x = 0;
y = 0;
lineX = 0;
lineY = 0;
charSpacing = 0;
wordSpacing = 0;
textHScale = 1;
textRenderingMode = TextRenderingMode.FILL;
textRise = 0;
fillColor = "#000000";
strokeColor = "#000000";
patternFill = false;
patternStroke = false;
fillAlpha = 1;
strokeAlpha = 1;
lineWidth = 1;
activeSMask = null;
transferMaps = "none";
constructor(width, height, preInit) {
preInit?.(this);
this.clipBox = new Float32Array([0, 0, width, height]);
this.minMax = MIN_MAX_INIT.slice();
}
clone() {
const clone3 = Object.create(this);
clone3.clipBox = this.clipBox.slice();
clone3.minMax = this.minMax.slice();
return clone3;
}
getPathBoundingBox(pathType = PathType.FILL, transform = null) {
const box = this.minMax.slice();
if (pathType === PathType.STROKE) {
if (!transform) {
unreachable("Stroke bounding box must include transform.");
}
Util.singularValueDecompose2dScale(transform, XY);
const xStrokePad = XY[0] * this.lineWidth / 2;
const yStrokePad = XY[1] * this.lineWidth / 2;
box[0] -= xStrokePad;
box[1] -= yStrokePad;
box[2] += xStrokePad;
box[3] += yStrokePad;
}
return box;
}
updateClipFromPath() {
const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());
this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
}
isEmptyClip() {
return this.minMax[0] === Infinity;
}
startNewPathAndClipBox(box) {
this.clipBox.set(box, 0);
this.minMax.set(MIN_MAX_INIT, 0);
}
getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {
return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
}
};
LINE_CAP_STYLES = ["butt", "round", "square"];
LINE_JOIN_STYLES = ["miter", "round", "bevel"];
NORMAL_CLIP = {};
EO_CLIP = {};
CanvasGraphics = class _CanvasGraphics {
constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, {
optionalContentConfig,
markedContentStack = null
}, annotationCanvasMap, pageColors, dependencyTracker) {
this.ctx = canvasCtx;
this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
this.stateStack = [];
this.pendingClip = null;
this.pendingEOFill = false;
this.res = null;
this.xobjs = null;
this.commonObjs = commonObjs;
this.objs = objs;
this.canvasFactory = canvasFactory;
this.filterFactory = filterFactory;
this.groupStack = [];
this.baseTransform = null;
this.baseTransformStack = [];
this.groupLevel = 0;
this.smaskStack = [];
this.smaskCounter = 0;
this.tempSMask = null;
this.suspendedCtx = null;
this.contentVisible = true;
this.markedContentStack = markedContentStack || [];
this.optionalContentConfig = optionalContentConfig;
this.cachedCanvases = new CachedCanvases(this.canvasFactory);
this.cachedPatterns = /* @__PURE__ */ new Map();
this.annotationCanvasMap = annotationCanvasMap;
this.viewportScale = 1;
this.outputScaleX = 1;
this.outputScaleY = 1;
this.pageColors = pageColors;
this._cachedScaleForStroking = [-1, 0];
this._cachedGetSinglePixelWidth = null;
this._cachedBitmapsMap = /* @__PURE__ */ new Map();
this.dependencyTracker = dependencyTracker ?? null;
}
getObject(opIdx, data, fallback = null) {
if (typeof data === "string") {
this.dependencyTracker?.recordNamedDependency(opIdx, data);
return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
}
return fallback;
}
beginDrawing({
transform,
viewport,
transparency = false,
background = null
}) {
const width = this.ctx.canvas.width;
const height = this.ctx.canvas.height;
const savedFillStyle = this.ctx.fillStyle;
this.ctx.fillStyle = background || "#ffffff";
this.ctx.fillRect(0, 0, width, height);
this.ctx.fillStyle = savedFillStyle;
if (transparency) {
const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
this.compositeCtx = this.ctx;
this.transparentCanvas = transparentCanvas.canvas;
this.ctx = transparentCanvas.context;
this.ctx.save();
this.ctx.transform(...getCurrentTransform(this.compositeCtx));
}
this.ctx.save();
resetCtxToDefault(this.ctx);
if (transform) {
this.ctx.transform(...transform);
this.outputScaleX = transform[0];
this.outputScaleY = transform[0];
}
this.ctx.transform(...viewport.transform);
this.viewportScale = viewport.scale;
this.baseTransform = getCurrentTransform(this.ctx);
}
executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper, operationsFilter) {
const argsArray = operatorList.argsArray;
const fnArray = operatorList.fnArray;
let i7 = executionStartIdx || 0;
const argsArrayLen = argsArray.length;
if (argsArrayLen === i7) {
return i7;
}
const chunkOperations = argsArrayLen - i7 > EXECUTION_STEPS && typeof continueCallback === "function";
const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
let steps2 = 0;
const commonObjs = this.commonObjs;
const objs = this.objs;
let fnId, fnArgs;
while (true) {
if (stepper !== void 0 && i7 === stepper.nextBreakPoint) {
stepper.breakIt(i7, continueCallback);
return i7;
}
if (!operationsFilter || operationsFilter(i7)) {
fnId = fnArray[i7];
fnArgs = argsArray[i7] ?? null;
if (fnId !== OPS.dependency) {
if (fnArgs === null) {
this[fnId](i7);
} else {
this[fnId](i7, ...fnArgs);
}
} else {
for (const depObjId of fnArgs) {
this.dependencyTracker?.recordNamedData(depObjId, i7);
const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
if (!objsPool.has(depObjId)) {
objsPool.get(depObjId, continueCallback);
return i7;
}
}
}
}
i7++;
if (i7 === argsArrayLen) {
return i7;
}
if (chunkOperations && ++steps2 > EXECUTION_STEPS) {
if (Date.now() > endTime) {
continueCallback();
return i7;
}
steps2 = 0;
}
}
}
#restoreInitialState() {
while (this.stateStack.length || this.inSMaskMode) {
this.restore();
}
this.current.activeSMask = null;
this.ctx.restore();
if (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.transparentCanvas = null;
}
}
endDrawing() {
this.#restoreInitialState();
this.cachedCanvases.clear();
this.cachedPatterns.clear();
for (const cache of this._cachedBitmapsMap.values()) {
for (const canvas of cache.values()) {
if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
canvas.width = canvas.height = 0;
}
}
cache.clear();
}
this._cachedBitmapsMap.clear();
this.#drawFilter();
}
#drawFilter() {
if (this.pageColors) {
const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background);
if (hcmFilterId !== "none") {
const savedFilter = this.ctx.filter;
this.ctx.filter = hcmFilterId;
this.ctx.drawImage(this.ctx.canvas, 0, 0);
this.ctx.filter = savedFilter;
}
}
}
_scaleImage(img, inverseTransform) {
const width = img.width ?? img.displayWidth;
const height = img.height ?? img.displayHeight;
let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
let paintWidth = width, paintHeight = height;
let tmpCanvasId = "prescale1";
let tmpCanvas, tmpCtx;
while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
let newWidth = paintWidth, newHeight = paintHeight;
if (widthScale > 2 && paintWidth > 1) {
newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2);
widthScale /= paintWidth / newWidth;
}
if (heightScale > 2 && paintHeight > 1) {
newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2;
heightScale /= paintHeight / newHeight;
}
tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
tmpCtx = tmpCanvas.context;
tmpCtx.clearRect(0, 0, newWidth, newHeight);
tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
img = tmpCanvas.canvas;
paintWidth = newWidth;
paintHeight = newHeight;
tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
}
return {
img,
paintWidth,
paintHeight
};
}
_createMaskCanvas(opIdx, img) {
const ctx = this.ctx;
const {
width,
height
} = img;
const fillColor = this.current.fillColor;
const isPatternFill = this.current.patternFill;
const currentTransform = getCurrentTransform(ctx);
let cache, cacheKey, scaled, maskCanvas;
if ((img.bitmap || img.data) && img.count > 1) {
const mainKey = img.bitmap || img.data.buffer;
cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
cache = this._cachedBitmapsMap.get(mainKey);
if (!cache) {
cache = /* @__PURE__ */ new Map();
this._cachedBitmapsMap.set(mainKey, cache);
}
const cachedImage = cache.get(cacheKey);
if (cachedImage && !isPatternFill) {
const offsetX2 = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
const offsetY2 = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill);
return {
canvas: cachedImage,
offsetX: offsetX2,
offsetY: offsetY2
};
}
scaled = cachedImage;
}
if (!scaled) {
maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
putBinaryImageMask(maskCanvas.context, img);
}
let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
const minMax = MIN_MAX_INIT.slice();
Util.axialAlignedBoundingBox([0, 0, width, height], maskToCanvas, minMax);
const [minX, minY, maxX, maxY] = minMax;
const drawnWidth = Math.round(maxX - minX) || 1;
const drawnHeight = Math.round(maxY - minY) || 1;
const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
const fillCtx = fillCanvas.context;
const offsetX = minX;
const offsetY = minY;
fillCtx.translate(-offsetX, -offsetY);
fillCtx.transform(...maskToCanvas);
if (!scaled) {
scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx));
scaled = scaled.img;
if (cache && isPatternFill) {
cache.set(cacheKey, scaled);
}
}
fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate);
drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
fillCtx.globalCompositeOperation = "source-in";
const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL, opIdx) : fillColor;
fillCtx.fillRect(0, 0, width, height);
if (cache && !isPatternFill) {
this.cachedCanvases.delete("fillCanvas");
cache.set(cacheKey, fillCanvas.canvas);
}
this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill);
return {
canvas: fillCanvas.canvas,
offsetX: Math.round(offsetX),
offsetY: Math.round(offsetY)
};
}
setLineWidth(opIdx, width) {
this.dependencyTracker?.recordSimpleData("lineWidth", opIdx);
if (width !== this.current.lineWidth) {
this._cachedScaleForStroking[0] = -1;
}
this.current.lineWidth = width;
this.ctx.lineWidth = width;
}
setLineCap(opIdx, style) {
this.dependencyTracker?.recordSimpleData("lineCap", opIdx);
this.ctx.lineCap = LINE_CAP_STYLES[style];
}
setLineJoin(opIdx, style) {
this.dependencyTracker?.recordSimpleData("lineJoin", opIdx);
this.ctx.lineJoin = LINE_JOIN_STYLES[style];
}
setMiterLimit(opIdx, limit2) {
this.dependencyTracker?.recordSimpleData("miterLimit", opIdx);
this.ctx.miterLimit = limit2;
}
setDash(opIdx, dashArray, dashPhase) {
this.dependencyTracker?.recordSimpleData("dash", opIdx);
const ctx = this.ctx;
if (ctx.setLineDash !== void 0) {
ctx.setLineDash(dashArray);
ctx.lineDashOffset = dashPhase;
}
}
setRenderingIntent(opIdx, intent) {
}
setFlatness(opIdx, flatness) {
}
setGState(opIdx, states) {
for (const [key, value] of states) {
switch (key) {
case "LW":
this.setLineWidth(opIdx, value);
break;
case "LC":
this.setLineCap(opIdx, value);
break;
case "LJ":
this.setLineJoin(opIdx, value);
break;
case "ML":
this.setMiterLimit(opIdx, value);
break;
case "D":
this.setDash(opIdx, value[0], value[1]);
break;
case "RI":
this.setRenderingIntent(opIdx, value);
break;
case "FL":
this.setFlatness(opIdx, value);
break;
case "Font":
this.setFont(opIdx, value[0], value[1]);
break;
case "CA":
this.dependencyTracker?.recordSimpleData("strokeAlpha", opIdx);
this.current.strokeAlpha = value;
break;
case "ca":
this.dependencyTracker?.recordSimpleData("fillAlpha", opIdx);
this.ctx.globalAlpha = this.current.fillAlpha = value;
break;
case "BM":
this.dependencyTracker?.recordSimpleData("globalCompositeOperation", opIdx);
this.ctx.globalCompositeOperation = value;
break;
case "SMask":
this.dependencyTracker?.recordSimpleData("SMask", opIdx);
this.current.activeSMask = value ? this.tempSMask : null;
this.tempSMask = null;
this.checkSMaskState();
break;
case "TR":
this.dependencyTracker?.recordSimpleData("filter", opIdx);
this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value);
break;
}
}
}
get inSMaskMode() {
return !!this.suspendedCtx;
}
checkSMaskState() {
const inSMaskMode = this.inSMaskMode;
if (this.current.activeSMask && !inSMaskMode) {
this.beginSMaskMode();
} else if (!this.current.activeSMask && inSMaskMode) {
this.endSMaskMode();
}
}
beginSMaskMode(opIdx) {
if (this.inSMaskMode) {
throw new Error("beginSMaskMode called while already in smask mode");
}
const drawnWidth = this.ctx.canvas.width;
const drawnHeight = this.ctx.canvas.height;
const cacheId = "smaskGroupAt" + this.groupLevel;
const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
this.suspendedCtx = this.ctx;
const ctx = this.ctx = scratchCanvas.context;
ctx.setTransform(this.suspendedCtx.getTransform());
copyCtxState(this.suspendedCtx, ctx);
mirrorContextOperations(ctx, this.suspendedCtx);
this.setGState(opIdx, [["BM", "source-over"]]);
}
endSMaskMode() {
if (!this.inSMaskMode) {
throw new Error("endSMaskMode called while not in smask mode");
}
this.ctx._removeMirroring();
copyCtxState(this.ctx, this.suspendedCtx);
this.ctx = this.suspendedCtx;
this.suspendedCtx = null;
}
compose(dirtyBox) {
if (!this.current.activeSMask) {
return;
}
if (!dirtyBox) {
dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
} else {
dirtyBox[0] = Math.floor(dirtyBox[0]);
dirtyBox[1] = Math.floor(dirtyBox[1]);
dirtyBox[2] = Math.ceil(dirtyBox[2]);
dirtyBox[3] = Math.ceil(dirtyBox[3]);
}
const smask = this.current.activeSMask;
const suspendedCtx = this.suspendedCtx;
this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
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(ctx, smask, layerCtx, layerBox) {
const layerOffsetX = layerBox[0];
const layerOffsetY = layerBox[1];
const layerWidth = layerBox[2] - layerOffsetX;
const layerHeight = layerBox[3] - layerOffsetY;
if (layerWidth === 0 || layerHeight === 0) {
return;
}
this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
ctx.save();
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = "source-over";
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.drawImage(layerCtx.canvas, 0, 0);
ctx.restore();
}
genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
let maskCanvas = maskCtx.canvas;
let maskX = layerOffsetX - maskOffsetX;
let maskY = layerOffsetY - maskOffsetY;
if (backdrop) {
if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) {
const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height);
const ctx = canvas.context;
ctx.drawImage(maskCanvas, -maskX, -maskY);
ctx.globalCompositeOperation = "destination-atop";
ctx.fillStyle = backdrop;
ctx.fillRect(0, 0, width, height);
ctx.globalCompositeOperation = "source-over";
maskCanvas = canvas.canvas;
maskX = maskY = 0;
} else {
maskCtx.save();
maskCtx.globalAlpha = 1;
maskCtx.setTransform(1, 0, 0, 1, 0, 0);
const clip2 = new Path2D();
clip2.rect(maskX, maskY, width, height);
maskCtx.clip(clip2);
maskCtx.globalCompositeOperation = "destination-atop";
maskCtx.fillStyle = backdrop;
maskCtx.fillRect(maskX, maskY, width, height);
maskCtx.restore();
}
}
layerCtx.save();
layerCtx.globalAlpha = 1;
layerCtx.setTransform(1, 0, 0, 1, 0, 0);
if (subtype === "Alpha" && transferMap) {
layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);
} else if (subtype === "Luminosity") {
layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);
}
const clip = new Path2D();
clip.rect(layerOffsetX, layerOffsetY, width, height);
layerCtx.clip(clip);
layerCtx.globalCompositeOperation = "destination-in";
layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height);
layerCtx.restore();
}
save(opIdx) {
if (this.inSMaskMode) {
copyCtxState(this.ctx, this.suspendedCtx);
}
this.ctx.save();
const old = this.current;
this.stateStack.push(old);
this.current = old.clone();
this.dependencyTracker?.save(opIdx);
}
restore(opIdx) {
this.dependencyTracker?.restore(opIdx);
if (this.stateStack.length === 0) {
if (this.inSMaskMode) {
this.endSMaskMode();
}
return;
}
this.current = this.stateStack.pop();
this.ctx.restore();
if (this.inSMaskMode) {
copyCtxState(this.suspendedCtx, this.ctx);
}
this.checkSMaskState();
this.pendingClip = null;
this._cachedScaleForStroking[0] = -1;
this._cachedGetSinglePixelWidth = null;
}
transform(opIdx, a3, b4, c6, d4, e9, f4) {
this.dependencyTracker?.recordIncrementalData("transform", opIdx);
this.ctx.transform(a3, b4, c6, d4, e9, f4);
this._cachedScaleForStroking[0] = -1;
this._cachedGetSinglePixelWidth = null;
}
constructPath(opIdx, op2, data, minMax) {
let [path6] = data;
if (!minMax) {
path6 ||= data[0] = new Path2D();
this[op2](opIdx, path6);
return;
}
if (this.dependencyTracker !== null) {
const outerExtraSize = op2 === OPS.stroke ? this.current.lineWidth / 2 : 0;
this.dependencyTracker.resetBBox(opIdx).recordBBox(opIdx, this.ctx, minMax[0] - outerExtraSize, minMax[2] + outerExtraSize, minMax[1] - outerExtraSize, minMax[3] + outerExtraSize).recordDependencies(opIdx, ["transform"]);
}
if (!(path6 instanceof Path2D)) {
path6 = data[0] = makePathFromDrawOPS(path6);
}
Util.axialAlignedBoundingBox(minMax, getCurrentTransform(this.ctx), this.current.minMax);
this[op2](opIdx, path6);
this._pathStartIdx = opIdx;
}
closePath(opIdx) {
this.ctx.closePath();
}
stroke(opIdx, path6, consumePath = true) {
const ctx = this.ctx;
const strokeColor = this.current.strokeColor;
ctx.globalAlpha = this.current.strokeAlpha;
if (this.contentVisible) {
if (typeof strokeColor === "object" && strokeColor?.getPattern) {
const baseTransform = strokeColor.isModifyingCurrentTransform() ? ctx.getTransform() : null;
ctx.save();
ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx);
if (baseTransform) {
const newPath = new Path2D();
newPath.addPath(path6, ctx.getTransform().invertSelf().multiplySelf(baseTransform));
path6 = newPath;
}
this.rescaleAndStroke(path6, false);
ctx.restore();
} else {
this.rescaleAndStroke(path6, true);
}
}
this.dependencyTracker?.recordDependencies(opIdx, Dependencies.stroke);
if (consumePath) {
this.consumePath(opIdx, path6, this.current.getClippedPathBoundingBox(PathType.STROKE, getCurrentTransform(this.ctx)));
}
ctx.globalAlpha = this.current.fillAlpha;
}
closeStroke(opIdx, path6) {
this.stroke(opIdx, path6);
}
fill(opIdx, path6, consumePath = true) {
const ctx = this.ctx;
const fillColor = this.current.fillColor;
const isPatternFill = this.current.patternFill;
let needRestore = false;
if (isPatternFill) {
const baseTransform = fillColor.isModifyingCurrentTransform() ? ctx.getTransform() : null;
this.dependencyTracker?.save(opIdx);
ctx.save();
ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx);
if (baseTransform) {
const newPath = new Path2D();
newPath.addPath(path6, ctx.getTransform().invertSelf().multiplySelf(baseTransform));
path6 = newPath;
}
needRestore = true;
}
const intersect = this.current.getClippedPathBoundingBox();
if (this.contentVisible && intersect !== null) {
if (this.pendingEOFill) {
ctx.fill(path6, "evenodd");
this.pendingEOFill = false;
} else {
ctx.fill(path6);
}
}
this.dependencyTracker?.recordDependencies(opIdx, Dependencies.fill);
if (needRestore) {
ctx.restore();
this.dependencyTracker?.restore(opIdx);
}
if (consumePath) {
this.consumePath(opIdx, path6, intersect);
}
}
eoFill(opIdx, path6) {
this.pendingEOFill = true;
this.fill(opIdx, path6);
}
fillStroke(opIdx, path6) {
this.fill(opIdx, path6, false);
this.stroke(opIdx, path6, false);
this.consumePath(opIdx, path6);
}
eoFillStroke(opIdx, path6) {
this.pendingEOFill = true;
this.fillStroke(opIdx, path6);
}
closeFillStroke(opIdx, path6) {
this.fillStroke(opIdx, path6);
}
closeEOFillStroke(opIdx, path6) {
this.pendingEOFill = true;
this.fillStroke(opIdx, path6);
}
endPath(opIdx, path6) {
this.consumePath(opIdx, path6);
}
rawFillPath(opIdx, path6) {
this.ctx.fill(path6);
this.dependencyTracker?.recordDependencies(opIdx, Dependencies.rawFillPath).recordOperation(opIdx);
}
clip(opIdx) {
this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx);
this.pendingClip = NORMAL_CLIP;
}
eoClip(opIdx) {
this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx);
this.pendingClip = EO_CLIP;
}
beginText(opIdx) {
this.current.textMatrix = null;
this.current.textMatrixScale = 1;
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
this.dependencyTracker?.recordOpenMarker(opIdx).resetIncrementalData("sameLineText").resetIncrementalData("moveText", opIdx);
}
endText(opIdx) {
const paths = this.pendingTextPaths;
const ctx = this.ctx;
if (this.dependencyTracker) {
const {
dependencyTracker
} = this;
if (paths !== void 0) {
dependencyTracker.recordFutureForcedDependency("textClip", dependencyTracker.getOpenMarker()).recordFutureForcedDependency("textClip", opIdx);
}
dependencyTracker.recordCloseMarker(opIdx);
}
if (paths !== void 0) {
const newPath = new Path2D();
const invTransf = ctx.getTransform().invertSelf();
for (const {
transform,
x: x2,
y: y4,
fontSize,
path: path6
} of paths) {
if (!path6) {
continue;
}
newPath.addPath(path6, new DOMMatrix(transform).preMultiplySelf(invTransf).translate(x2, y4).scale(fontSize, -fontSize));
}
ctx.clip(newPath);
}
delete this.pendingTextPaths;
}
setCharSpacing(opIdx, spacing2) {
this.dependencyTracker?.recordSimpleData("charSpacing", opIdx);
this.current.charSpacing = spacing2;
}
setWordSpacing(opIdx, spacing2) {
this.dependencyTracker?.recordSimpleData("wordSpacing", opIdx);
this.current.wordSpacing = spacing2;
}
setHScale(opIdx, scale) {
this.dependencyTracker?.recordSimpleData("hScale", opIdx);
this.current.textHScale = scale / 100;
}
setLeading(opIdx, leading) {
this.dependencyTracker?.recordSimpleData("leading", opIdx);
this.current.leading = -leading;
}
setFont(opIdx, fontRefName, size) {
this.dependencyTracker?.recordSimpleData("font", opIdx).recordSimpleDataFromNamed("fontObj", fontRefName, opIdx);
const fontObj = this.commonObjs.get(fontRefName);
const current2 = this.current;
if (!fontObj) {
throw new Error(`Can't find font for ${fontRefName}`);
}
current2.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;
if (current2.fontMatrix[0] === 0 || current2.fontMatrix[3] === 0) {
warn("Invalid font matrix for font " + fontRefName);
}
if (size < 0) {
size = -size;
current2.fontDirection = -1;
} else {
current2.fontDirection = 1;
}
this.current.font = fontObj;
this.current.fontSize = size;
if (fontObj.isType3Font) {
return;
}
const name = fontObj.loadedName || "sans-serif";
const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`;
let bold2 = "normal";
if (fontObj.black) {
bold2 = "900";
} else if (fontObj.bold) {
bold2 = "bold";
}
const italic = fontObj.italic ? "italic" : "normal";
let browserFontSize = size;
if (size < MIN_FONT_SIZE) {
browserFontSize = MIN_FONT_SIZE;
} else if (size > MAX_FONT_SIZE) {
browserFontSize = MAX_FONT_SIZE;
}
this.current.fontSizeScale = size / browserFontSize;
this.ctx.font = `${italic} ${bold2} ${browserFontSize}px ${typeface}`;
}
setTextRenderingMode(opIdx, mode) {
this.dependencyTracker?.recordSimpleData("textRenderingMode", opIdx);
this.current.textRenderingMode = mode;
}
setTextRise(opIdx, rise) {
this.dependencyTracker?.recordSimpleData("textRise", opIdx);
this.current.textRise = rise;
}
moveText(opIdx, x2, y4) {
this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText", opIdx);
this.current.x = this.current.lineX += x2;
this.current.y = this.current.lineY += y4;
}
setLeadingMoveText(opIdx, x2, y4) {
this.setLeading(opIdx, -y4);
this.moveText(opIdx, x2, y4);
}
setTextMatrix(opIdx, matrix) {
this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix", opIdx);
const {
current: current2
} = this;
current2.textMatrix = matrix;
current2.textMatrixScale = Math.hypot(matrix[0], matrix[1]);
current2.x = current2.lineX = 0;
current2.y = current2.lineY = 0;
}
nextLine(opIdx) {
this.moveText(opIdx, 0, this.current.leading);
this.dependencyTracker?.recordIncrementalData("moveText", this.dependencyTracker.getSimpleIndex("leading") ?? opIdx);
}
#getScaledPath(path6, currentTransform, transform) {
const newPath = new Path2D();
newPath.addPath(path6, new DOMMatrix(transform).invertSelf().multiplySelf(currentTransform));
return newPath;
}
paintChar(opIdx, character, x2, y4, patternFillTransform, patternStrokeTransform) {
const ctx = this.ctx;
const current2 = this.current;
const font = current2.font;
const textRenderingMode = current2.textRenderingMode;
const fontSize = current2.fontSize / current2.fontSizeScale;
const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
const patternFill = current2.patternFill && !font.missingFile;
const patternStroke = current2.patternStroke && !font.missingFile;
let path6;
if ((font.disableFontFace || isAddToPathSet || patternFill || patternStroke) && !font.missingFile) {
path6 = font.getPathGenerator(this.commonObjs, character);
}
if (path6 && (font.disableFontFace || patternFill || patternStroke)) {
ctx.save();
ctx.translate(x2, y4);
ctx.scale(fontSize, -fontSize);
this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font);
let currentTransform;
if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
if (patternFillTransform) {
currentTransform = ctx.getTransform();
ctx.setTransform(...patternFillTransform);
const scaledPath = this.#getScaledPath(path6, currentTransform, patternFillTransform);
ctx.fill(scaledPath);
} else {
ctx.fill(path6);
}
}
if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
if (patternStrokeTransform) {
currentTransform ||= ctx.getTransform();
ctx.setTransform(...patternStrokeTransform);
const {
a: a3,
b: b4,
c: c6,
d: d4
} = currentTransform;
const invPatternTransform = Util.inverseTransform(patternStrokeTransform);
const transf = Util.transform([a3, b4, c6, d4, 0, 0], invPatternTransform);
Util.singularValueDecompose2dScale(transf, XY);
ctx.lineWidth *= Math.max(XY[0], XY[1]) / fontSize;
ctx.stroke(this.#getScaledPath(path6, currentTransform, patternStrokeTransform));
} else {
ctx.lineWidth /= fontSize;
ctx.stroke(path6);
}
}
ctx.restore();
} else {
if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.fillText(character, x2, y4);
this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x2, y4, () => ctx.measureText(character));
}
if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
if (this.dependencyTracker) {
this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x2, y4, () => ctx.measureText(character)).recordDependencies(opIdx, Dependencies.stroke);
}
ctx.strokeText(character, x2, y4);
}
}
if (isAddToPathSet) {
const paths = this.pendingTextPaths ||= [];
paths.push({
transform: getCurrentTransform(ctx),
x: x2,
y: y4,
fontSize,
path: path6
});
this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x2, y4);
}
}
get isFontSubpixelAAEnabled() {
const {
context: ctx
} = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
ctx.scale(1.5, 1);
ctx.fillText("I", 0, 10);
const data = ctx.getImageData(0, 0, 10, 10).data;
let enabled = false;
for (let i7 = 3; i7 < data.length; i7 += 4) {
if (data[i7] > 0 && data[i7] < 255) {
enabled = true;
break;
}
}
return shadow(this, "isFontSubpixelAAEnabled", enabled);
}
showText(opIdx, glyphs) {
if (this.dependencyTracker) {
this.dependencyTracker.recordDependencies(opIdx, Dependencies.showText).resetBBox(opIdx);
if (this.current.textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG) {
this.dependencyTracker.recordFutureForcedDependency("textClip", opIdx).inheritPendingDependenciesAsFutureForcedDependencies();
}
}
const current2 = this.current;
const font = current2.font;
if (font.isType3Font) {
this.showType3Text(opIdx, glyphs);
this.dependencyTracker?.recordShowTextOperation(opIdx);
return void 0;
}
const fontSize = current2.fontSize;
if (fontSize === 0) {
this.dependencyTracker?.recordOperation(opIdx);
return void 0;
}
const ctx = this.ctx;
const fontSizeScale = current2.fontSizeScale;
const charSpacing = current2.charSpacing;
const wordSpacing = current2.wordSpacing;
const fontDirection = current2.fontDirection;
const textHScale = current2.textHScale * fontDirection;
const glyphsLength = glyphs.length;
const vertical = font.vertical;
const spacingDir = vertical ? 1 : -1;
const defaultVMetrics = font.defaultVMetrics;
const widthAdvanceScale = fontSize * current2.fontMatrix[0];
const simpleFillText = current2.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current2.patternFill;
ctx.save();
if (current2.textMatrix) {
ctx.transform(...current2.textMatrix);
}
ctx.translate(current2.x, current2.y + current2.textRise);
if (fontDirection > 0) {
ctx.scale(textHScale, -1);
} else {
ctx.scale(textHScale, 1);
}
let patternFillTransform, patternStrokeTransform;
if (current2.patternFill) {
ctx.save();
const pattern = current2.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx);
patternFillTransform = getCurrentTransform(ctx);
ctx.restore();
ctx.fillStyle = pattern;
}
if (current2.patternStroke) {
ctx.save();
const pattern = current2.strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx);
patternStrokeTransform = getCurrentTransform(ctx);
ctx.restore();
ctx.strokeStyle = pattern;
}
let lineWidth = current2.lineWidth;
const scale = current2.textMatrixScale;
if (scale === 0 || lineWidth === 0) {
const fillStrokeMode = current2.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
lineWidth = this.getSinglePixelWidth();
}
} else {
lineWidth /= scale;
}
if (fontSizeScale !== 1) {
ctx.scale(fontSizeScale, fontSizeScale);
lineWidth /= fontSizeScale;
}
ctx.lineWidth = lineWidth;
if (font.isInvalidPDFjsFont) {
const chars = [];
let width = 0;
for (const glyph of glyphs) {
chars.push(glyph.unicode);
width += glyph.width;
}
const joinedChars = chars.join("");
ctx.fillText(joinedChars, 0, 0);
if (this.dependencyTracker !== null) {
const measure = ctx.measureText(joinedChars);
this.dependencyTracker.recordBBox(opIdx, this.ctx, -measure.actualBoundingBoxLeft, measure.actualBoundingBoxRight, -measure.actualBoundingBoxAscent, measure.actualBoundingBoxDescent).recordShowTextOperation(opIdx);
}
current2.x += width * widthAdvanceScale * textHScale;
ctx.restore();
this.compose();
return void 0;
}
let x2 = 0, i7;
for (i7 = 0; i7 < glyphsLength; ++i7) {
const glyph = glyphs[i7];
if (typeof glyph === "number") {
x2 += spacingDir * glyph * fontSize / 1e3;
continue;
}
let restoreNeeded = false;
const spacing2 = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
const character = glyph.fontChar;
const accent2 = glyph.accent;
let scaledX, scaledY;
let width = glyph.width;
if (vertical) {
const vmetric = glyph.vmetric || defaultVMetrics;
const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
const vy = vmetric[2] * widthAdvanceScale;
width = vmetric ? -vmetric[0] : width;
scaledX = vx / fontSizeScale;
scaledY = (x2 + vy) / fontSizeScale;
} else {
scaledX = x2 / fontSizeScale;
scaledY = 0;
}
let measure;
if (font.remeasure && width > 0) {
measure = ctx.measureText(character);
const measuredWidth = measure.width * 1e3 / fontSize * fontSizeScale;
if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
const characterScaleX = width / measuredWidth;
restoreNeeded = true;
ctx.save();
ctx.scale(characterScaleX, 1);
scaledX /= characterScaleX;
} else if (width !== measuredWidth) {
scaledX += (width - measuredWidth) / 2e3 * fontSize / fontSizeScale;
}
}
if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
if (simpleFillText && !accent2) {
ctx.fillText(character, scaledX, scaledY);
this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, measure ? {
bbox: null
} : font, fontSize / fontSizeScale, scaledX, scaledY, () => measure ?? ctx.measureText(character));
} else {
this.paintChar(opIdx, character, scaledX, scaledY, patternFillTransform, patternStrokeTransform);
if (accent2) {
const scaledAccentX = scaledX + fontSize * accent2.offset.x / fontSizeScale;
const scaledAccentY = scaledY - fontSize * accent2.offset.y / fontSizeScale;
this.paintChar(opIdx, accent2.fontChar, scaledAccentX, scaledAccentY, patternFillTransform, patternStrokeTransform);
}
}
}
const charWidth = vertical ? width * widthAdvanceScale - spacing2 * fontDirection : width * widthAdvanceScale + spacing2 * fontDirection;
x2 += charWidth;
if (restoreNeeded) {
ctx.restore();
}
}
if (vertical) {
current2.y -= x2;
} else {
current2.x += x2 * textHScale;
}
ctx.restore();
this.compose();
this.dependencyTracker?.recordShowTextOperation(opIdx);
return void 0;
}
showType3Text(opIdx, glyphs) {
const ctx = this.ctx;
const current2 = this.current;
const font = current2.font;
const fontSize = current2.fontSize;
const fontDirection = current2.fontDirection;
const spacingDir = font.vertical ? 1 : -1;
const charSpacing = current2.charSpacing;
const wordSpacing = current2.wordSpacing;
const textHScale = current2.textHScale * fontDirection;
const fontMatrix = current2.fontMatrix || FONT_IDENTITY_MATRIX;
const glyphsLength = glyphs.length;
const isTextInvisible = current2.textRenderingMode === TextRenderingMode.INVISIBLE;
let i7, glyph, width, spacingLength;
if (isTextInvisible || fontSize === 0) {
return;
}
this._cachedScaleForStroking[0] = -1;
this._cachedGetSinglePixelWidth = null;
ctx.save();
if (current2.textMatrix) {
ctx.transform(...current2.textMatrix);
}
ctx.translate(current2.x, current2.y + current2.textRise);
ctx.scale(textHScale, fontDirection);
const dependencyTracker = this.dependencyTracker;
this.dependencyTracker = dependencyTracker ? new CanvasNestedDependencyTracker(dependencyTracker, opIdx) : null;
for (i7 = 0; i7 < glyphsLength; ++i7) {
glyph = glyphs[i7];
if (typeof glyph === "number") {
spacingLength = spacingDir * glyph * fontSize / 1e3;
this.ctx.translate(spacingLength, 0);
current2.x += spacingLength * textHScale;
continue;
}
const spacing2 = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
const operatorList = font.charProcOperatorList[glyph.operatorListId];
if (!operatorList) {
warn(`Type3 character "${glyph.operatorListId}" is not available.`);
} else if (this.contentVisible) {
this.save();
ctx.scale(fontSize, fontSize);
ctx.transform(...fontMatrix);
this.executeOperatorList(operatorList);
this.restore();
}
const p4 = [glyph.width, 0];
Util.applyTransform(p4, fontMatrix);
width = p4[0] * fontSize + spacing2;
ctx.translate(width, 0);
current2.x += width * textHScale;
}
ctx.restore();
if (dependencyTracker) {
this.dependencyTracker = dependencyTracker;
}
}
setCharWidth(opIdx, xWidth, yWidth) {
}
setCharWidthAndBounds(opIdx, xWidth, yWidth, llx, lly, urx, ury) {
const clip = new Path2D();
clip.rect(llx, lly, urx - llx, ury - lly);
this.ctx.clip(clip);
this.dependencyTracker?.recordBBox(opIdx, this.ctx, llx, urx, lly, ury).recordClipBox(opIdx, this.ctx, llx, urx, lly, ury);
this.endPath(opIdx);
}
getColorN_Pattern(opIdx, IR) {
let pattern;
if (IR[0] === "TilingPattern") {
const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);
const canvasGraphicsFactory = {
createCanvasGraphics: (ctx, renderingOpIdx) => new _CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
optionalContentConfig: this.optionalContentConfig,
markedContentStack: this.markedContentStack
}, void 0, void 0, this.dependencyTracker ? new CanvasNestedDependencyTracker(this.dependencyTracker, renderingOpIdx, true) : null)
};
pattern = new TilingPattern(IR, this.ctx, canvasGraphicsFactory, baseTransform);
} else {
pattern = this._getPattern(opIdx, IR[1], IR[2]);
}
return pattern;
}
setStrokeColorN(opIdx, ...args) {
this.dependencyTracker?.recordSimpleData("strokeColor", opIdx);
this.current.strokeColor = this.getColorN_Pattern(opIdx, args);
this.current.patternStroke = true;
}
setFillColorN(opIdx, ...args) {
this.dependencyTracker?.recordSimpleData("fillColor", opIdx);
this.current.fillColor = this.getColorN_Pattern(opIdx, args);
this.current.patternFill = true;
}
setStrokeRGBColor(opIdx, color2) {
this.dependencyTracker?.recordSimpleData("strokeColor", opIdx);
this.ctx.strokeStyle = this.current.strokeColor = color2;
this.current.patternStroke = false;
}
setStrokeTransparent(opIdx) {
this.dependencyTracker?.recordSimpleData("strokeColor", opIdx);
this.ctx.strokeStyle = this.current.strokeColor = "transparent";
this.current.patternStroke = false;
}
setFillRGBColor(opIdx, color2) {
this.dependencyTracker?.recordSimpleData("fillColor", opIdx);
this.ctx.fillStyle = this.current.fillColor = color2;
this.current.patternFill = false;
}
setFillTransparent(opIdx) {
this.dependencyTracker?.recordSimpleData("fillColor", opIdx);
this.ctx.fillStyle = this.current.fillColor = "transparent";
this.current.patternFill = false;
}
_getPattern(opIdx, objId, matrix = null) {
let pattern;
if (this.cachedPatterns.has(objId)) {
pattern = this.cachedPatterns.get(objId);
} else {
pattern = getShadingPattern(this.getObject(opIdx, objId));
this.cachedPatterns.set(objId, pattern);
}
if (matrix) {
pattern.matrix = matrix;
}
return pattern;
}
shadingFill(opIdx, objId) {
if (!this.contentVisible) {
return;
}
const ctx = this.ctx;
this.save(opIdx);
const pattern = this._getPattern(opIdx, objId);
ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING, opIdx);
const inv = getCurrentTransformInverse(ctx);
if (inv) {
const {
width,
height
} = ctx.canvas;
const minMax = MIN_MAX_INIT.slice();
Util.axialAlignedBoundingBox([0, 0, width, height], inv, minMax);
const [x0, y0, x1, y1] = minMax;
this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
} else {
this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
}
this.dependencyTracker?.resetBBox(opIdx).recordFullPageBBox(opIdx).recordDependencies(opIdx, Dependencies.transform).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx);
this.compose(this.current.getClippedPathBoundingBox());
this.restore(opIdx);
}
beginInlineImage() {
unreachable("Should not call beginInlineImage");
}
beginImageData() {
unreachable("Should not call beginImageData");
}
paintFormXObjectBegin(opIdx, matrix, bbox) {
if (!this.contentVisible) {
return;
}
this.save(opIdx);
this.baseTransformStack.push(this.baseTransform);
if (matrix) {
this.transform(opIdx, ...matrix);
}
this.baseTransform = getCurrentTransform(this.ctx);
if (bbox) {
Util.axialAlignedBoundingBox(bbox, this.baseTransform, this.current.minMax);
const [x0, y0, x1, y1] = bbox;
const clip = new Path2D();
clip.rect(x0, y0, x1 - x0, y1 - y0);
this.ctx.clip(clip);
this.dependencyTracker?.recordClipBox(opIdx, this.ctx, x0, x1, y0, y1);
this.endPath(opIdx);
}
}
paintFormXObjectEnd(opIdx) {
if (!this.contentVisible) {
return;
}
this.restore(opIdx);
this.baseTransform = this.baseTransformStack.pop();
}
beginGroup(opIdx, group) {
if (!this.contentVisible) {
return;
}
this.save(opIdx);
if (this.inSMaskMode) {
this.endSMaskMode();
this.current.activeSMask = null;
}
const currentCtx = this.ctx;
if (!group.isolated) {
info("TODO: Support non-isolated groups.");
}
if (group.knockout) {
warn("Knockout groups not supported.");
}
const currentTransform = getCurrentTransform(currentCtx);
if (group.matrix) {
currentCtx.transform(...group.matrix);
}
if (!group.bbox) {
throw new Error("Bounding box is required.");
}
let bounds = MIN_MAX_INIT.slice();
Util.axialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx), bounds);
const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
const offsetX = Math.floor(bounds[0]);
const offsetY = Math.floor(bounds[1]);
const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
let cacheId = "groupAt" + this.groupLevel;
if (group.smask) {
cacheId += "_smask_" + this.smaskCounter++ % 2;
}
const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
const groupCtx = scratchCanvas.context;
groupCtx.translate(-offsetX, -offsetY);
groupCtx.transform(...currentTransform);
let clip = new Path2D();
const [x0, y0, x1, y1] = group.bbox;
clip.rect(x0, y0, x1 - x0, y1 - y0);
if (group.matrix) {
const path6 = new Path2D();
path6.addPath(clip, new DOMMatrix(group.matrix));
clip = path6;
}
groupCtx.clip(clip);
if (group.smask) {
this.smaskStack.push({
canvas: scratchCanvas.canvas,
context: groupCtx,
offsetX,
offsetY,
subtype: group.smask.subtype,
backdrop: group.smask.backdrop,
transferMap: group.smask.transferMap || null,
startTransformInverse: null
});
}
if (!group.smask || this.dependencyTracker) {
currentCtx.setTransform(1, 0, 0, 1, 0, 0);
currentCtx.translate(offsetX, offsetY);
currentCtx.save();
}
copyCtxState(currentCtx, groupCtx);
this.ctx = groupCtx;
this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha", "strokeAlpha", "globalCompositeOperation"]).pushBaseTransform(currentCtx);
this.setGState(opIdx, [["BM", "source-over"], ["ca", 1], ["CA", 1]]);
this.groupStack.push(currentCtx);
this.groupLevel++;
}
endGroup(opIdx, group) {
if (!this.contentVisible) {
return;
}
this.groupLevel--;
const groupCtx = this.ctx;
const ctx = this.groupStack.pop();
this.ctx = ctx;
this.ctx.imageSmoothingEnabled = false;
this.dependencyTracker?.popBaseTransform();
if (group.smask) {
this.tempSMask = this.smaskStack.pop();
this.restore(opIdx);
if (this.dependencyTracker) {
this.ctx.restore();
}
} else {
this.ctx.restore();
const currentMtx = getCurrentTransform(this.ctx);
this.restore(opIdx);
this.ctx.save();
this.ctx.setTransform(...currentMtx);
const dirtyBox = MIN_MAX_INIT.slice();
Util.axialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx, dirtyBox);
this.ctx.drawImage(groupCtx.canvas, 0, 0);
this.ctx.restore();
this.compose(dirtyBox);
}
}
beginAnnotation(opIdx, id, rect, transform, matrix, hasOwnCanvas) {
this.#restoreInitialState();
resetCtxToDefault(this.ctx);
this.ctx.save();
this.save(opIdx);
if (this.baseTransform) {
this.ctx.setTransform(...this.baseTransform);
}
if (rect) {
const width = rect[2] - rect[0];
const height = rect[3] - rect[1];
if (hasOwnCanvas && this.annotationCanvasMap) {
transform = transform.slice();
transform[4] -= rect[0];
transform[5] -= rect[1];
rect = rect.slice();
rect[0] = rect[1] = 0;
rect[2] = width;
rect[3] = height;
Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx), XY);
const {
viewportScale
} = this;
const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
const {
canvas,
context
} = this.annotationCanvas;
this.annotationCanvasMap.set(id, canvas);
this.annotationCanvas.savedCtx = this.ctx;
this.ctx = context;
this.ctx.save();
this.ctx.setTransform(XY[0], 0, 0, -XY[1], 0, height * XY[1]);
resetCtxToDefault(this.ctx);
} else {
resetCtxToDefault(this.ctx);
this.endPath(opIdx);
const clip = new Path2D();
clip.rect(rect[0], rect[1], width, height);
this.ctx.clip(clip);
}
}
this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
this.transform(opIdx, ...transform);
this.transform(opIdx, ...matrix);
}
endAnnotation(opIdx) {
if (this.annotationCanvas) {
this.ctx.restore();
this.#drawFilter();
this.ctx = this.annotationCanvas.savedCtx;
delete this.annotationCanvas.savedCtx;
delete this.annotationCanvas;
}
}
paintImageMaskXObject(opIdx, img) {
if (!this.contentVisible) {
return;
}
const count = img.count;
img = this.getObject(opIdx, img.data, img);
img.count = count;
const ctx = this.ctx;
const mask = this._createMaskCanvas(opIdx, img);
const maskCanvas = mask.canvas;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, mask.offsetX, mask.offsetX + maskCanvas.width, mask.offsetY, mask.offsetY + maskCanvas.height).recordOperation(opIdx);
ctx.restore();
this.compose();
}
paintImageMaskXObjectRepeat(opIdx, img, scaleX, skewX = 0, skewY = 0, scaleY, positions2) {
if (!this.contentVisible) {
return;
}
img = this.getObject(opIdx, img.data, img);
const ctx = this.ctx;
ctx.save();
const currentTransform = getCurrentTransform(ctx);
ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
const mask = this._createMaskCanvas(opIdx, img);
ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
this.dependencyTracker?.resetBBox(opIdx);
for (let i7 = 0, ii = positions2.length; i7 < ii; i7 += 2) {
const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions2[i7], positions2[i7 + 1]]);
ctx.drawImage(mask.canvas, trans[4], trans[5]);
this.dependencyTracker?.recordBBox(opIdx, this.ctx, trans[4], trans[4] + mask.canvas.width, trans[5], trans[5] + mask.canvas.height);
}
ctx.restore();
this.compose();
this.dependencyTracker?.recordOperation(opIdx);
}
paintImageMaskXObjectGroup(opIdx, images) {
if (!this.contentVisible) {
return;
}
const ctx = this.ctx;
const fillColor = this.current.fillColor;
const isPatternFill = this.current.patternFill;
this.dependencyTracker?.resetBBox(opIdx).recordDependencies(opIdx, Dependencies.transformAndFill);
for (const image of images) {
const {
data,
width,
height,
transform
} = image;
const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
const maskCtx = maskCanvas.context;
maskCtx.save();
const img = this.getObject(opIdx, data, image);
putBinaryImageMask(maskCtx, img);
maskCtx.globalCompositeOperation = "source-in";
maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx) : fillColor;
maskCtx.fillRect(0, 0, width, height);
maskCtx.restore();
ctx.save();
ctx.transform(...transform);
ctx.scale(1, -1);
drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
this.dependencyTracker?.recordBBox(opIdx, ctx, 0, width, 0, height);
ctx.restore();
}
this.compose();
this.dependencyTracker?.recordOperation(opIdx);
}
paintImageXObject(opIdx, objId) {
if (!this.contentVisible) {
return;
}
const imgData = this.getObject(opIdx, objId);
if (!imgData) {
warn("Dependent image isn't ready yet");
return;
}
this.paintInlineImageXObject(opIdx, imgData);
}
paintImageXObjectRepeat(opIdx, objId, scaleX, scaleY, positions2) {
if (!this.contentVisible) {
return;
}
const imgData = this.getObject(opIdx, objId);
if (!imgData) {
warn("Dependent image isn't ready yet");
return;
}
const width = imgData.width;
const height = imgData.height;
const map3 = [];
for (let i7 = 0, ii = positions2.length; i7 < ii; i7 += 2) {
map3.push({
transform: [scaleX, 0, 0, scaleY, positions2[i7], positions2[i7 + 1]],
x: 0,
y: 0,
w: width,
h: height
});
}
this.paintInlineImageXObjectGroup(opIdx, imgData, map3);
}
applyTransferMapsToCanvas(ctx) {
if (this.current.transferMaps !== "none") {
ctx.filter = this.current.transferMaps;
ctx.drawImage(ctx.canvas, 0, 0);
ctx.filter = "none";
}
return ctx.canvas;
}
applyTransferMapsToBitmap(imgData) {
if (this.current.transferMaps === "none") {
return imgData.bitmap;
}
const {
bitmap,
width,
height
} = imgData;
const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
const tmpCtx = tmpCanvas.context;
tmpCtx.filter = this.current.transferMaps;
tmpCtx.drawImage(bitmap, 0, 0);
tmpCtx.filter = "none";
return tmpCanvas.canvas;
}
paintInlineImageXObject(opIdx, imgData) {
if (!this.contentVisible) {
return;
}
const width = imgData.width;
const height = imgData.height;
const ctx = this.ctx;
this.save(opIdx);
const {
filter: filter2
} = ctx;
if (filter2 !== "none" && filter2 !== "") {
ctx.filter = "none";
}
ctx.scale(1 / width, -1 / height);
let imgToPaint;
if (imgData.bitmap) {
imgToPaint = this.applyTransferMapsToBitmap(imgData);
} else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
imgToPaint = imgData;
} else {
const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
const tmpCtx = tmpCanvas.context;
putBinaryImageData(tmpCtx, imgData);
imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
}
const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx));
ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate);
this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, ctx, 0, width, -height, 0).recordDependencies(opIdx, Dependencies.imageXObject).recordOperation(opIdx);
drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
this.compose();
this.restore(opIdx);
}
paintInlineImageXObjectGroup(opIdx, imgData, map3) {
if (!this.contentVisible) {
return;
}
const ctx = this.ctx;
let imgToPaint;
if (imgData.bitmap) {
imgToPaint = imgData.bitmap;
} else {
const w3 = imgData.width;
const h7 = imgData.height;
const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w3, h7);
const tmpCtx = tmpCanvas.context;
putBinaryImageData(tmpCtx, imgData);
imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);
}
this.dependencyTracker?.resetBBox(opIdx);
for (const entry of map3) {
ctx.save();
ctx.transform(...entry.transform);
ctx.scale(1, -1);
drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
this.dependencyTracker?.recordBBox(opIdx, ctx, 0, 1, -1, 0);
ctx.restore();
}
this.dependencyTracker?.recordOperation(opIdx);
this.compose();
}
paintSolidColorImageMask(opIdx) {
if (!this.contentVisible) {
return;
}
this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, 0, 1, 0, 1).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx);
this.ctx.fillRect(0, 0, 1, 1);
this.compose();
}
markPoint(opIdx, tag) {
}
markPointProps(opIdx, tag, properties) {
}
beginMarkedContent(opIdx, tag) {
this.dependencyTracker?.beginMarkedContent(opIdx);
this.markedContentStack.push({
visible: true
});
}
beginMarkedContentProps(opIdx, tag, properties) {
this.dependencyTracker?.beginMarkedContent(opIdx);
if (tag === "OC") {
this.markedContentStack.push({
visible: this.optionalContentConfig.isVisible(properties)
});
} else {
this.markedContentStack.push({
visible: true
});
}
this.contentVisible = this.isContentVisible();
}
endMarkedContent(opIdx) {
this.dependencyTracker?.endMarkedContent(opIdx);
this.markedContentStack.pop();
this.contentVisible = this.isContentVisible();
}
beginCompat(opIdx) {
}
endCompat(opIdx) {
}
consumePath(opIdx, path6, clipBox) {
const isEmpty = this.current.isEmptyClip();
if (this.pendingClip) {
this.current.updateClipFromPath();
}
if (!this.pendingClip) {
this.compose(clipBox);
}
const ctx = this.ctx;
if (this.pendingClip) {
if (!isEmpty) {
if (this.pendingClip === EO_CLIP) {
ctx.clip(path6, "evenodd");
} else {
ctx.clip(path6);
}
}
this.pendingClip = null;
this.dependencyTracker?.bboxToClipBoxDropOperation(opIdx).recordFutureForcedDependency("clipPath", opIdx);
} else {
this.dependencyTracker?.recordOperation(opIdx);
}
this.current.startNewPathAndClipBox(this.current.clipBox);
}
getSinglePixelWidth() {
if (!this._cachedGetSinglePixelWidth) {
const m4 = getCurrentTransform(this.ctx);
if (m4[1] === 0 && m4[2] === 0) {
this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m4[0]), Math.abs(m4[3]));
} else {
const absDet = Math.abs(m4[0] * m4[3] - m4[2] * m4[1]);
const normX = Math.hypot(m4[0], m4[2]);
const normY = Math.hypot(m4[1], m4[3]);
this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
}
}
return this._cachedGetSinglePixelWidth;
}
getScaleForStroking() {
if (this._cachedScaleForStroking[0] === -1) {
const {
lineWidth
} = this.current;
const {
a: a3,
b: b4,
c: c6,
d: d4
} = this.ctx.getTransform();
let scaleX, scaleY;
if (b4 === 0 && c6 === 0) {
const normX = Math.abs(a3);
const normY = Math.abs(d4);
if (normX === normY) {
if (lineWidth === 0) {
scaleX = scaleY = 1 / normX;
} else {
const scaledLineWidth = normX * lineWidth;
scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;
}
} else if (lineWidth === 0) {
scaleX = 1 / normX;
scaleY = 1 / normY;
} else {
const scaledXLineWidth = normX * lineWidth;
const scaledYLineWidth = normY * lineWidth;
scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
}
} else {
const absDet = Math.abs(a3 * d4 - b4 * c6);
const normX = Math.hypot(a3, b4);
const normY = Math.hypot(c6, d4);
if (lineWidth === 0) {
scaleX = normY / absDet;
scaleY = normX / absDet;
} else {
const baseArea = lineWidth * absDet;
scaleX = normY > baseArea ? normY / baseArea : 1;
scaleY = normX > baseArea ? normX / baseArea : 1;
}
}
this._cachedScaleForStroking[0] = scaleX;
this._cachedScaleForStroking[1] = scaleY;
}
return this._cachedScaleForStroking;
}
rescaleAndStroke(path6, saveRestore) {
const {
ctx,
current: {
lineWidth
}
} = this;
const [scaleX, scaleY] = this.getScaleForStroking();
if (scaleX === scaleY) {
ctx.lineWidth = (lineWidth || 1) * scaleX;
ctx.stroke(path6);
return;
}
const dashes = ctx.getLineDash();
if (saveRestore) {
ctx.save();
}
ctx.scale(scaleX, scaleY);
SCALE_MATRIX.a = 1 / scaleX;
SCALE_MATRIX.d = 1 / scaleY;
const newPath = new Path2D();
newPath.addPath(path6, SCALE_MATRIX);
if (dashes.length > 0) {
const scale = Math.max(scaleX, scaleY);
ctx.setLineDash(dashes.map((x2) => x2 / scale));
ctx.lineDashOffset /= scale;
}
ctx.lineWidth = lineWidth || 1;
ctx.stroke(newPath);
if (saveRestore) {
ctx.restore();
}
}
isContentVisible() {
for (let i7 = this.markedContentStack.length - 1; i7 >= 0; i7--) {
if (!this.markedContentStack[i7].visible) {
return false;
}
}
return true;
}
};
for (const op2 in OPS) {
if (CanvasGraphics.prototype[op2] !== void 0) {
CanvasGraphics.prototype[OPS[op2]] = CanvasGraphics.prototype[op2];
}
}
GlobalWorkerOptions = class {
static #port = null;
static #src = "";
static get workerPort() {
return this.#port;
}
static set workerPort(val2) {
if (!(typeof Worker !== "undefined" && val2 instanceof Worker) && val2 !== null) {
throw new Error("Invalid `workerPort` type.");
}
this.#port = val2;
}
static get workerSrc() {
return this.#src;
}
static set workerSrc(val2) {
if (typeof val2 !== "string") {
throw new Error("Invalid `workerSrc` type.");
}
this.#src = val2;
}
};
Metadata = class {
#map;
#data;
constructor({
parsedData,
rawData
}) {
this.#map = parsedData;
this.#data = rawData;
}
getRaw() {
return this.#data;
}
get(name) {
return this.#map.get(name) ?? null;
}
[Symbol.iterator]() {
return this.#map.entries();
}
};
INTERNAL = Symbol("INTERNAL");
OptionalContentGroup = class {
#isDisplay = false;
#isPrint = false;
#userSet = false;
#visible = true;
constructor(renderingIntent, {
name,
intent,
usage,
rbGroups
}) {
this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);
this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
this.name = name;
this.intent = intent;
this.usage = usage;
this.rbGroups = rbGroups;
}
get visible() {
if (this.#userSet) {
return this.#visible;
}
if (!this.#visible) {
return false;
}
const {
print,
view
} = this.usage;
if (this.#isDisplay) {
return view?.viewState !== "OFF";
} else if (this.#isPrint) {
return print?.printState !== "OFF";
}
return true;
}
_setVisible(internal, visible, userSet = false) {
if (internal !== INTERNAL) {
unreachable("Internal method `_setVisible` called.");
}
this.#userSet = userSet;
this.#visible = visible;
}
};
OptionalContentConfig = class {
#cachedGetHash = null;
#groups = /* @__PURE__ */ new Map();
#initialHash = null;
#order = null;
constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {
this.renderingIntent = renderingIntent;
this.name = null;
this.creator = null;
if (data === null) {
return;
}
this.name = data.name;
this.creator = data.creator;
this.#order = data.order;
for (const group of data.groups) {
this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group));
}
if (data.baseState === "OFF") {
for (const group of this.#groups.values()) {
group._setVisible(INTERNAL, false);
}
}
for (const on of data.on) {
this.#groups.get(on)._setVisible(INTERNAL, true);
}
for (const off of data.off) {
this.#groups.get(off)._setVisible(INTERNAL, false);
}
this.#initialHash = this.getHash();
}
#evaluateVisibilityExpression(array) {
const length = array.length;
if (length < 2) {
return true;
}
const operator = array[0];
for (let i7 = 1; i7 < length; i7++) {
const element = array[i7];
let state;
if (Array.isArray(element)) {
state = this.#evaluateVisibilityExpression(element);
} else if (this.#groups.has(element)) {
state = this.#groups.get(element).visible;
} else {
warn(`Optional content group not found: ${element}`);
return true;
}
switch (operator) {
case "And":
if (!state) {
return false;
}
break;
case "Or":
if (state) {
return true;
}
break;
case "Not":
return !state;
default:
return true;
}
}
return operator === "And";
}
isVisible(group) {
if (this.#groups.size === 0) {
return true;
}
if (!group) {
info("Optional content group not defined.");
return true;
}
if (group.type === "OCG") {
if (!this.#groups.has(group.id)) {
warn(`Optional content group not found: ${group.id}`);
return true;
}
return this.#groups.get(group.id).visible;
} else if (group.type === "OCMD") {
if (group.expression) {
return this.#evaluateVisibilityExpression(group.expression);
}
if (!group.policy || group.policy === "AnyOn") {
for (const id of group.ids) {
if (!this.#groups.has(id)) {
warn(`Optional content group not found: ${id}`);
return true;
}
if (this.#groups.get(id).visible) {
return true;
}
}
return false;
} else if (group.policy === "AllOn") {
for (const id of group.ids) {
if (!this.#groups.has(id)) {
warn(`Optional content group not found: ${id}`);
return true;
}
if (!this.#groups.get(id).visible) {
return false;
}
}
return true;
} else if (group.policy === "AnyOff") {
for (const id of group.ids) {
if (!this.#groups.has(id)) {
warn(`Optional content group not found: ${id}`);
return true;
}
if (!this.#groups.get(id).visible) {
return true;
}
}
return false;
} else if (group.policy === "AllOff") {
for (const id of group.ids) {
if (!this.#groups.has(id)) {
warn(`Optional content group not found: ${id}`);
return true;
}
if (this.#groups.get(id).visible) {
return false;
}
}
return true;
}
warn(`Unknown optional content policy ${group.policy}.`);
return true;
}
warn(`Unknown group type ${group.type}.`);
return true;
}
setVisibility(id, visible = true, preserveRB = true) {
const group = this.#groups.get(id);
if (!group) {
warn(`Optional content group not found: ${id}`);
return;
}
if (preserveRB && visible && group.rbGroups.length) {
for (const rbGroup of group.rbGroups) {
for (const otherId of rbGroup) {
if (otherId !== id) {
this.#groups.get(otherId)?._setVisible(INTERNAL, false, true);
}
}
}
}
group._setVisible(INTERNAL, !!visible, true);
this.#cachedGetHash = null;
}
setOCGState({
state,
preserveRB
}) {
let operator;
for (const elem of state) {
switch (elem) {
case "ON":
case "OFF":
case "Toggle":
operator = elem;
continue;
}
const group = this.#groups.get(elem);
if (!group) {
continue;
}
switch (operator) {
case "ON":
this.setVisibility(elem, true, preserveRB);
break;
case "OFF":
this.setVisibility(elem, false, preserveRB);
break;
case "Toggle":
this.setVisibility(elem, !group.visible, preserveRB);
break;
}
}
this.#cachedGetHash = null;
}
get hasInitialVisibility() {
return this.#initialHash === null || this.getHash() === this.#initialHash;
}
getOrder() {
if (!this.#groups.size) {
return null;
}
if (this.#order) {
return this.#order.slice();
}
return [...this.#groups.keys()];
}
getGroup(id) {
return this.#groups.get(id) || null;
}
getHash() {
if (this.#cachedGetHash !== null) {
return this.#cachedGetHash;
}
const hash = new MurmurHash3_64();
for (const [id, group] of this.#groups) {
hash.update(`${id}:${group.visible}`);
}
return this.#cachedGetHash = hash.hexdigest();
}
[Symbol.iterator]() {
return this.#groups.entries();
}
};
PDFDataTransportStream = class {
constructor(pdfDataRangeTransport, {
disableRange = false,
disableStream = false
}) {
assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
const {
length,
initialData,
progressiveDone,
contentDispositionFilename
} = pdfDataRangeTransport;
this._queuedChunks = [];
this._progressiveDone = progressiveDone;
this._contentDispositionFilename = contentDispositionFilename;
if (initialData?.length > 0) {
const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
this._queuedChunks.push(buffer);
}
this._pdfDataRangeTransport = pdfDataRangeTransport;
this._isStreamingSupported = !disableStream;
this._isRangeSupported = !disableRange;
this._contentLength = length;
this._fullRequestReader = null;
this._rangeReaders = [];
pdfDataRangeTransport.addRangeListener((begin, chunk) => {
this._onReceiveData({
begin,
chunk
});
});
pdfDataRangeTransport.addProgressListener((loaded, total) => {
this._onProgress({
loaded,
total
});
});
pdfDataRangeTransport.addProgressiveReadListener((chunk) => {
this._onReceiveData({
chunk
});
});
pdfDataRangeTransport.addProgressiveDoneListener(() => {
this._onProgressiveDone();
});
pdfDataRangeTransport.transportReady();
}
_onReceiveData({
begin,
chunk
}) {
const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
if (begin === void 0) {
if (this._fullRequestReader) {
this._fullRequestReader._enqueue(buffer);
} else {
this._queuedChunks.push(buffer);
}
} else {
const found = this._rangeReaders.some(function(rangeReader) {
if (rangeReader._begin !== begin) {
return false;
}
rangeReader._enqueue(buffer);
return true;
});
assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
}
}
get _progressiveDataLength() {
return this._fullRequestReader?._loaded ?? 0;
}
_onProgress(evt) {
if (evt.total === void 0) {
this._rangeReaders[0]?.onProgress?.({
loaded: evt.loaded
});
} else {
this._fullRequestReader?.onProgress?.({
loaded: evt.loaded,
total: evt.total
});
}
}
_onProgressiveDone() {
this._fullRequestReader?.progressiveDone();
this._progressiveDone = true;
}
_removeRangeReader(reader) {
const i7 = this._rangeReaders.indexOf(reader);
if (i7 >= 0) {
this._rangeReaders.splice(i7, 1);
}
}
getFullReader() {
assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
const queuedChunks = this._queuedChunks;
this._queuedChunks = null;
return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
}
getRangeReader(begin, end) {
if (end <= this._progressiveDataLength) {
return null;
}
const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
this._pdfDataRangeTransport.requestDataRange(begin, end);
this._rangeReaders.push(reader);
return reader;
}
cancelAllRequests(reason) {
this._fullRequestReader?.cancel(reason);
for (const reader of this._rangeReaders.slice(0)) {
reader.cancel(reason);
}
this._pdfDataRangeTransport.abort();
}
};
PDFDataTransportStreamReader = class {
constructor(stream2, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
this._stream = stream2;
this._done = progressiveDone || false;
this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null;
this._queuedChunks = queuedChunks || [];
this._loaded = 0;
for (const chunk of this._queuedChunks) {
this._loaded += chunk.byteLength;
}
this._requests = [];
this._headersReady = Promise.resolve();
stream2._fullRequestReader = this;
this.onProgress = null;
}
_enqueue(chunk) {
if (this._done) {
return;
}
if (this._requests.length > 0) {
const requestCapability = this._requests.shift();
requestCapability.resolve({
value: chunk,
done: false
});
} else {
this._queuedChunks.push(chunk);
}
this._loaded += chunk.byteLength;
}
get headersReady() {
return this._headersReady;
}
get filename() {
return this._filename;
}
get isRangeSupported() {
return this._stream._isRangeSupported;
}
get isStreamingSupported() {
return this._stream._isStreamingSupported;
}
get contentLength() {
return this._stream._contentLength;
}
async read() {
if (this._queuedChunks.length > 0) {
const chunk = this._queuedChunks.shift();
return {
value: chunk,
done: false
};
}
if (this._done) {
return {
value: void 0,
done: true
};
}
const requestCapability = Promise.withResolvers();
this._requests.push(requestCapability);
return requestCapability.promise;
}
cancel(reason) {
this._done = true;
for (const requestCapability of this._requests) {
requestCapability.resolve({
value: void 0,
done: true
});
}
this._requests.length = 0;
}
progressiveDone() {
if (this._done) {
return;
}
this._done = true;
}
};
PDFDataTransportStreamRangeReader = class {
constructor(stream2, begin, end) {
this._stream = stream2;
this._begin = begin;
this._end = end;
this._queuedChunk = null;
this._requests = [];
this._done = false;
this.onProgress = null;
}
_enqueue(chunk) {
if (this._done) {
return;
}
if (this._requests.length === 0) {
this._queuedChunk = chunk;
} else {
const requestsCapability = this._requests.shift();
requestsCapability.resolve({
value: chunk,
done: false
});
for (const requestCapability of this._requests) {
requestCapability.resolve({
value: void 0,
done: true
});
}
this._requests.length = 0;
}
this._done = true;
this._stream._removeRangeReader(this);
}
get isStreamingSupported() {
return false;
}
async read() {
if (this._queuedChunk) {
const chunk = this._queuedChunk;
this._queuedChunk = null;
return {
value: chunk,
done: false
};
}
if (this._done) {
return {
value: void 0,
done: true
};
}
const requestCapability = Promise.withResolvers();
this._requests.push(requestCapability);
return requestCapability.promise;
}
cancel(reason) {
this._done = true;
for (const requestCapability of this._requests) {
requestCapability.resolve({
value: void 0,
done: true
});
}
this._requests.length = 0;
this._stream._removeRangeReader(this);
}
};
PDFFetchStream = class {
_responseOrigin = null;
constructor(source) {
this.source = source;
this.isHttp = /^https?:/i.test(source.url);
this.headers = createHeaders(this.isHttp, source.httpHeaders);
this._fullRequestReader = null;
this._rangeRequestReaders = [];
}
get _progressiveDataLength() {
return this._fullRequestReader?._loaded ?? 0;
}
getFullReader() {
assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
this._fullRequestReader = new PDFFetchStreamReader(this);
return this._fullRequestReader;
}
getRangeReader(begin, end) {
if (end <= this._progressiveDataLength) {
return null;
}
const reader = new PDFFetchStreamRangeReader(this, begin, end);
this._rangeRequestReaders.push(reader);
return reader;
}
cancelAllRequests(reason) {
this._fullRequestReader?.cancel(reason);
for (const reader of this._rangeRequestReaders.slice(0)) {
reader.cancel(reason);
}
}
};
PDFFetchStreamReader = class {
constructor(stream2) {
this._stream = stream2;
this._reader = null;
this._loaded = 0;
this._filename = null;
const source = stream2.source;
this._withCredentials = source.withCredentials || false;
this._contentLength = source.length;
this._headersCapability = Promise.withResolvers();
this._disableRange = source.disableRange || false;
this._rangeChunkSize = source.rangeChunkSize;
if (!this._rangeChunkSize && !this._disableRange) {
this._disableRange = true;
}
this._abortController = new AbortController();
this._isStreamingSupported = !source.disableStream;
this._isRangeSupported = !source.disableRange;
const headers = new Headers(stream2.headers);
const url = source.url;
fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then((response) => {
stream2._responseOrigin = getResponseOrigin(response.url);
if (!validateResponseStatus(response.status)) {
throw createResponseError(response.status, url);
}
this._reader = response.body.getReader();
this._headersCapability.resolve();
const responseHeaders = response.headers;
const {
allowRangeRequests,
suggestedLength
} = validateRangeRequestCapabilities({
responseHeaders,
isHttp: stream2.isHttp,
rangeChunkSize: this._rangeChunkSize,
disableRange: this._disableRange
});
this._isRangeSupported = allowRangeRequests;
this._contentLength = suggestedLength || this._contentLength;
this._filename = extractFilenameFromHeader(responseHeaders);
if (!this._isStreamingSupported && this._isRangeSupported) {
this.cancel(new AbortException("Streaming is disabled."));
}
}).catch(this._headersCapability.reject);
this.onProgress = null;
}
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() {
await this._headersCapability.promise;
const {
value,
done
} = await this._reader.read();
if (done) {
return {
value,
done
};
}
this._loaded += value.byteLength;
this.onProgress?.({
loaded: this._loaded,
total: this._contentLength
});
return {
value: getArrayBuffer(value),
done: false
};
}
cancel(reason) {
this._reader?.cancel(reason);
this._abortController.abort();
}
};
PDFFetchStreamRangeReader = class {
constructor(stream2, begin, end) {
this._stream = stream2;
this._reader = null;
this._loaded = 0;
const source = stream2.source;
this._withCredentials = source.withCredentials || false;
this._readCapability = Promise.withResolvers();
this._isStreamingSupported = !source.disableStream;
this._abortController = new AbortController();
const headers = new Headers(stream2.headers);
headers.append("Range", `bytes=${begin}-${end - 1}`);
const url = source.url;
fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then((response) => {
const responseOrigin = getResponseOrigin(response.url);
if (responseOrigin !== stream2._responseOrigin) {
throw new Error(`Expected range response-origin "${responseOrigin}" to match "${stream2._responseOrigin}".`);
}
if (!validateResponseStatus(response.status)) {
throw createResponseError(response.status, url);
}
this._readCapability.resolve();
this._reader = response.body.getReader();
}).catch(this._readCapability.reject);
this.onProgress = null;
}
get isStreamingSupported() {
return this._isStreamingSupported;
}
async read() {
await this._readCapability.promise;
const {
value,
done
} = await this._reader.read();
if (done) {
return {
value,
done
};
}
this._loaded += value.byteLength;
this.onProgress?.({
loaded: this._loaded
});
return {
value: getArrayBuffer(value),
done: false
};
}
cancel(reason) {
this._reader?.cancel(reason);
this._abortController.abort();
}
};
OK_RESPONSE = 200;
PARTIAL_CONTENT_RESPONSE = 206;
NetworkManager = class {
_responseOrigin = null;
constructor({
url,
httpHeaders,
withCredentials
}) {
this.url = url;
this.isHttp = /^https?:/i.test(url);
this.headers = createHeaders(this.isHttp, httpHeaders);
this.withCredentials = withCredentials || false;
this.currXhrId = 0;
this.pendingRequests = /* @__PURE__ */ Object.create(null);
}
request(args) {
const xhr = new XMLHttpRequest();
const xhrId = this.currXhrId++;
const pendingRequest = this.pendingRequests[xhrId] = {
xhr
};
xhr.open("GET", this.url);
xhr.withCredentials = this.withCredentials;
for (const [key, val2] of this.headers) {
xhr.setRequestHeader(key, val2);
}
if (this.isHttp && "begin" in args && "end" in args) {
xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
} else {
pendingRequest.expectedStatus = OK_RESPONSE;
}
xhr.responseType = "arraybuffer";
assert(args.onError, "Expected `onError` callback to be provided.");
xhr.onerror = () => {
args.onError(xhr.status);
};
xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
xhr.onprogress = this.onProgress.bind(this, xhrId);
pendingRequest.onHeadersReceived = args.onHeadersReceived;
pendingRequest.onDone = args.onDone;
pendingRequest.onError = args.onError;
pendingRequest.onProgress = args.onProgress;
xhr.send(null);
return xhrId;
}
onProgress(xhrId, evt) {
const pendingRequest = this.pendingRequests[xhrId];
if (!pendingRequest) {
return;
}
pendingRequest.onProgress?.(evt);
}
onStateChange(xhrId, evt) {
const pendingRequest = this.pendingRequests[xhrId];
if (!pendingRequest) {
return;
}
const xhr = pendingRequest.xhr;
if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
pendingRequest.onHeadersReceived();
delete pendingRequest.onHeadersReceived;
}
if (xhr.readyState !== 4) {
return;
}
if (!(xhrId in this.pendingRequests)) {
return;
}
delete this.pendingRequests[xhrId];
if (xhr.status === 0 && this.isHttp) {
pendingRequest.onError(xhr.status);
return;
}
const xhrStatus = xhr.status || OK_RESPONSE;
const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
pendingRequest.onError(xhr.status);
return;
}
const chunk = network_getArrayBuffer(xhr);
if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
const rangeHeader = xhr.getResponseHeader("Content-Range");
const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
if (matches) {
pendingRequest.onDone({
begin: parseInt(matches[1], 10),
chunk
});
} else {
warn(`Missing or invalid "Content-Range" header.`);
pendingRequest.onError(0);
}
} else if (chunk) {
pendingRequest.onDone({
begin: 0,
chunk
});
} else {
pendingRequest.onError(xhr.status);
}
}
getRequestXhr(xhrId) {
return this.pendingRequests[xhrId].xhr;
}
isPendingRequest(xhrId) {
return xhrId in this.pendingRequests;
}
abortRequest(xhrId) {
const xhr = this.pendingRequests[xhrId].xhr;
delete this.pendingRequests[xhrId];
xhr.abort();
}
};
PDFNetworkStream = class {
constructor(source) {
this._source = source;
this._manager = new NetworkManager(source);
this._rangeChunkSize = source.rangeChunkSize;
this._fullRequestReader = null;
this._rangeRequestReaders = [];
}
_onRangeRequestReaderClosed(reader) {
const i7 = this._rangeRequestReaders.indexOf(reader);
if (i7 >= 0) {
this._rangeRequestReaders.splice(i7, 1);
}
}
getFullReader() {
assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
return this._fullRequestReader;
}
getRangeReader(begin, end) {
const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
this._rangeRequestReaders.push(reader);
return reader;
}
cancelAllRequests(reason) {
this._fullRequestReader?.cancel(reason);
for (const reader of this._rangeRequestReaders.slice(0)) {
reader.cancel(reason);
}
}
};
PDFNetworkStreamFullRequestReader = class {
constructor(manager, source) {
this._manager = manager;
this._url = source.url;
this._fullRequestId = manager.request({
onHeadersReceived: this._onHeadersReceived.bind(this),
onDone: this._onDone.bind(this),
onError: this._onError.bind(this),
onProgress: this._onProgress.bind(this)
});
this._headersCapability = Promise.withResolvers();
this._disableRange = source.disableRange || false;
this._contentLength = source.length;
this._rangeChunkSize = source.rangeChunkSize;
if (!this._rangeChunkSize && !this._disableRange) {
this._disableRange = true;
}
this._isStreamingSupported = false;
this._isRangeSupported = false;
this._cachedChunks = [];
this._requests = [];
this._done = false;
this._storedError = void 0;
this._filename = null;
this.onProgress = null;
}
_onHeadersReceived() {
const fullRequestXhrId = this._fullRequestId;
const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
this._manager._responseOrigin = getResponseOrigin(fullRequestXhr.responseURL);
const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders();
const responseHeaders = new Headers(rawResponseHeaders ? rawResponseHeaders.trimStart().replace(/[^\S ]+$/, "").split(/[\r\n]+/).map((x2) => {
const [key, ...val2] = x2.split(": ");
return [key, val2.join(": ")];
}) : []);
const {
allowRangeRequests,
suggestedLength
} = validateRangeRequestCapabilities({
responseHeaders,
isHttp: this._manager.isHttp,
rangeChunkSize: this._rangeChunkSize,
disableRange: this._disableRange
});
if (allowRangeRequests) {
this._isRangeSupported = true;
}
this._contentLength = suggestedLength || this._contentLength;
this._filename = extractFilenameFromHeader(responseHeaders);
if (this._isRangeSupported) {
this._manager.abortRequest(fullRequestXhrId);
}
this._headersCapability.resolve();
}
_onDone(data) {
if (data) {
if (this._requests.length > 0) {
const requestCapability = this._requests.shift();
requestCapability.resolve({
value: data.chunk,
done: false
});
} else {
this._cachedChunks.push(data.chunk);
}
}
this._done = true;
if (this._cachedChunks.length > 0) {
return;
}
for (const requestCapability of this._requests) {
requestCapability.resolve({
value: void 0,
done: true
});
}
this._requests.length = 0;
}
_onError(status) {
this._storedError = createResponseError(status, this._url);
this._headersCapability.reject(this._storedError);
for (const requestCapability of this._requests) {
requestCapability.reject(this._storedError);
}
this._requests.length = 0;
this._cachedChunks.length = 0;
}
_onProgress(evt) {
this.onProgress?.({
loaded: evt.loaded,
total: evt.lengthComputable ? evt.total : this._contentLength
});
}
get filename() {
return this._filename;
}
get isRangeSupported() {
return this._isRangeSupported;
}
get isStreamingSupported() {
return this._isStreamingSupported;
}
get contentLength() {
return this._contentLength;
}
get headersReady() {
return this._headersCapability.promise;
}
async read() {
await this._headersCapability.promise;
if (this._storedError) {
throw this._storedError;
}
if (this._cachedChunks.length > 0) {
const chunk = this._cachedChunks.shift();
return {
value: chunk,
done: false
};
}
if (this._done) {
return {
value: void 0,
done: true
};
}
const requestCapability = Promise.withResolvers();
this._requests.push(requestCapability);
return requestCapability.promise;
}
cancel(reason) {
this._done = true;
this._headersCapability.reject(reason);
for (const requestCapability of this._requests) {
requestCapability.resolve({
value: void 0,
done: true
});
}
this._requests.length = 0;
if (this._manager.isPendingRequest(this._fullRequestId)) {
this._manager.abortRequest(this._fullRequestId);
}
this._fullRequestReader = null;
}
};
PDFNetworkStreamRangeRequestReader = class {
constructor(manager, begin, end) {
this._manager = manager;
this._url = manager.url;
this._requestId = manager.request({
begin,
end,
onHeadersReceived: this._onHeadersReceived.bind(this),
onDone: this._onDone.bind(this),
onError: this._onError.bind(this),
onProgress: this._onProgress.bind(this)
});
this._requests = [];
this._queuedChunk = null;
this._done = false;
this._storedError = void 0;
this.onProgress = null;
this.onClosed = null;
}
_onHeadersReceived() {
const responseOrigin = getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);
if (responseOrigin !== this._manager._responseOrigin) {
this._storedError = new Error(`Expected range response-origin "${responseOrigin}" to match "${this._manager._responseOrigin}".`);
this._onError(0);
}
}
_close() {
this.onClosed?.(this);
}
_onDone(data) {
const chunk = data.chunk;
if (this._requests.length > 0) {
const requestCapability = this._requests.shift();
requestCapability.resolve({
value: chunk,
done: false
});
} else {
this._queuedChunk = chunk;
}
this._done = true;
for (const requestCapability of this._requests) {
requestCapability.resolve({
value: void 0,
done: true
});
}
this._requests.length = 0;
this._close();
}
_onError(status) {
this._storedError ??= createResponseError(status, this._url);
for (const requestCapability of this._requests) {
requestCapability.reject(this._storedError);
}
this._requests.length = 0;
this._queuedChunk = null;
}
_onProgress(evt) {
if (!this.isStreamingSupported) {
this.onProgress?.({
loaded: evt.loaded
});
}
}
get isStreamingSupported() {
return false;
}
async read() {
if (this._storedError) {
throw this._storedError;
}
if (this._queuedChunk !== null) {
const chunk = this._queuedChunk;
this._queuedChunk = null;
return {
value: chunk,
done: false
};
}
if (this._done) {
return {
value: void 0,
done: true
};
}
const requestCapability = Promise.withResolvers();
this._requests.push(requestCapability);
return requestCapability.promise;
}
cancel(reason) {
this._done = true;
for (const requestCapability of this._requests) {
requestCapability.resolve({
value: void 0,
done: true
});
}
this._requests.length = 0;
if (this._manager.isPendingRequest(this._requestId)) {
this._manager.abortRequest(this._requestId);
}
this._close();
}
};
urlRegex = /^[a-z][a-z0-9\-+.]+:/i;
PDFNodeStream = class {
constructor(source) {
this.source = source;
this.url = parseUrlOrPath(source.url);
assert(this.url.protocol === "file:", "PDFNodeStream only supports file:// URLs.");
this._fullRequestReader = null;
this._rangeRequestReaders = [];
}
get _progressiveDataLength() {
return this._fullRequestReader?._loaded ?? 0;
}
getFullReader() {
assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
this._fullRequestReader = new PDFNodeStreamFsFullReader(this);
return this._fullRequestReader;
}
getRangeReader(start, end) {
if (end <= this._progressiveDataLength) {
return null;
}
const rangeReader = new PDFNodeStreamFsRangeReader(this, start, end);
this._rangeRequestReaders.push(rangeReader);
return rangeReader;
}
cancelAllRequests(reason) {
this._fullRequestReader?.cancel(reason);
for (const reader of this._rangeRequestReaders.slice(0)) {
reader.cancel(reason);
}
}
};
PDFNodeStreamFsFullReader = class {
constructor(stream2) {
this._url = stream2.url;
this._done = false;
this._storedError = null;
this.onProgress = null;
const source = stream2.source;
this._contentLength = source.length;
this._loaded = 0;
this._filename = null;
this._disableRange = source.disableRange || false;
this._rangeChunkSize = source.rangeChunkSize;
if (!this._rangeChunkSize && !this._disableRange) {
this._disableRange = true;
}
this._isStreamingSupported = !source.disableStream;
this._isRangeSupported = !source.disableRange;
this._readableStream = null;
this._readCapability = Promise.withResolvers();
this._headersCapability = Promise.withResolvers();
const fs = process.getBuiltinModule("fs");
fs.promises.lstat(this._url).then((stat) => {
this._contentLength = stat.size;
this._setReadableStream(fs.createReadStream(this._url));
this._headersCapability.resolve();
}, (error) => {
if (error.code === "ENOENT") {
error = createResponseError(0, this._url.href);
}
this._storedError = error;
this._headersCapability.reject(error);
});
}
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() {
await this._readCapability.promise;
if (this._done) {
return {
value: void 0,
done: true
};
}
if (this._storedError) {
throw this._storedError;
}
const chunk = this._readableStream.read();
if (chunk === null) {
this._readCapability = Promise.withResolvers();
return this.read();
}
this._loaded += chunk.length;
this.onProgress?.({
loaded: this._loaded,
total: this._contentLength
});
const buffer = new Uint8Array(chunk).buffer;
return {
value: buffer,
done: false
};
}
cancel(reason) {
if (!this._readableStream) {
this._error(reason);
return;
}
this._readableStream.destroy(reason);
}
_error(reason) {
this._storedError = reason;
this._readCapability.resolve();
}
_setReadableStream(readableStream) {
this._readableStream = readableStream;
readableStream.on("readable", () => {
this._readCapability.resolve();
});
readableStream.on("end", () => {
readableStream.destroy();
this._done = true;
this._readCapability.resolve();
});
readableStream.on("error", (reason) => {
this._error(reason);
});
if (!this._isStreamingSupported && this._isRangeSupported) {
this._error(new AbortException("streaming is disabled"));
}
if (this._storedError) {
this._readableStream.destroy(this._storedError);
}
}
};
PDFNodeStreamFsRangeReader = class {
constructor(stream2, start, end) {
this._url = stream2.url;
this._done = false;
this._storedError = null;
this.onProgress = null;
this._loaded = 0;
this._readableStream = null;
this._readCapability = Promise.withResolvers();
const source = stream2.source;
this._isStreamingSupported = !source.disableStream;
const fs = process.getBuiltinModule("fs");
this._setReadableStream(fs.createReadStream(this._url, {
start,
end: end - 1
}));
}
get isStreamingSupported() {
return this._isStreamingSupported;
}
async read() {
await this._readCapability.promise;
if (this._done) {
return {
value: void 0,
done: true
};
}
if (this._storedError) {
throw this._storedError;
}
const chunk = this._readableStream.read();
if (chunk === null) {
this._readCapability = Promise.withResolvers();
return this.read();
}
this._loaded += chunk.length;
this.onProgress?.({
loaded: this._loaded
});
const buffer = new Uint8Array(chunk).buffer;
return {
value: buffer,
done: false
};
}
cancel(reason) {
if (!this._readableStream) {
this._error(reason);
return;
}
this._readableStream.destroy(reason);
}
_error(reason) {
this._storedError = reason;
this._readCapability.resolve();
}
_setReadableStream(readableStream) {
this._readableStream = readableStream;
readableStream.on("readable", () => {
this._readCapability.resolve();
});
readableStream.on("end", () => {
readableStream.destroy();
this._done = true;
this._readCapability.resolve();
});
readableStream.on("error", (reason) => {
this._error(reason);
});
if (this._storedError) {
this._readableStream.destroy(this._storedError);
}
}
};
INITIAL_DATA = Symbol("INITIAL_DATA");
PDFObjects = class {
#objs = /* @__PURE__ */ Object.create(null);
#ensureObj(objId) {
return this.#objs[objId] ||= {
...Promise.withResolvers(),
data: INITIAL_DATA
};
}
get(objId, callback2 = null) {
if (callback2) {
const obj2 = this.#ensureObj(objId);
obj2.promise.then(() => callback2(obj2.data));
return null;
}
const obj = this.#objs[objId];
if (!obj || obj.data === INITIAL_DATA) {
throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
}
return obj.data;
}
has(objId) {
const obj = this.#objs[objId];
return !!obj && obj.data !== INITIAL_DATA;
}
delete(objId) {
const obj = this.#objs[objId];
if (!obj || obj.data === INITIAL_DATA) {
return false;
}
delete this.#objs[objId];
return true;
}
resolve(objId, data = null) {
const obj = this.#ensureObj(objId);
obj.data = data;
obj.resolve();
}
clear() {
for (const objId in this.#objs) {
const {
data
} = this.#objs[objId];
data?.bitmap?.close();
}
this.#objs = /* @__PURE__ */ Object.create(null);
}
*[Symbol.iterator]() {
for (const objId in this.#objs) {
const {
data
} = this.#objs[objId];
if (data === INITIAL_DATA) {
continue;
}
yield [objId, data];
}
}
};
MAX_TEXT_DIVS_TO_RENDER = 1e5;
DEFAULT_FONT_SIZE = 30;
TextLayer = class _TextLayer {
#capability = Promise.withResolvers();
#container = null;
#disableProcessItems = false;
#fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
#lang = null;
#layoutTextParams = null;
#pageHeight = 0;
#pageWidth = 0;
#reader = null;
#rootContainer = null;
#rotation = 0;
#scale = 0;
#styleCache = /* @__PURE__ */ Object.create(null);
#textContentItemsStr = [];
#textContentSource = null;
#textDivs = [];
#textDivProperties = /* @__PURE__ */ new WeakMap();
#transform = null;
static #ascentCache = /* @__PURE__ */ new Map();
static #canvasContexts = /* @__PURE__ */ new Map();
static #canvasCtxFonts = /* @__PURE__ */ new WeakMap();
static #minFontSize = null;
static #pendingTextLayers = /* @__PURE__ */ new Set();
constructor({
textContentSource,
container,
viewport
}) {
if (textContentSource instanceof ReadableStream) {
this.#textContentSource = textContentSource;
} else if (typeof textContentSource === "object") {
this.#textContentSource = new ReadableStream({
start(controller) {
controller.enqueue(textContentSource);
controller.close();
}
});
} else {
throw new Error('No "textContentSource" parameter specified.');
}
this.#container = this.#rootContainer = container;
this.#scale = viewport.scale * OutputScale.pixelRatio;
this.#rotation = viewport.rotation;
this.#layoutTextParams = {
div: null,
properties: null,
ctx: null
};
const {
pageWidth,
pageHeight,
pageX,
pageY
} = viewport.rawDims;
this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
this.#pageWidth = pageWidth;
this.#pageHeight = pageHeight;
_TextLayer.#ensureMinFontSizeComputed();
setLayerDimensions(container, viewport);
this.#capability.promise.finally(() => {
_TextLayer.#pendingTextLayers.delete(this);
this.#layoutTextParams = null;
this.#styleCache = null;
}).catch(() => {
});
}
static get fontFamilyMap() {
const {
isWindows,
isFirefox
} = util_FeatureTest.platform;
return shadow(this, "fontFamilyMap", /* @__PURE__ */ new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]]));
}
render() {
const pump = () => {
this.#reader.read().then(({
value,
done
}) => {
if (done) {
this.#capability.resolve();
return;
}
this.#lang ??= value.lang;
Object.assign(this.#styleCache, value.styles);
this.#processItems(value.items);
pump();
}, this.#capability.reject);
};
this.#reader = this.#textContentSource.getReader();
_TextLayer.#pendingTextLayers.add(this);
pump();
return this.#capability.promise;
}
update({
viewport,
onBefore = null
}) {
const scale = viewport.scale * OutputScale.pixelRatio;
const rotation = viewport.rotation;
if (rotation !== this.#rotation) {
onBefore?.();
this.#rotation = rotation;
setLayerDimensions(this.#rootContainer, {
rotation
});
}
if (scale !== this.#scale) {
onBefore?.();
this.#scale = scale;
const params = {
div: null,
properties: null,
ctx: _TextLayer.#getCtx(this.#lang)
};
for (const div of this.#textDivs) {
params.properties = this.#textDivProperties.get(div);
params.div = div;
this.#layout(params);
}
}
}
cancel() {
const abortEx = new AbortException("TextLayer task cancelled.");
this.#reader?.cancel(abortEx).catch(() => {
});
this.#reader = null;
this.#capability.reject(abortEx);
}
get textDivs() {
return this.#textDivs;
}
get textContentItemsStr() {
return this.#textContentItemsStr;
}
#processItems(items) {
if (this.#disableProcessItems) {
return;
}
this.#layoutTextParams.ctx ??= _TextLayer.#getCtx(this.#lang);
const textDivs = this.#textDivs, textContentItemsStr = this.#textContentItemsStr;
for (const item of items) {
if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {
warn("Ignoring additional textDivs for performance reasons.");
this.#disableProcessItems = true;
return;
}
if (item.str === void 0) {
if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
const parent = this.#container;
this.#container = document.createElement("span");
this.#container.classList.add("markedContent");
if (item.id) {
this.#container.setAttribute("id", `${item.id}`);
}
parent.append(this.#container);
} else if (item.type === "endMarkedContent") {
this.#container = this.#container.parentNode;
}
continue;
}
textContentItemsStr.push(item.str);
this.#appendText(item);
}
}
#appendText(geom) {
const textDiv = document.createElement("span");
const textDivProperties = {
angle: 0,
canvasWidth: 0,
hasText: geom.str !== "",
hasEOL: geom.hasEOL,
fontSize: 0
};
this.#textDivs.push(textDiv);
const tx = Util.transform(this.#transform, geom.transform);
let angle = Math.atan2(tx[1], tx[0]);
const style = this.#styleCache[geom.fontName];
if (style.vertical) {
angle += Math.PI / 2;
}
let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily;
fontFamily = _TextLayer.fontFamilyMap.get(fontFamily) || fontFamily;
const fontHeight = Math.hypot(tx[2], tx[3]);
const fontAscent = fontHeight * _TextLayer.#getAscent(fontFamily, style, this.#lang);
let left, top;
if (angle === 0) {
left = tx[4];
top = tx[5] - fontAscent;
} else {
left = tx[4] + fontAscent * Math.sin(angle);
top = tx[5] - fontAscent * Math.cos(angle);
}
const scaleFactorStr = "calc(var(--total-scale-factor) *";
const divStyle = textDiv.style;
if (this.#container === this.#rootContainer) {
divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`;
divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`;
} else {
divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
}
divStyle.fontSize = `${scaleFactorStr}${(_TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`;
divStyle.fontFamily = fontFamily;
textDivProperties.fontSize = fontHeight;
textDiv.setAttribute("role", "presentation");
textDiv.textContent = geom.str;
textDiv.dir = geom.dir;
if (this.#fontInspectorEnabled) {
textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName;
}
if (angle !== 0) {
textDivProperties.angle = angle * (180 / Math.PI);
}
let shouldScaleText = false;
if (geom.str.length > 1) {
shouldScaleText = true;
} else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
const absScaleX = Math.abs(geom.transform[0]), absScaleY = Math.abs(geom.transform[3]);
if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
shouldScaleText = true;
}
}
if (shouldScaleText) {
textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
}
this.#textDivProperties.set(textDiv, textDivProperties);
this.#layoutTextParams.div = textDiv;
this.#layoutTextParams.properties = textDivProperties;
this.#layout(this.#layoutTextParams);
if (textDivProperties.hasText) {
this.#container.append(textDiv);
}
if (textDivProperties.hasEOL) {
const br = document.createElement("br");
br.setAttribute("role", "presentation");
this.#container.append(br);
}
}
#layout(params) {
const {
div,
properties,
ctx
} = params;
const {
style
} = div;
let transform = "";
if (_TextLayer.#minFontSize > 1) {
transform = `scale(${1 / _TextLayer.#minFontSize})`;
}
if (properties.canvasWidth !== 0 && properties.hasText) {
const {
fontFamily
} = style;
const {
canvasWidth,
fontSize
} = properties;
_TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily);
const {
width
} = ctx.measureText(div.textContent);
if (width > 0) {
transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`;
}
}
if (properties.angle !== 0) {
transform = `rotate(${properties.angle}deg) ${transform}`;
}
if (transform.length > 0) {
style.transform = transform;
}
}
static cleanup() {
if (this.#pendingTextLayers.size > 0) {
return;
}
this.#ascentCache.clear();
for (const {
canvas
} of this.#canvasContexts.values()) {
canvas.remove();
}
this.#canvasContexts.clear();
}
static #getCtx(lang = null) {
let ctx = this.#canvasContexts.get(lang ||= "");
if (!ctx) {
const canvas = document.createElement("canvas");
canvas.className = "hiddenCanvasElement";
canvas.lang = lang;
document.body.append(canvas);
ctx = canvas.getContext("2d", {
alpha: false,
willReadFrequently: true
});
this.#canvasContexts.set(lang, ctx);
this.#canvasCtxFonts.set(ctx, {
size: 0,
family: ""
});
}
return ctx;
}
static #ensureCtxFont(ctx, size, family) {
const cached = this.#canvasCtxFonts.get(ctx);
if (size === cached.size && family === cached.family) {
return;
}
ctx.font = `${size}px ${family}`;
cached.size = size;
cached.family = family;
}
static #ensureMinFontSizeComputed() {
if (this.#minFontSize !== null) {
return;
}
const div = document.createElement("div");
div.style.opacity = 0;
div.style.lineHeight = 1;
div.style.fontSize = "1px";
div.style.position = "absolute";
div.textContent = "X";
document.body.append(div);
this.#minFontSize = div.getBoundingClientRect().height;
div.remove();
}
static #getAscent(fontFamily, style, lang) {
const cachedAscent = this.#ascentCache.get(fontFamily);
if (cachedAscent) {
return cachedAscent;
}
const ctx = this.#getCtx(lang);
ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;
this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily);
const metrics = ctx.measureText("");
const ascent = metrics.fontBoundingBoxAscent;
const descent = Math.abs(metrics.fontBoundingBoxDescent);
ctx.canvas.width = ctx.canvas.height = 0;
let ratio = 0.8;
if (ascent) {
ratio = ascent / (ascent + descent);
} else {
if (util_FeatureTest.platform.isFirefox) {
warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering.");
}
if (style.ascent) {
ratio = style.ascent;
} else if (style.descent) {
ratio = 1 + style.descent;
}
}
this.#ascentCache.set(fontFamily, ratio);
return ratio;
}
};
RENDERING_CANCELLED_TIMEOUT = 100;
PDFDocumentLoadingTask = class _PDFDocumentLoadingTask {
static #docId = 0;
_capability = Promise.withResolvers();
_transport = null;
_worker = null;
docId = `d${_PDFDocumentLoadingTask.#docId++}`;
destroyed = false;
onPassword = null;
onProgress = null;
get promise() {
return this._capability.promise;
}
async destroy() {
this.destroyed = true;
try {
if (this._worker?.port) {
this._worker._pendingDestroy = true;
}
await this._transport?.destroy();
} catch (ex) {
if (this._worker?.port) {
delete this._worker._pendingDestroy;
}
throw ex;
}
this._transport = null;
this._worker?.destroy();
this._worker = null;
}
async getData() {
return this._transport.getData();
}
};
PDFDataRangeTransport = class {
#capability = Promise.withResolvers();
#progressiveDoneListeners = [];
#progressiveReadListeners = [];
#progressListeners = [];
#rangeListeners = [];
constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
this.length = length;
this.initialData = initialData;
this.progressiveDone = progressiveDone;
this.contentDispositionFilename = contentDispositionFilename;
}
addRangeListener(listener) {
this.#rangeListeners.push(listener);
}
addProgressListener(listener) {
this.#progressListeners.push(listener);
}
addProgressiveReadListener(listener) {
this.#progressiveReadListeners.push(listener);
}
addProgressiveDoneListener(listener) {
this.#progressiveDoneListeners.push(listener);
}
onDataRange(begin, chunk) {
for (const listener of this.#rangeListeners) {
listener(begin, chunk);
}
}
onDataProgress(loaded, total) {
this.#capability.promise.then(() => {
for (const listener of this.#progressListeners) {
listener(loaded, total);
}
});
}
onDataProgressiveRead(chunk) {
this.#capability.promise.then(() => {
for (const listener of this.#progressiveReadListeners) {
listener(chunk);
}
});
}
onDataProgressiveDone() {
this.#capability.promise.then(() => {
for (const listener of this.#progressiveDoneListeners) {
listener();
}
});
}
transportReady() {
this.#capability.resolve();
}
requestDataRange(begin, end) {
unreachable("Abstract method PDFDataRangeTransport.requestDataRange");
}
abort() {
}
};
PDFDocumentProxy = class {
constructor(pdfInfo, transport) {
this._pdfInfo = pdfInfo;
this._transport = transport;
}
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 shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
}
get allXfaHtml() {
return this._transport._htmlForXfa;
}
getPage(pageNumber) {
return this._transport.getPage(pageNumber);
}
getPageIndex(ref) {
return this._transport.getPageIndex(ref);
}
getDestinations() {
return this._transport.getDestinations();
}
getDestination(id) {
return this._transport.getDestination(id);
}
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();
}
getAnnotationsByType(types2, pageIndexesToSkip) {
return this._transport.getAnnotationsByType(types2, pageIndexesToSkip);
}
getJSActions() {
return this._transport.getDocJSActions();
}
getOutline() {
return this._transport.getOutline();
}
getOptionalContentConfig({
intent = "display"
} = {}) {
const {
renderingIntent
} = this._transport.getRenderingIntent(intent);
return this._transport.getOptionalContentConfig(renderingIntent);
}
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();
}
getDownloadInfo() {
return this._transport.downloadInfoCapability.promise;
}
cleanup(keepLoadedFonts = false) {
return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
}
destroy() {
return this.loadingTask.destroy();
}
cachedPageNumber(ref) {
return this._transport.cachedPageNumber(ref);
}
get loadingParams() {
return this._transport.loadingParams;
}
get loadingTask() {
return this._transport.loadingTask;
}
getFieldObjects() {
return this._transport.getFieldObjects();
}
hasJSActions() {
return this._transport.hasJSActions();
}
getCalculationOrderIds() {
return this._transport.getCalculationOrderIds();
}
};
PDFPageProxy = class {
#pendingCleanup = false;
constructor(pageIndex, pageInfo, transport, pdfBug = false) {
this._pageIndex = pageIndex;
this._pageInfo = pageInfo;
this._transport = transport;
this._stats = pdfBug ? new StatTimer() : null;
this._pdfBug = pdfBug;
this.commonObjs = transport.commonObjs;
this.objs = new PDFObjects();
this._intentStates = /* @__PURE__ */ new Map();
this.destroyed = false;
this.recordedBBoxes = null;
}
get pageNumber() {
return this._pageIndex + 1;
}
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,
rotation = this.rotate,
offsetX = 0,
offsetY = 0,
dontFlip = false
} = {}) {
return new PageViewport({
viewBox: this.view,
userUnit: this.userUnit,
scale,
rotation,
offsetX,
offsetY,
dontFlip
});
}
getAnnotations({
intent = "display"
} = {}) {
const {
renderingIntent
} = this._transport.getRenderingIntent(intent);
return this._transport.getAnnotations(this._pageIndex, renderingIntent);
}
getJSActions() {
return this._transport.getPageJSActions(this._pageIndex);
}
get filterFactory() {
return this._transport.filterFactory;
}
get isPureXfa() {
return shadow(this, "isPureXfa", !!this._transport._htmlForXfa);
}
async getXfa() {
return this._transport._htmlForXfa?.children[this._pageIndex] || null;
}
render({
canvasContext,
canvas = canvasContext.canvas,
viewport,
intent = "display",
annotationMode = AnnotationMode.ENABLE,
transform = null,
background = null,
optionalContentConfigPromise = null,
annotationCanvasMap = null,
pageColors = null,
printAnnotationStorage = null,
isEditing = false,
recordOperations = false,
operationsFilter = null
}) {
this._stats?.time("Overall");
const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing);
const {
renderingIntent,
cacheKey
} = intentArgs;
this.#pendingCleanup = false;
optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent);
let intentState = this._intentStates.get(cacheKey);
if (!intentState) {
intentState = /* @__PURE__ */ Object.create(null);
this._intentStates.set(cacheKey, intentState);
}
if (intentState.streamReaderCancelTimeout) {
clearTimeout(intentState.streamReaderCancelTimeout);
intentState.streamReaderCancelTimeout = null;
}
const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);
if (!intentState.displayReadyCapability) {
intentState.displayReadyCapability = Promise.withResolvers();
intentState.operatorList = {
fnArray: [],
argsArray: [],
lastChunk: false,
separateAnnots: null
};
this._stats?.time("Page Request");
this._pumpOperatorList(intentArgs);
}
const recordForDebugger = Boolean(this._pdfBug && globalThis.StepperManager?.enabled);
const shouldRecordOperations = !this.recordedBBoxes && (recordOperations || recordForDebugger);
const complete2 = (error) => {
intentState.renderTasks.delete(internalRenderTask);
if (shouldRecordOperations) {
const recordedBBoxes = internalRenderTask.gfx?.dependencyTracker.take();
if (recordedBBoxes) {
if (internalRenderTask.stepper) {
internalRenderTask.stepper.setOperatorBBoxes(recordedBBoxes, internalRenderTask.gfx.dependencyTracker.takeDebugMetadata());
}
if (recordOperations) {
this.recordedBBoxes = recordedBBoxes;
}
}
}
if (intentPrint) {
this.#pendingCleanup = true;
}
this.#tryCleanup();
if (error) {
internalRenderTask.capability.reject(error);
this._abortOperatorList({
intentState,
reason: error instanceof Error ? error : new Error(error)
});
} else {
internalRenderTask.capability.resolve();
}
if (this._stats) {
this._stats.timeEnd("Rendering");
this._stats.timeEnd("Overall");
if (globalThis.Stats?.enabled) {
globalThis.Stats.add(this.pageNumber, this._stats);
}
}
};
const internalRenderTask = new InternalRenderTask({
callback: complete2,
params: {
canvas,
canvasContext,
dependencyTracker: shouldRecordOperations ? new CanvasDependencyTracker(canvas, intentState.operatorList.length, recordForDebugger) : null,
viewport,
transform,
background
},
objs: this.objs,
commonObjs: this.commonObjs,
annotationCanvasMap,
operatorList: intentState.operatorList,
pageIndex: this._pageIndex,
canvasFactory: this._transport.canvasFactory,
filterFactory: this._transport.filterFactory,
useRequestAnimationFrame: !intentPrint,
pdfBug: this._pdfBug,
pageColors,
enableHWA: this._transport.enableHWA,
operationsFilter
});
(intentState.renderTasks ||= /* @__PURE__ */ new Set()).add(internalRenderTask);
const renderTask = internalRenderTask.task;
Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
if (this.destroyed) {
complete2();
return;
}
this._stats?.time("Rendering");
if (!(optionalContentConfig.renderingIntent & renderingIntent)) {
throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");
}
internalRenderTask.initializeGraphics({
transparency,
optionalContentConfig
});
internalRenderTask.operatorListChanged();
}).catch(complete2);
return renderTask;
}
getOperatorList({
intent = "display",
annotationMode = AnnotationMode.ENABLE,
printAnnotationStorage = null,
isEditing = false
} = {}) {
function operatorListChanged() {
if (intentState.operatorList.lastChunk) {
intentState.opListReadCapability.resolve(intentState.operatorList);
intentState.renderTasks.delete(opListTask);
}
}
const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true);
let intentState = this._intentStates.get(intentArgs.cacheKey);
if (!intentState) {
intentState = /* @__PURE__ */ Object.create(null);
this._intentStates.set(intentArgs.cacheKey, intentState);
}
let opListTask;
if (!intentState.opListReadCapability) {
opListTask = /* @__PURE__ */ Object.create(null);
opListTask.operatorListChanged = operatorListChanged;
intentState.opListReadCapability = Promise.withResolvers();
(intentState.renderTasks ||= /* @__PURE__ */ new Set()).add(opListTask);
intentState.operatorList = {
fnArray: [],
argsArray: [],
lastChunk: false,
separateAnnots: null
};
this._stats?.time("Page Request");
this._pumpOperatorList(intentArgs);
}
return intentState.opListReadCapability.promise;
}
streamTextContent({
includeMarkedContent = false,
disableNormalization = false
} = {}) {
const TEXT_CONTENT_CHUNK_SIZE = 100;
return this._transport.messageHandler.sendWithStream("GetTextContent", {
pageIndex: this._pageIndex,
includeMarkedContent: includeMarkedContent === true,
disableNormalization: disableNormalization === true
}, {
highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
size(textContent) {
return textContent.items.length;
}
});
}
getTextContent(params = {}) {
if (this._transport._htmlForXfa) {
return this.getXfa().then((xfa) => XfaText.textContent(xfa));
}
const readableStream = this.streamTextContent(params);
return new Promise(function(resolve2, reject) {
function pump() {
reader.read().then(function({
value,
done
}) {
if (done) {
resolve2(textContent);
return;
}
textContent.lang ??= value.lang;
Object.assign(textContent.styles, value.styles);
textContent.items.push(...value.items);
pump();
}, reject);
}
const reader = readableStream.getReader();
const textContent = {
items: [],
styles: /* @__PURE__ */ Object.create(null),
lang: null
};
pump();
});
}
getStructTree() {
return this._transport.getStructTree(this._pageIndex);
}
_destroy() {
this.destroyed = true;
const waitOn = [];
for (const intentState of this._intentStates.values()) {
this._abortOperatorList({
intentState,
reason: new Error("Page was destroyed."),
force: true
});
if (intentState.opListReadCapability) {
continue;
}
for (const internalRenderTask of intentState.renderTasks) {
waitOn.push(internalRenderTask.completed);
internalRenderTask.cancel();
}
}
this.objs.clear();
this.#pendingCleanup = false;
return Promise.all(waitOn);
}
cleanup(resetStats = false) {
this.#pendingCleanup = true;
const success = this.#tryCleanup();
if (resetStats && success) {
this._stats &&= new StatTimer();
}
return success;
}
#tryCleanup() {
if (!this.#pendingCleanup || this.destroyed) {
return false;
}
for (const {
renderTasks,
operatorList
} of this._intentStates.values()) {
if (renderTasks.size > 0 || !operatorList.lastChunk) {
return false;
}
}
this._intentStates.clear();
this.objs.clear();
this.#pendingCleanup = false;
return true;
}
_startRenderPage(transparency, cacheKey) {
const intentState = this._intentStates.get(cacheKey);
if (!intentState) {
return;
}
this._stats?.timeEnd("Page Request");
intentState.displayReadyCapability?.resolve(transparency);
}
_renderPageChunk(operatorListChunk, intentState) {
for (let i7 = 0, ii = operatorListChunk.length; i7 < ii; i7++) {
intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i7]);
intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i7]);
}
intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
for (const internalRenderTask of intentState.renderTasks) {
internalRenderTask.operatorListChanged();
}
if (operatorListChunk.lastChunk) {
this.#tryCleanup();
}
}
_pumpOperatorList({
renderingIntent,
cacheKey,
annotationStorageSerializable,
modifiedIds
}) {
const {
map: map3,
transfer
} = annotationStorageSerializable;
const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
pageIndex: this._pageIndex,
intent: renderingIntent,
cacheKey,
annotationStorage: map3,
modifiedIds
}, transfer);
const reader = readableStream.getReader();
const intentState = this._intentStates.get(cacheKey);
intentState.streamReader = reader;
const pump = () => {
reader.read().then(({
value,
done
}) => {
if (done) {
intentState.streamReader = null;
return;
}
if (this._transport.destroyed) {
return;
}
this._renderPageChunk(value, intentState);
pump();
}, (reason) => {
intentState.streamReader = null;
if (this._transport.destroyed) {
return;
}
if (intentState.operatorList) {
intentState.operatorList.lastChunk = true;
for (const internalRenderTask of intentState.renderTasks) {
internalRenderTask.operatorListChanged();
}
this.#tryCleanup();
}
if (intentState.displayReadyCapability) {
intentState.displayReadyCapability.reject(reason);
} else if (intentState.opListReadCapability) {
intentState.opListReadCapability.reject(reason);
} else {
throw reason;
}
});
};
pump();
}
_abortOperatorList({
intentState,
reason,
force = false
}) {
if (!intentState.streamReader) {
return;
}
if (intentState.streamReaderCancelTimeout) {
clearTimeout(intentState.streamReaderCancelTimeout);
intentState.streamReaderCancelTimeout = null;
}
if (!force) {
if (intentState.renderTasks.size > 0) {
return;
}
if (reason instanceof RenderingCancelledException) {
let delay = RENDERING_CANCELLED_TIMEOUT;
if (reason.extraDelay > 0 && reason.extraDelay < 1e3) {
delay += reason.extraDelay;
}
intentState.streamReaderCancelTimeout = setTimeout(() => {
intentState.streamReaderCancelTimeout = null;
this._abortOperatorList({
intentState,
reason,
force: true
});
}, delay);
return;
}
}
intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {
});
intentState.streamReader = null;
if (this._transport.destroyed) {
return;
}
for (const [curCacheKey, curIntentState] of this._intentStates) {
if (curIntentState === intentState) {
this._intentStates.delete(curCacheKey);
break;
}
}
this.cleanup();
}
get stats() {
return this._stats;
}
};
PDFWorker = class _PDFWorker {
#capability = Promise.withResolvers();
#messageHandler = null;
#port = null;
#webWorker = null;
static #fakeWorkerId = 0;
static #isWorkerDisabled = false;
static #workerPorts = /* @__PURE__ */ new WeakMap();
static {
if (isNodeJS) {
this.#isWorkerDisabled = true;
GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs";
}
this._isSameOrigin = (baseUrl, otherUrl) => {
const base = URL.parse(baseUrl);
if (!base?.origin || base.origin === "null") {
return false;
}
const other = new URL(otherUrl, base);
return base.origin === other.origin;
};
this._createCDNWrapper = (url) => {
const wrapper = `await import("${url}");`;
return URL.createObjectURL(new Blob([wrapper], {
type: "text/javascript"
}));
};
this.fromPort = (params) => {
deprecated("`PDFWorker.fromPort` - please use `PDFWorker.create` instead.");
if (!params?.port) {
throw new Error("PDFWorker.fromPort - invalid method signature.");
}
return this.create(params);
};
}
constructor({
name = null,
port: port2 = null,
verbosity: verbosity2 = getVerbosityLevel()
} = {}) {
this.name = name;
this.destroyed = false;
this.verbosity = verbosity2;
if (port2) {
if (_PDFWorker.#workerPorts.has(port2)) {
throw new Error("Cannot use more than one PDFWorker per port.");
}
_PDFWorker.#workerPorts.set(port2, this);
this.#initializeFromPort(port2);
} else {
this.#initialize();
}
}
get promise() {
return this.#capability.promise;
}
#resolve() {
this.#capability.resolve();
this.#messageHandler.send("configure", {
verbosity: this.verbosity
});
}
get port() {
return this.#port;
}
get messageHandler() {
return this.#messageHandler;
}
#initializeFromPort(port2) {
this.#port = port2;
this.#messageHandler = new MessageHandler("main", "worker", port2);
this.#messageHandler.on("ready", () => {
});
this.#resolve();
}
#initialize() {
if (_PDFWorker.#isWorkerDisabled || _PDFWorker.#mainThreadWorkerMessageHandler) {
this.#setupFakeWorker();
return;
}
let {
workerSrc
} = _PDFWorker;
try {
if (!_PDFWorker._isSameOrigin(window.location, workerSrc)) {
workerSrc = _PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href);
}
const worker = new Worker(workerSrc, {
type: "module"
});
const messageHandler = new MessageHandler("main", "worker", worker);
const terminateEarly = () => {
ac.abort();
messageHandler.destroy();
worker.terminate();
if (this.destroyed) {
this.#capability.reject(new Error("Worker was destroyed"));
} else {
this.#setupFakeWorker();
}
};
const ac = new AbortController();
worker.addEventListener("error", () => {
if (!this.#webWorker) {
terminateEarly();
}
}, {
signal: ac.signal
});
messageHandler.on("test", (data) => {
ac.abort();
if (this.destroyed || !data) {
terminateEarly();
return;
}
this.#messageHandler = messageHandler;
this.#port = worker;
this.#webWorker = worker;
this.#resolve();
});
messageHandler.on("ready", (data) => {
ac.abort();
if (this.destroyed) {
terminateEarly();
return;
}
try {
sendTest();
} catch {
this.#setupFakeWorker();
}
});
const sendTest = () => {
const testObj = new Uint8Array();
messageHandler.send("test", testObj, [testObj.buffer]);
};
sendTest();
return;
} catch {
info("The worker has been disabled.");
}
this.#setupFakeWorker();
}
#setupFakeWorker() {
if (!_PDFWorker.#isWorkerDisabled) {
warn("Setting up fake worker.");
_PDFWorker.#isWorkerDisabled = true;
}
_PDFWorker._setupFakeWorkerGlobal.then((WorkerMessageHandler) => {
if (this.destroyed) {
this.#capability.reject(new Error("Worker was destroyed"));
return;
}
const port2 = new LoopbackPort();
this.#port = port2;
const id = `fake${_PDFWorker.#fakeWorkerId++}`;
const workerHandler = new MessageHandler(id + "_worker", id, port2);
WorkerMessageHandler.setup(workerHandler, port2);
this.#messageHandler = new MessageHandler(id, id + "_worker", port2);
this.#resolve();
}).catch((reason) => {
this.#capability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
});
}
destroy() {
this.destroyed = true;
this.#webWorker?.terminate();
this.#webWorker = null;
_PDFWorker.#workerPorts.delete(this.#port);
this.#port = null;
this.#messageHandler?.destroy();
this.#messageHandler = null;
}
static create(params) {
const cachedPort = this.#workerPorts.get(params?.port);
if (cachedPort) {
if (cachedPort._pendingDestroy) {
throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");
}
return cachedPort;
}
return new _PDFWorker(params);
}
static get workerSrc() {
if (GlobalWorkerOptions.workerSrc) {
return GlobalWorkerOptions.workerSrc;
}
throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
}
static get #mainThreadWorkerMessageHandler() {
try {
return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
} catch {
return null;
}
}
static get _setupFakeWorkerGlobal() {
const loader = async () => {
if (this.#mainThreadWorkerMessageHandler) {
return this.#mainThreadWorkerMessageHandler;
}
const worker = await import(
/*webpackIgnore: true*/
/*@vite-ignore*/
this.workerSrc
);
return worker.WorkerMessageHandler;
};
return shadow(this, "_setupFakeWorkerGlobal", loader());
}
};
WorkerTransport = class {
#methodPromises = /* @__PURE__ */ new Map();
#pageCache = /* @__PURE__ */ new Map();
#pagePromises = /* @__PURE__ */ new Map();
#pageRefCache = /* @__PURE__ */ new Map();
#passwordCapability = null;
constructor(messageHandler, loadingTask, networkStream, params, factory, enableHWA) {
this.messageHandler = messageHandler;
this.loadingTask = loadingTask;
this.commonObjs = new PDFObjects();
this.fontLoader = new FontLoader({
ownerDocument: params.ownerDocument,
styleElement: params.styleElement
});
this.loadingParams = params.loadingParams;
this._params = params;
this.canvasFactory = factory.canvasFactory;
this.filterFactory = factory.filterFactory;
this.cMapReaderFactory = factory.cMapReaderFactory;
this.standardFontDataFactory = factory.standardFontDataFactory;
this.wasmFactory = factory.wasmFactory;
this.destroyed = false;
this.destroyCapability = null;
this._networkStream = networkStream;
this._fullReader = null;
this._lastProgress = null;
this.downloadInfoCapability = Promise.withResolvers();
this.enableHWA = enableHWA;
this.setupMessageHandler();
}
#cacheSimpleMethod(name, data = null) {
const cachedPromise = this.#methodPromises.get(name);
if (cachedPromise) {
return cachedPromise;
}
const promise = this.messageHandler.sendWithPromise(name, data);
this.#methodPromises.set(name, promise);
return promise;
}
get annotationStorage() {
return shadow(this, "annotationStorage", new AnnotationStorage());
}
getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) {
let renderingIntent = RenderingIntentFlag.DISPLAY;
let annotationStorageSerializable = SerializableEmpty;
switch (intent) {
case "any":
renderingIntent = RenderingIntentFlag.ANY;
break;
case "display":
break;
case "print":
renderingIntent = RenderingIntentFlag.PRINT;
break;
default:
warn(`getRenderingIntent - invalid intent: ${intent}`);
}
const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
switch (annotationMode) {
case AnnotationMode.DISABLE:
renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE;
break;
case AnnotationMode.ENABLE:
break;
case AnnotationMode.ENABLE_FORMS:
renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS;
break;
case AnnotationMode.ENABLE_STORAGE:
renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE;
annotationStorageSerializable = annotationStorage.serializable;
break;
default:
warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
}
if (isEditing) {
renderingIntent += RenderingIntentFlag.IS_EDITING;
}
if (isOpList) {
renderingIntent += RenderingIntentFlag.OPLIST;
}
const {
ids: modifiedIds,
hash: modifiedIdsHash
} = annotationStorage.modifiedIds;
const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash];
return {
renderingIntent,
cacheKey: cacheKeyBuf.join("_"),
annotationStorageSerializable,
modifiedIds
};
}
destroy() {
if (this.destroyCapability) {
return this.destroyCapability.promise;
}
this.destroyed = true;
this.destroyCapability = Promise.withResolvers();
this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback"));
const waitOn = [];
for (const page of this.#pageCache.values()) {
waitOn.push(page._destroy());
}
this.#pageCache.clear();
this.#pagePromises.clear();
this.#pageRefCache.clear();
if (this.hasOwnProperty("annotationStorage")) {
this.annotationStorage.resetModified();
}
const terminated = this.messageHandler.sendWithPromise("Terminate", null);
waitOn.push(terminated);
Promise.all(waitOn).then(() => {
this.commonObjs.clear();
this.fontLoader.clear();
this.#methodPromises.clear();
this.filterFactory.destroy();
TextLayer.cleanup();
this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));
this.messageHandler?.destroy();
this.messageHandler = null;
this.destroyCapability.resolve();
}, this.destroyCapability.reject);
return this.destroyCapability.promise;
}
setupMessageHandler() {
const {
messageHandler,
loadingTask
} = this;
messageHandler.on("GetReader", (data, sink) => {
assert(this._networkStream, "GetReader - no `IPDFStream` instance available.");
this._fullReader = this._networkStream.getFullReader();
this._fullReader.onProgress = (evt) => {
this._lastProgress = {
loaded: evt.loaded,
total: evt.total
};
};
sink.onPull = () => {
this._fullReader.read().then(function({
value,
done
}) {
if (done) {
sink.close();
return;
}
assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
sink.enqueue(new Uint8Array(value), 1, [value]);
}).catch((reason) => {
sink.error(reason);
});
};
sink.onCancel = (reason) => {
this._fullReader.cancel(reason);
sink.ready.catch((readyReason) => {
if (this.destroyed) {
return;
}
throw readyReason;
});
};
});
messageHandler.on("ReaderHeadersReady", async (data) => {
await this._fullReader.headersReady;
const {
isStreamingSupported,
isRangeSupported,
contentLength
} = this._fullReader;
if (!isStreamingSupported || !isRangeSupported) {
if (this._lastProgress) {
loadingTask.onProgress?.(this._lastProgress);
}
this._fullReader.onProgress = (evt) => {
loadingTask.onProgress?.({
loaded: evt.loaded,
total: evt.total
});
};
}
return {
isStreamingSupported,
isRangeSupported,
contentLength
};
});
messageHandler.on("GetRangeReader", (data, sink) => {
assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
if (!rangeReader) {
sink.close();
return;
}
sink.onPull = () => {
rangeReader.read().then(function({
value,
done
}) {
if (done) {
sink.close();
return;
}
assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
sink.enqueue(new Uint8Array(value), 1, [value]);
}).catch((reason) => {
sink.error(reason);
});
};
sink.onCancel = (reason) => {
rangeReader.cancel(reason);
sink.ready.catch((readyReason) => {
if (this.destroyed) {
return;
}
throw readyReason;
});
};
});
messageHandler.on("GetDoc", ({
pdfInfo
}) => {
this._numPages = pdfInfo.numPages;
this._htmlForXfa = pdfInfo.htmlForXfa;
delete pdfInfo.htmlForXfa;
loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
});
messageHandler.on("DocException", (ex) => {
loadingTask._capability.reject(wrapReason(ex));
});
messageHandler.on("PasswordRequest", (ex) => {
this.#passwordCapability = Promise.withResolvers();
try {
if (!loadingTask.onPassword) {
throw wrapReason(ex);
}
const updatePassword = (password) => {
if (password instanceof Error) {
this.#passwordCapability.reject(password);
} else {
this.#passwordCapability.resolve({
password
});
}
};
loadingTask.onPassword(updatePassword, ex.code);
} catch (err) {
this.#passwordCapability.reject(err);
}
return this.#passwordCapability.promise;
});
messageHandler.on("DataLoaded", (data) => {
loadingTask.onProgress?.({
loaded: data.length,
total: data.length
});
this.downloadInfoCapability.resolve(data);
});
messageHandler.on("StartRenderPage", (data) => {
if (this.destroyed) {
return;
}
const page = this.#pageCache.get(data.pageIndex);
page._startRenderPage(data.transparency, data.cacheKey);
});
messageHandler.on("commonobj", ([id, type, exportedData]) => {
if (this.destroyed) {
return null;
}
if (this.commonObjs.has(id)) {
return null;
}
switch (type) {
case "Font":
if ("error" in exportedData) {
const exportedError = exportedData.error;
warn(`Error during font loading: ${exportedError}`);
this.commonObjs.resolve(id, exportedError);
break;
}
const fontData = new FontInfo(exportedData);
const inspectFont = this._params.pdfBug && globalThis.FontInspector?.enabled ? (font2, url) => globalThis.FontInspector.fontAdded(font2, url) : null;
const font = new FontFaceObject(fontData, inspectFont, exportedData.extra, exportedData.charProcOperatorList);
this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", {
id
})).finally(() => {
if (!font.fontExtraProperties && font.data) {
font.clearData();
}
this.commonObjs.resolve(id, font);
});
break;
case "CopyLocalImage":
const {
imageRef
} = exportedData;
assert(imageRef, "The imageRef must be defined.");
for (const pageProxy of this.#pageCache.values()) {
for (const [, data] of pageProxy.objs) {
if (data?.ref !== imageRef) {
continue;
}
if (!data.dataLen) {
return null;
}
this.commonObjs.resolve(id, structuredClone(data));
return data.dataLen;
}
}
break;
case "FontPath":
case "Image":
this.commonObjs.resolve(id, exportedData);
break;
case "Pattern":
const pattern = new PatternInfo(exportedData);
this.commonObjs.resolve(id, pattern.getIR());
break;
default:
throw new Error(`Got unknown common object type ${type}`);
}
return null;
});
messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
if (this.destroyed) {
return;
}
const pageProxy = this.#pageCache.get(pageIndex);
if (pageProxy.objs.has(id)) {
return;
}
if (pageProxy._intentStates.size === 0) {
imageData?.bitmap?.close();
return;
}
switch (type) {
case "Image":
case "Pattern":
pageProxy.objs.resolve(id, imageData);
break;
default:
throw new Error(`Got unknown object type ${type}`);
}
});
messageHandler.on("DocProgress", (data) => {
if (this.destroyed) {
return;
}
loadingTask.onProgress?.({
loaded: data.loaded,
total: data.total
});
});
messageHandler.on("FetchBinaryData", async (data) => {
if (this.destroyed) {
throw new Error("Worker was destroyed.");
}
const factory = this[data.type];
if (!factory) {
throw new Error(`${data.type} not initialized, see the \`useWorkerFetch\` parameter.`);
}
return factory.fetch(data);
});
}
getData() {
return this.messageHandler.sendWithPromise("GetData", null);
}
saveDocument() {
if (this.annotationStorage.size <= 0) {
warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");
}
const {
map: map3,
transfer
} = this.annotationStorage.serializable;
return this.messageHandler.sendWithPromise("SaveDocument", {
isPureXfa: !!this._htmlForXfa,
numPages: this._numPages,
annotationStorage: map3,
filename: this._fullReader?.filename ?? null
}, transfer).finally(() => {
this.annotationStorage.resetModified();
});
}
getPage(pageNumber) {
if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
return Promise.reject(new Error("Invalid page request."));
}
const pageIndex = pageNumber - 1, cachedPromise = this.#pagePromises.get(pageIndex);
if (cachedPromise) {
return cachedPromise;
}
const promise = this.messageHandler.sendWithPromise("GetPage", {
pageIndex
}).then((pageInfo) => {
if (this.destroyed) {
throw new Error("Transport destroyed");
}
if (pageInfo.refStr) {
this.#pageRefCache.set(pageInfo.refStr, pageNumber);
}
const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
this.#pageCache.set(pageIndex, page);
return page;
});
this.#pagePromises.set(pageIndex, promise);
return promise;
}
getPageIndex(ref) {
if (!isRefProxy(ref)) {
return Promise.reject(new Error("Invalid pageIndex request."));
}
return this.messageHandler.sendWithPromise("GetPageIndex", {
num: ref.num,
gen: ref.gen
});
}
getAnnotations(pageIndex, intent) {
return this.messageHandler.sendWithPromise("GetAnnotations", {
pageIndex,
intent
});
}
getFieldObjects() {
return this.#cacheSimpleMethod("GetFieldObjects");
}
hasJSActions() {
return this.#cacheSimpleMethod("HasJSActions");
}
getCalculationOrderIds() {
return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
}
getDestinations() {
return this.messageHandler.sendWithPromise("GetDestinations", null);
}
getDestination(id) {
if (typeof id !== "string") {
return Promise.reject(new Error("Invalid destination request."));
}
return this.messageHandler.sendWithPromise("GetDestination", {
id
});
}
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);
}
getAnnotationsByType(types2, pageIndexesToSkip) {
return this.messageHandler.sendWithPromise("GetAnnotationsByType", {
types: types2,
pageIndexesToSkip
});
}
getDocJSActions() {
return this.#cacheSimpleMethod("GetDocJSActions");
}
getPageJSActions(pageIndex) {
return this.messageHandler.sendWithPromise("GetPageJSActions", {
pageIndex
});
}
getStructTree(pageIndex) {
return this.messageHandler.sendWithPromise("GetStructTree", {
pageIndex
});
}
getOutline() {
return this.messageHandler.sendWithPromise("GetOutline", null);
}
getOptionalContentConfig(renderingIntent) {
return this.#cacheSimpleMethod("GetOptionalContentConfig").then((data) => new OptionalContentConfig(data, renderingIntent));
}
getPermissions() {
return this.messageHandler.sendWithPromise("GetPermissions", null);
}
getMetadata() {
const name = "GetMetadata", cachedPromise = this.#methodPromises.get(name);
if (cachedPromise) {
return cachedPromise;
}
const promise = this.messageHandler.sendWithPromise(name, null).then((results) => ({
info: results[0],
metadata: results[1] ? new Metadata(results[1]) : null,
contentDispositionFilename: this._fullReader?.filename ?? null,
contentLength: this._fullReader?.contentLength ?? null
}));
this.#methodPromises.set(name, promise);
return promise;
}
getMarkInfo() {
return this.messageHandler.sendWithPromise("GetMarkInfo", null);
}
async startCleanup(keepLoadedFonts = false) {
if (this.destroyed) {
return;
}
await this.messageHandler.sendWithPromise("Cleanup", null);
for (const page of this.#pageCache.values()) {
const cleanupSuccessful = page.cleanup();
if (!cleanupSuccessful) {
throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
}
}
this.commonObjs.clear();
if (!keepLoadedFonts) {
this.fontLoader.clear();
}
this.#methodPromises.clear();
this.filterFactory.destroy(true);
TextLayer.cleanup();
}
cachedPageNumber(ref) {
if (!isRefProxy(ref)) {
return null;
}
const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`;
return this.#pageRefCache.get(refStr) ?? null;
}
};
RenderTask = class {
#internalRenderTask = null;
onContinue = null;
onError = null;
constructor(internalRenderTask) {
this.#internalRenderTask = internalRenderTask;
}
get promise() {
return this.#internalRenderTask.capability.promise;
}
cancel(extraDelay = 0) {
this.#internalRenderTask.cancel(null, extraDelay);
}
get separateAnnots() {
const {
separateAnnots
} = this.#internalRenderTask.operatorList;
if (!separateAnnots) {
return false;
}
const {
annotationCanvasMap
} = this.#internalRenderTask;
return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
}
};
InternalRenderTask = class _InternalRenderTask {
#rAF = null;
static #canvasInUse = /* @__PURE__ */ new WeakSet();
constructor({
callback: callback2,
params,
objs,
commonObjs,
annotationCanvasMap,
operatorList,
pageIndex,
canvasFactory,
filterFactory,
useRequestAnimationFrame = false,
pdfBug = false,
pageColors = null,
enableHWA = false,
operationsFilter = null
}) {
this.callback = callback2;
this.params = params;
this.objs = objs;
this.commonObjs = commonObjs;
this.annotationCanvasMap = annotationCanvasMap;
this.operatorListIdx = null;
this.operatorList = operatorList;
this._pageIndex = pageIndex;
this.canvasFactory = canvasFactory;
this.filterFactory = filterFactory;
this._pdfBug = pdfBug;
this.pageColors = pageColors;
this.running = false;
this.graphicsReadyCallback = null;
this.graphicsReady = false;
this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
this.cancelled = false;
this.capability = Promise.withResolvers();
this.task = new RenderTask(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 = params.canvas;
this._canvasContext = params.canvas ? null : params.canvasContext;
this._enableHWA = enableHWA;
this._dependencyTracker = params.dependencyTracker;
this._operationsFilter = operationsFilter;
}
get completed() {
return this.capability.promise.catch(function() {
});
}
initializeGraphics({
transparency = false,
optionalContentConfig
}) {
if (this.cancelled) {
return;
}
if (this._canvas) {
if (_InternalRenderTask.#canvasInUse.has(this._canvas)) {
throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");
}
_InternalRenderTask.#canvasInUse.add(this._canvas);
}
if (this._pdfBug && globalThis.StepperManager?.enabled) {
this.stepper = globalThis.StepperManager.create(this._pageIndex);
this.stepper.init(this.operatorList);
this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
}
const {
viewport,
transform,
background,
dependencyTracker
} = this.params;
const canvasContext = this._canvasContext || this._canvas.getContext("2d", {
alpha: false,
willReadFrequently: !this._enableHWA
});
this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, {
optionalContentConfig
}, this.annotationCanvasMap, this.pageColors, dependencyTracker);
this.gfx.beginDrawing({
transform,
viewport,
transparency,
background
});
this.operatorListIdx = 0;
this.graphicsReady = true;
this.graphicsReadyCallback?.();
}
cancel(error = null, extraDelay = 0) {
this.running = false;
this.cancelled = true;
this.gfx?.endDrawing();
if (this.#rAF) {
window.cancelAnimationFrame(this.#rAF);
this.#rAF = null;
}
_InternalRenderTask.#canvasInUse.delete(this._canvas);
error ||= new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay);
this.callback(error);
this.task.onError?.(error);
}
operatorListChanged() {
if (!this.graphicsReady) {
this.graphicsReadyCallback ||= this._continueBound;
return;
}
this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length);
this.stepper?.updateOperatorList(this.operatorList);
if (this.running) {
return;
}
this._continue();
}
_continue() {
this.running = true;
if (this.cancelled) {
return;
}
if (this.task.onContinue) {
this.task.onContinue(this._scheduleNextBound);
} else {
this._scheduleNext();
}
}
_scheduleNext() {
if (this._useRequestAnimationFrame) {
this.#rAF = window.requestAnimationFrame(() => {
this.#rAF = null;
this._nextBound().catch(this._cancelBound);
});
} else {
Promise.resolve().then(this._nextBound).catch(this._cancelBound);
}
}
async _next() {
if (this.cancelled) {
return;
}
this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper, this._operationsFilter);
if (this.operatorListIdx === this.operatorList.argsArray.length) {
this.running = false;
if (this.operatorList.lastChunk) {
this.gfx.endDrawing();
_InternalRenderTask.#canvasInUse.delete(this._canvas);
this.callback();
}
}
}
};
version2 = "5.4.394";
build = "2cc809ade";
ColorPicker = class _ColorPicker {
#button = null;
#buttonSwatch = null;
#defaultColor;
#dropdown = null;
#dropdownWasFromKeyboard = false;
#isMainColorPicker = false;
#editor = null;
#eventBus;
#openDropdownAC = null;
#uiManager = null;
static #l10nColor = null;
static get _keyboardManager() {
return shadow(this, "_keyboardManager", new KeyboardManager([[["Escape", "mac+Escape"], _ColorPicker.prototype._hideDropdownFromKeyboard], [[" ", "mac+ "], _ColorPicker.prototype._colorSelectFromKeyboard], [["ArrowDown", "ArrowRight", "mac+ArrowDown", "mac+ArrowRight"], _ColorPicker.prototype._moveToNext], [["ArrowUp", "ArrowLeft", "mac+ArrowUp", "mac+ArrowLeft"], _ColorPicker.prototype._moveToPrevious], [["Home", "mac+Home"], _ColorPicker.prototype._moveToBeginning], [["End", "mac+End"], _ColorPicker.prototype._moveToEnd]]));
}
constructor({
editor = null,
uiManager = null
}) {
if (editor) {
this.#isMainColorPicker = false;
this.#editor = editor;
} else {
this.#isMainColorPicker = true;
}
this.#uiManager = editor?._uiManager || uiManager;
this.#eventBus = this.#uiManager._eventBus;
this.#defaultColor = editor?.color?.toUpperCase() || this.#uiManager?.highlightColors.values().next().value || "#FFFF98";
_ColorPicker.#l10nColor ||= 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() {
const button = this.#button = document.createElement("button");
button.className = "colorPicker";
button.tabIndex = "0";
button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button");
button.ariaHasPopup = "true";
if (this.#editor) {
button.ariaControls = `${this.#editor.id}_colorpicker_dropdown`;
}
const signal = this.#uiManager._signal;
button.addEventListener("click", this.#openDropdown.bind(this), {
signal
});
button.addEventListener("keydown", this.#keyDown.bind(this), {
signal
});
const swatch = this.#buttonSwatch = document.createElement("span");
swatch.className = "swatch";
swatch.ariaHidden = "true";
swatch.style.backgroundColor = this.#defaultColor;
button.append(swatch);
return button;
}
renderMainDropdown() {
const dropdown = this.#dropdown = this.#getDropdownRoot();
dropdown.ariaOrientation = "horizontal";
dropdown.ariaLabelledBy = "highlightColorPickerLabel";
return dropdown;
}
#getDropdownRoot() {
const div = document.createElement("div");
const signal = this.#uiManager._signal;
div.addEventListener("contextmenu", noContextMenu, {
signal
});
div.className = "dropdown";
div.role = "listbox";
div.ariaMultiSelectable = "false";
div.ariaOrientation = "vertical";
div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown");
if (this.#editor) {
div.id = `${this.#editor.id}_colorpicker_dropdown`;
}
for (const [name, color2] of this.#uiManager.highlightColors) {
const button = document.createElement("button");
button.tabIndex = "0";
button.role = "option";
button.setAttribute("data-color", color2);
button.title = name;
button.setAttribute("data-l10n-id", _ColorPicker.#l10nColor[name]);
const swatch = document.createElement("span");
button.append(swatch);
swatch.className = "swatch";
swatch.style.backgroundColor = color2;
button.ariaSelected = color2 === this.#defaultColor;
button.addEventListener("click", this.#colorSelect.bind(this, color2), {
signal
});
div.append(button);
}
div.addEventListener("keydown", this.#keyDown.bind(this), {
signal
});
return div;
}
#colorSelect(color2, event) {
event.stopPropagation();
this.#eventBus.dispatch("switchannotationeditorparams", {
source: this,
type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,
value: color2
});
this.updateColor(color2);
}
_colorSelectFromKeyboard(event) {
if (event.target === this.#button) {
this.#openDropdown(event);
return;
}
const color2 = event.target.getAttribute("data-color");
if (!color2) {
return;
}
this.#colorSelect(color2, event);
}
_moveToNext(event) {
if (!this.#isDropdownVisible) {
this.#openDropdown(event);
return;
}
if (event.target === this.#button) {
this.#dropdown.firstChild?.focus();
return;
}
event.target.nextSibling?.focus();
}
_moveToPrevious(event) {
if (event.target === this.#dropdown?.firstChild || event.target === this.#button) {
if (this.#isDropdownVisible) {
this._hideDropdownFromKeyboard();
}
return;
}
if (!this.#isDropdownVisible) {
this.#openDropdown(event);
}
event.target.previousSibling?.focus();
}
_moveToBeginning(event) {
if (!this.#isDropdownVisible) {
this.#openDropdown(event);
return;
}
this.#dropdown.firstChild?.focus();
}
_moveToEnd(event) {
if (!this.#isDropdownVisible) {
this.#openDropdown(event);
return;
}
this.#dropdown.lastChild?.focus();
}
#keyDown(event) {
_ColorPicker._keyboardManager.exec(this, event);
}
#openDropdown(event) {
if (this.#isDropdownVisible) {
this.hideDropdown();
return;
}
this.#dropdownWasFromKeyboard = event.detail === 0;
if (!this.#openDropdownAC) {
this.#openDropdownAC = new AbortController();
window.addEventListener("pointerdown", this.#pointerDown.bind(this), {
signal: this.#uiManager.combinedSignal(this.#openDropdownAC)
});
}
this.#button.ariaExpanded = "true";
if (this.#dropdown) {
this.#dropdown.classList.remove("hidden");
return;
}
const root = this.#dropdown = this.#getDropdownRoot();
this.#button.append(root);
}
#pointerDown(event) {
if (this.#dropdown?.contains(event.target)) {
return;
}
this.hideDropdown();
}
hideDropdown() {
this.#dropdown?.classList.add("hidden");
this.#button.ariaExpanded = "false";
this.#openDropdownAC?.abort();
this.#openDropdownAC = null;
}
get #isDropdownVisible() {
return this.#dropdown && !this.#dropdown.classList.contains("hidden");
}
_hideDropdownFromKeyboard() {
if (this.#isMainColorPicker) {
return;
}
if (!this.#isDropdownVisible) {
this.#editor?.unselect();
return;
}
this.hideDropdown();
this.#button.focus({
preventScroll: true,
focusVisible: this.#dropdownWasFromKeyboard
});
}
updateColor(color2) {
if (this.#buttonSwatch) {
this.#buttonSwatch.style.backgroundColor = color2;
}
if (!this.#dropdown) {
return;
}
const i7 = this.#uiManager.highlightColors.values();
for (const child of this.#dropdown.children) {
child.ariaSelected = i7.next().value === color2.toUpperCase();
}
}
destroy() {
this.#button?.remove();
this.#button = null;
this.#buttonSwatch = null;
this.#dropdown?.remove();
this.#dropdown = null;
}
};
BasicColorPicker = class _BasicColorPicker {
#input = null;
#editor = null;
#uiManager = null;
static #l10nColor = null;
constructor(editor) {
this.#editor = editor;
this.#uiManager = editor._uiManager;
_BasicColorPicker.#l10nColor ||= Object.freeze({
freetext: "pdfjs-editor-color-picker-free-text-input",
ink: "pdfjs-editor-color-picker-ink-input"
});
}
renderButton() {
if (this.#input) {
return this.#input;
}
const {
editorType,
colorType,
color: color2
} = this.#editor;
const input = this.#input = document.createElement("input");
input.type = "color";
input.value = color2 || "#000000";
input.className = "basicColorPicker";
input.tabIndex = 0;
input.setAttribute("data-l10n-id", _BasicColorPicker.#l10nColor[editorType]);
input.addEventListener("input", () => {
this.#uiManager.updateParams(colorType, input.value);
}, {
signal: this.#uiManager._signal
});
return input;
}
update(value) {
if (!this.#input) {
return;
}
this.#input.value = value;
}
destroy() {
this.#input?.remove();
this.#input = null;
}
hideDropdown() {
}
};
ColorConverters = class {
static CMYK_G([c6, y4, m4, k2]) {
return ["G", 1 - Math.min(1, 0.3 * c6 + 0.59 * m4 + 0.11 * y4 + k2)];
}
static G_CMYK([g3]) {
return ["CMYK", 0, 0, 0, 1 - g3];
}
static G_RGB([g3]) {
return ["RGB", g3, g3, g3];
}
static G_rgb([g3]) {
g3 = scaleAndClamp(g3);
return [g3, g3, g3];
}
static G_HTML([g3]) {
const G2 = makeColorComp(g3);
return `#${G2}${G2}${G2}`;
}
static RGB_G([r8, g3, b4]) {
return ["G", 0.3 * r8 + 0.59 * g3 + 0.11 * b4];
}
static RGB_rgb(color2) {
return color2.map(scaleAndClamp);
}
static RGB_HTML(color2) {
return `#${color2.map(makeColorComp).join("")}`;
}
static T_HTML() {
return "#00000000";
}
static T_rgb() {
return [null];
}
static CMYK_RGB([c6, y4, m4, k2]) {
return ["RGB", 1 - Math.min(1, c6 + k2), 1 - Math.min(1, m4 + k2), 1 - Math.min(1, y4 + k2)];
}
static CMYK_rgb([c6, y4, m4, k2]) {
return [scaleAndClamp(1 - Math.min(1, c6 + k2)), scaleAndClamp(1 - Math.min(1, m4 + k2)), scaleAndClamp(1 - Math.min(1, y4 + k2))];
}
static CMYK_HTML(components) {
const rgb = this.CMYK_RGB(components).slice(1);
return this.RGB_HTML(rgb);
}
static RGB_CMYK([r8, g3, b4]) {
const c6 = 1 - r8;
const m4 = 1 - g3;
const y4 = 1 - b4;
const k2 = Math.min(c6, m4, y4);
return ["CMYK", c6, m4, y4, k2];
}
};
BaseSVGFactory = class {
create(width, height, skipDimensions = false) {
if (width <= 0 || height <= 0) {
throw new Error("Invalid SVG dimensions");
}
const svg = this._createSVG("svg:svg");
svg.setAttribute("version", "1.1");
if (!skipDimensions) {
svg.setAttribute("width", `${width}px`);
svg.setAttribute("height", `${height}px`);
}
svg.setAttribute("preserveAspectRatio", "none");
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
return svg;
}
createElement(type) {
if (typeof type !== "string") {
throw new Error("Invalid SVG element type");
}
return this._createSVG(type);
}
_createSVG(type) {
unreachable("Abstract method `_createSVG` called.");
}
};
DOMSVGFactory = class extends BaseSVGFactory {
_createSVG(type) {
return document.createElementNS(SVG_NS, type);
}
};
annotation_layer_DEFAULT_FONT_SIZE = 9;
GetElementsByNameSet = /* @__PURE__ */ new WeakSet();
TIMEZONE_OFFSET = (/* @__PURE__ */ new Date()).getTimezoneOffset() * 60 * 1e3;
AnnotationElementFactory = class {
static create(parameters) {
const subtype = parameters.data.annotationType;
switch (subtype) {
case AnnotationType.LINK:
return new LinkAnnotationElement(parameters);
case AnnotationType.TEXT:
return new TextAnnotationElement(parameters);
case AnnotationType.WIDGET:
const fieldType = parameters.data.fieldType;
switch (fieldType) {
case "Tx":
return new TextWidgetAnnotationElement(parameters);
case "Btn":
if (parameters.data.radioButton) {
return new RadioButtonWidgetAnnotationElement(parameters);
} else if (parameters.data.checkBox) {
return new CheckboxWidgetAnnotationElement(parameters);
}
return new PushButtonWidgetAnnotationElement(parameters);
case "Ch":
return new ChoiceWidgetAnnotationElement(parameters);
case "Sig":
return new SignatureWidgetAnnotationElement(parameters);
}
return new WidgetAnnotationElement(parameters);
case AnnotationType.POPUP:
return new PopupAnnotationElement(parameters);
case AnnotationType.FREETEXT:
return new FreeTextAnnotationElement(parameters);
case AnnotationType.LINE:
return new LineAnnotationElement(parameters);
case AnnotationType.SQUARE:
return new SquareAnnotationElement(parameters);
case AnnotationType.CIRCLE:
return new CircleAnnotationElement(parameters);
case AnnotationType.POLYLINE:
return new PolylineAnnotationElement(parameters);
case AnnotationType.CARET:
return new CaretAnnotationElement(parameters);
case AnnotationType.INK:
return new InkAnnotationElement(parameters);
case AnnotationType.POLYGON:
return new PolygonAnnotationElement(parameters);
case AnnotationType.HIGHLIGHT:
return new HighlightAnnotationElement(parameters);
case AnnotationType.UNDERLINE:
return new UnderlineAnnotationElement(parameters);
case AnnotationType.SQUIGGLY:
return new SquigglyAnnotationElement(parameters);
case AnnotationType.STRIKEOUT:
return new StrikeOutAnnotationElement(parameters);
case AnnotationType.STAMP:
return new StampAnnotationElement(parameters);
case AnnotationType.FILEATTACHMENT:
return new FileAttachmentAnnotationElement(parameters);
default:
return new AnnotationElement(parameters);
}
}
};
AnnotationElement = class _AnnotationElement {
#updates = null;
#hasBorder = false;
#popupElement = null;
constructor(parameters, {
isRenderable = false,
ignoreBorder = false,
createQuadrilaterals = false
} = {}) {
this.isRenderable = isRenderable;
this.data = parameters.data;
this.layer = parameters.layer;
this.linkService = parameters.linkService;
this.downloadManager = parameters.downloadManager;
this.imageResourcesPath = parameters.imageResourcesPath;
this.renderForms = parameters.renderForms;
this.svgFactory = parameters.svgFactory;
this.annotationStorage = parameters.annotationStorage;
this.enableComment = parameters.enableComment;
this.enableScripting = parameters.enableScripting;
this.hasJSActions = parameters.hasJSActions;
this._fieldObjects = parameters.fieldObjects;
this.parent = parameters.parent;
this.hasOwnCommentButton = false;
if (isRenderable) {
this.contentElement = this.container = this._createContainer(ignoreBorder);
}
if (createQuadrilaterals) {
this._createQuadrilaterals();
}
}
static _hasPopupData({
contentsObj,
richText
}) {
return !!(contentsObj?.str || richText?.str);
}
get _isEditable() {
return this.data.isEditable;
}
get hasPopupData() {
return _AnnotationElement._hasPopupData(this.data) || this.enableComment && !!this.commentText;
}
get commentData() {
const {
data
} = this;
const editor = this.annotationStorage?.getEditor(data.id);
if (editor) {
return editor.getData();
}
return data;
}
get hasCommentButton() {
return this.enableComment && this.hasPopupElement;
}
get commentButtonPosition() {
const editor = this.annotationStorage?.getEditor(this.data.id);
if (editor) {
return editor.commentButtonPositionInPage;
}
const {
quadPoints,
inkLists,
rect
} = this.data;
let maxX = -Infinity;
let maxY = -Infinity;
if (quadPoints?.length >= 8) {
for (let i7 = 0; i7 < quadPoints.length; i7 += 8) {
if (quadPoints[i7 + 1] > maxY) {
maxY = quadPoints[i7 + 1];
maxX = quadPoints[i7 + 2];
} else if (quadPoints[i7 + 1] === maxY) {
maxX = Math.max(maxX, quadPoints[i7 + 2]);
}
}
return [maxX, maxY];
}
if (inkLists?.length >= 1) {
for (const inkList of inkLists) {
for (let i7 = 0, ii = inkList.length; i7 < ii; i7 += 2) {
if (inkList[i7 + 1] > maxY) {
maxY = inkList[i7 + 1];
maxX = inkList[i7];
} else if (inkList[i7 + 1] === maxY) {
maxX = Math.max(maxX, inkList[i7]);
}
}
}
if (maxX !== Infinity) {
return [maxX, maxY];
}
}
if (rect) {
return [rect[2], rect[3]];
}
return null;
}
_normalizePoint(point) {
const {
page: {
view
},
viewport: {
rawDims: {
pageWidth,
pageHeight,
pageX,
pageY
}
}
} = this.parent;
point[1] = view[3] - point[1] + view[1];
point[0] = 100 * (point[0] - pageX) / pageWidth;
point[1] = 100 * (point[1] - pageY) / pageHeight;
return point;
}
get commentText() {
const {
data
} = this;
return this.annotationStorage.getRawValue(`${AnnotationEditorPrefix}${data.id}`)?.popup?.contents || data.contentsObj?.str || "";
}
set commentText(text3) {
const {
data
} = this;
const popup = {
deleted: !text3,
contents: text3 || ""
};
if (!this.annotationStorage.updateEditor(data.id, {
popup
})) {
this.annotationStorage.setValue(`${AnnotationEditorPrefix}${data.id}`, {
id: data.id,
annotationType: data.annotationType,
pageIndex: this.parent.page._pageIndex,
popup,
popupRef: data.popupRef,
modificationDate: /* @__PURE__ */ new Date()
});
}
if (!text3) {
this.removePopup();
}
}
removePopup() {
(this.#popupElement?.popup || this.popup)?.remove();
this.#popupElement = this.popup = null;
}
updateEdited(params) {
if (!this.container) {
return;
}
if (params.rect) {
this.#updates ||= {
rect: this.data.rect.slice(0)
};
}
const {
rect,
popup: newPopup
} = params;
if (rect) {
this.#setRectEdited(rect);
}
let popup = this.#popupElement?.popup || this.popup;
if (!popup && newPopup?.text) {
this._createPopup(newPopup);
popup = this.#popupElement.popup;
}
if (!popup) {
return;
}
popup.updateEdited(params);
if (newPopup?.deleted) {
popup.remove();
this.#popupElement = null;
this.popup = null;
}
}
resetEdited() {
if (!this.#updates) {
return;
}
this.#setRectEdited(this.#updates.rect);
this.#popupElement?.popup.resetEdited();
this.#updates = null;
}
#setRectEdited(rect) {
const {
container: {
style
},
data: {
rect: currentRect,
rotation
},
parent: {
viewport: {
rawDims: {
pageWidth,
pageHeight,
pageX,
pageY
}
}
}
} = this;
currentRect?.splice(0, 4, ...rect);
style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`;
if (rotation === 0) {
style.width = `${100 * (rect[2] - rect[0]) / pageWidth}%`;
style.height = `${100 * (rect[3] - rect[1]) / pageHeight}%`;
} else {
this.setRotation(rotation);
}
}
_createContainer(ignoreBorder) {
const {
data,
parent: {
page,
viewport
}
} = this;
const container = document.createElement("section");
container.setAttribute("data-annotation-id", data.id);
if (!(this instanceof WidgetAnnotationElement) && !(this instanceof LinkAnnotationElement)) {
container.tabIndex = 0;
}
const {
style
} = container;
style.zIndex = this.parent.zIndex;
this.parent.zIndex += 2;
if (data.alternativeText) {
container.title = data.alternativeText;
}
if (data.noRotate) {
container.classList.add("norotate");
}
if (!data.rect || this instanceof PopupAnnotationElement) {
const {
rotation: rotation2
} = data;
if (!data.hasOwnCanvas && rotation2 !== 0) {
this.setRotation(rotation2, container);
}
return container;
}
const {
width,
height
} = this;
if (!ignoreBorder && data.borderStyle.width > 0) {
style.borderWidth = `${data.borderStyle.width}px`;
const horizontalRadius = data.borderStyle.horizontalCornerRadius;
const verticalRadius = data.borderStyle.verticalCornerRadius;
if (horizontalRadius > 0 || verticalRadius > 0) {
const radius = `calc(${horizontalRadius}px * var(--total-scale-factor)) / calc(${verticalRadius}px * var(--total-scale-factor))`;
style.borderRadius = radius;
} else if (this instanceof RadioButtonWidgetAnnotationElement) {
const radius = `calc(${width}px * var(--total-scale-factor)) / calc(${height}px * var(--total-scale-factor))`;
style.borderRadius = radius;
}
switch (data.borderStyle.style) {
case AnnotationBorderStyleType.SOLID:
style.borderStyle = "solid";
break;
case AnnotationBorderStyleType.DASHED:
style.borderStyle = "dashed";
break;
case AnnotationBorderStyleType.BEVELED:
warn("Unimplemented border style: beveled");
break;
case AnnotationBorderStyleType.INSET:
warn("Unimplemented border style: inset");
break;
case AnnotationBorderStyleType.UNDERLINE:
style.borderBottomStyle = "solid";
break;
default:
break;
}
const borderColor = data.borderColor || null;
if (borderColor) {
this.#hasBorder = true;
style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
} else {
style.borderWidth = 0;
}
}
const rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
const {
pageWidth,
pageHeight,
pageX,
pageY
} = viewport.rawDims;
style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
const {
rotation
} = data;
if (data.hasOwnCanvas || rotation === 0) {
style.width = `${100 * width / pageWidth}%`;
style.height = `${100 * height / pageHeight}%`;
} else {
this.setRotation(rotation, container);
}
return container;
}
setRotation(angle, container = this.container) {
if (!this.data.rect) {
return;
}
const {
pageWidth,
pageHeight
} = this.parent.viewport.rawDims;
let {
width,
height
} = this;
if (angle % 180 !== 0) {
[width, height] = [height, width];
}
container.style.width = `${100 * width / pageWidth}%`;
container.style.height = `${100 * height / pageHeight}%`;
container.setAttribute("data-main-rotation", (360 - angle) % 360);
}
get _commonActions() {
const setColor = (jsName, styleName, event) => {
const color2 = event.detail[jsName];
const colorType = color2[0];
const colorArray = color2.slice(1);
event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray);
this.annotationStorage.setValue(this.data.id, {
[styleName]: ColorConverters[`${colorType}_rgb`](colorArray)
});
};
return shadow(this, "_commonActions", {
display: (event) => {
const {
display
} = event.detail;
const hidden = display % 2 === 1;
this.container.style.visibility = hidden ? "hidden" : "visible";
this.annotationStorage.setValue(this.data.id, {
noView: hidden,
noPrint: display === 1 || display === 2
});
},
print: (event) => {
this.annotationStorage.setValue(this.data.id, {
noPrint: !event.detail.print
});
},
hidden: (event) => {
const {
hidden
} = event.detail;
this.container.style.visibility = hidden ? "hidden" : "visible";
this.annotationStorage.setValue(this.data.id, {
noPrint: hidden,
noView: hidden
});
},
focus: (event) => {
setTimeout(() => event.target.focus({
preventScroll: false
}), 0);
},
userName: (event) => {
event.target.title = event.detail.userName;
},
readonly: (event) => {
event.target.disabled = event.detail.readonly;
},
required: (event) => {
this._setRequired(event.target, event.detail.required);
},
bgColor: (event) => {
setColor("bgColor", "backgroundColor", event);
},
fillColor: (event) => {
setColor("fillColor", "backgroundColor", event);
},
fgColor: (event) => {
setColor("fgColor", "color", event);
},
textColor: (event) => {
setColor("textColor", "color", event);
},
borderColor: (event) => {
setColor("borderColor", "borderColor", event);
},
strokeColor: (event) => {
setColor("strokeColor", "borderColor", event);
},
rotation: (event) => {
const angle = event.detail.rotation;
this.setRotation(angle);
this.annotationStorage.setValue(this.data.id, {
rotation: angle
});
}
});
}
_dispatchEventFromSandbox(actions, jsEvent) {
const commonActions = this._commonActions;
for (const name of Object.keys(jsEvent.detail)) {
const action = actions[name] || commonActions[name];
action?.(jsEvent);
}
}
_setDefaultPropertiesFromJS(element) {
if (!this.enableScripting) {
return;
}
const storedData = this.annotationStorage.getRawValue(this.data.id);
if (!storedData) {
return;
}
const commonActions = this._commonActions;
for (const [actionName, detail] of Object.entries(storedData)) {
const action = commonActions[actionName];
if (action) {
const eventProxy = {
detail: {
[actionName]: detail
},
target: element
};
action(eventProxy);
delete storedData[actionName];
}
}
}
_createQuadrilaterals() {
if (!this.container) {
return;
}
const {
quadPoints
} = this.data;
if (!quadPoints) {
return;
}
const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map((x2) => Math.fround(x2));
if (quadPoints.length === 8) {
const [trX, trY, blX, blY] = quadPoints.subarray(2, 6);
if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) {
return;
}
}
const {
style
} = this.container;
let svgBuffer;
if (this.#hasBorder) {
const {
borderColor,
borderWidth
} = style;
style.borderWidth = 0;
svgBuffer = ["url('data:image/svg+xml;utf8,", `')`);
style.backgroundImage = svgBuffer.join("");
}
this.container.append(svg);
this.container.style.clipPath = `url(#${id})`;
}
_createPopup(popupData = null) {
const {
data
} = this;
let contentsObj, modificationDate;
if (popupData) {
contentsObj = {
str: popupData.text
};
modificationDate = popupData.date;
} else {
contentsObj = data.contentsObj;
modificationDate = data.modificationDate;
}
this.#popupElement = new PopupAnnotationElement({
data: {
color: data.color,
titleObj: data.titleObj,
modificationDate,
contentsObj,
richText: data.richText,
parentRect: data.rect,
borderStyle: 0,
id: `popup_${data.id}`,
rotation: data.rotation,
noRotate: true
},
linkService: this.linkService,
parent: this.parent,
elements: [this]
});
}
get hasPopupElement() {
return !!(this.#popupElement || this.popup || this.data.popupRef);
}
get extraPopupElement() {
return this.#popupElement;
}
render() {
unreachable("Abstract method `AnnotationElement.render` called");
}
_getElementsByName(name, skipId = null) {
const fields = [];
if (this._fieldObjects) {
const fieldObj = this._fieldObjects[name];
if (fieldObj) {
for (const {
page,
id,
exportValues
} of fieldObj) {
if (page === -1) {
continue;
}
if (id === skipId) {
continue;
}
const exportValue = typeof exportValues === "string" ? exportValues : null;
const domElement = document.querySelector(`[data-element-id="${id}"]`);
if (domElement && !GetElementsByNameSet.has(domElement)) {
warn(`_getElementsByName - element not allowed: ${id}`);
continue;
}
fields.push({
id,
exportValue,
domElement
});
}
}
return fields;
}
for (const domElement of document.getElementsByName(name)) {
const {
exportValue
} = domElement;
const id = domElement.getAttribute("data-element-id");
if (id === skipId) {
continue;
}
if (!GetElementsByNameSet.has(domElement)) {
continue;
}
fields.push({
id,
exportValue,
domElement
});
}
return fields;
}
show() {
if (this.container) {
this.container.hidden = false;
}
this.popup?.maybeShow();
}
hide() {
if (this.container) {
this.container.hidden = true;
}
this.popup?.forceHide();
}
getElementsToTriggerPopup() {
return this.container;
}
addHighlightArea() {
const triggers = this.getElementsToTriggerPopup();
if (Array.isArray(triggers)) {
for (const element of triggers) {
element.classList.add("highlightArea");
}
} else {
triggers.classList.add("highlightArea");
}
}
_editOnDoubleClick() {
if (!this._isEditable) {
return;
}
const {
annotationEditorType: mode,
data: {
id: editId
}
} = this;
this.container.addEventListener("dblclick", () => {
this.linkService.eventBus?.dispatch("switchannotationeditormode", {
source: this,
mode,
editId,
mustEnterInEditMode: true
});
});
}
get width() {
return this.data.rect[2] - this.data.rect[0];
}
get height() {
return this.data.rect[3] - this.data.rect[1];
}
};
EditorAnnotationElement = class extends AnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true
});
this.editor = parameters.editor;
}
render() {
this.container.className = "editorAnnotation";
return this.container;
}
createOrUpdatePopup() {
const {
editor
} = this;
if (!editor.hasComment) {
return;
}
this._createPopup(editor.comment);
}
get hasCommentButton() {
return this.enableComment && this.editor.hasComment;
}
get commentButtonPosition() {
return this.editor.commentButtonPositionInPage;
}
get commentText() {
return this.editor.comment.text;
}
set commentText(text3) {
this.editor.comment = text3;
if (!text3) {
this.removePopup();
}
}
get commentData() {
return this.editor.getData();
}
remove() {
this.parent.removeAnnotation(this.data.id);
this.container.remove();
this.container = null;
this.removePopup();
}
};
LinkAnnotationElement = class extends AnnotationElement {
constructor(parameters, options = null) {
super(parameters, {
isRenderable: true,
ignoreBorder: !!options?.ignoreBorder,
createQuadrilaterals: true
});
this.isTooltipOnly = parameters.data.isTooltipOnly;
}
render() {
const {
data,
linkService
} = this;
const link = document.createElement("a");
link.setAttribute("data-element-id", data.id);
let isBound = false;
if (data.url) {
linkService.addLinkAttributes(link, data.url, data.newWindow);
isBound = true;
} else if (data.action) {
this._bindNamedAction(link, data.action, data.overlaidText);
isBound = true;
} else if (data.attachment) {
this.#bindAttachment(link, data.attachment, data.overlaidText, data.attachmentDest);
isBound = true;
} else if (data.setOCGState) {
this.#bindSetOCGState(link, data.setOCGState, data.overlaidText);
isBound = true;
} else if (data.dest) {
this._bindLink(link, data.dest, data.overlaidText);
isBound = true;
} else {
if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
this._bindJSAction(link, data);
isBound = true;
}
if (data.resetForm) {
this._bindResetFormAction(link, data.resetForm);
isBound = true;
} else if (this.isTooltipOnly && !isBound) {
this._bindLink(link, "");
isBound = true;
}
}
this.container.classList.add("linkAnnotation");
if (isBound) {
this.contentElement = link;
this.container.append(link);
}
return this.container;
}
#setInternalLink() {
this.container.setAttribute("data-internal-link", "");
}
_bindLink(link, destination, overlaidText = "") {
link.href = this.linkService.getDestinationHash(destination);
link.onclick = () => {
if (destination) {
this.linkService.goToDestination(destination);
}
return false;
};
if (destination || destination === "") {
this.#setInternalLink();
}
if (overlaidText) {
link.title = overlaidText;
}
}
_bindNamedAction(link, action, overlaidText = "") {
link.href = this.linkService.getAnchorUrl("");
link.onclick = () => {
this.linkService.executeNamedAction(action);
return false;
};
if (overlaidText) {
link.title = overlaidText;
}
this.#setInternalLink();
}
#bindAttachment(link, attachment, overlaidText = "", dest = null) {
link.href = this.linkService.getAnchorUrl("");
if (attachment.description) {
link.title = attachment.description;
} else if (overlaidText) {
link.title = overlaidText;
}
link.onclick = () => {
this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest);
return false;
};
this.#setInternalLink();
}
#bindSetOCGState(link, action, overlaidText = "") {
link.href = this.linkService.getAnchorUrl("");
link.onclick = () => {
this.linkService.executeSetOCGState(action);
return false;
};
if (overlaidText) {
link.title = overlaidText;
}
this.#setInternalLink();
}
_bindJSAction(link, data) {
link.href = this.linkService.getAnchorUrl("");
const map3 = /* @__PURE__ */ new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
for (const name of Object.keys(data.actions)) {
const jsName = map3.get(name);
if (!jsName) {
continue;
}
link[jsName] = () => {
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id: data.id,
name
}
});
return false;
};
}
if (data.overlaidText) {
link.title = data.overlaidText;
}
if (!link.onclick) {
link.onclick = () => false;
}
this.#setInternalLink();
}
_bindResetFormAction(link, resetForm) {
const otherClickAction = link.onclick;
if (!otherClickAction) {
link.href = this.linkService.getAnchorUrl("");
}
this.#setInternalLink();
if (!this._fieldObjects) {
warn(`_bindResetFormAction - "resetForm" action not supported, ensure that the \`fieldObjects\` parameter is provided.`);
if (!otherClickAction) {
link.onclick = () => false;
}
return;
}
link.onclick = () => {
otherClickAction?.();
const {
fields: resetFormFields,
refs: resetFormRefs,
include
} = resetForm;
const allFields = [];
if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
const fieldIds = new Set(resetFormRefs);
for (const fieldName of resetFormFields) {
const fields = this._fieldObjects[fieldName] || [];
for (const {
id
} of fields) {
fieldIds.add(id);
}
}
for (const fields of Object.values(this._fieldObjects)) {
for (const field of fields) {
if (fieldIds.has(field.id) === include) {
allFields.push(field);
}
}
}
} else {
for (const fields of Object.values(this._fieldObjects)) {
allFields.push(...fields);
}
}
const storage2 = this.annotationStorage;
const allIds = [];
for (const field of allFields) {
const {
id
} = field;
allIds.push(id);
switch (field.type) {
case "text": {
const value = field.defaultValue || "";
storage2.setValue(id, {
value
});
break;
}
case "checkbox":
case "radiobutton": {
const value = field.defaultValue === field.exportValues;
storage2.setValue(id, {
value
});
break;
}
case "combobox":
case "listbox": {
const value = field.defaultValue || "";
storage2.setValue(id, {
value
});
break;
}
default:
continue;
}
const domElement = document.querySelector(`[data-element-id="${id}"]`);
if (!domElement) {
continue;
} else if (!GetElementsByNameSet.has(domElement)) {
warn(`_bindResetFormAction - element not allowed: ${id}`);
continue;
}
domElement.dispatchEvent(new Event("resetform"));
}
if (this.enableScripting) {
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id: "app",
ids: allIds,
name: "ResetForm"
}
});
}
return false;
};
}
};
TextAnnotationElement = class extends AnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: true
});
}
render() {
this.container.classList.add("textAnnotation");
const image = document.createElement("img");
image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type");
image.setAttribute("data-l10n-args", JSON.stringify({
type: this.data.name
}));
if (!this.data.popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
this.container.append(image);
return this.container;
}
};
WidgetAnnotationElement = class extends AnnotationElement {
render() {
return this.container;
}
showElementAndHideCanvas(element) {
if (this.data.hasOwnCanvas) {
if (element.previousSibling?.nodeName === "CANVAS") {
element.previousSibling.hidden = true;
}
element.hidden = false;
}
}
_getKeyModifier(event) {
return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey;
}
_setEventListener(element, elementData, baseName, eventName, valueGetter) {
if (baseName.includes("mouse")) {
element.addEventListener(baseName, (event) => {
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id: this.data.id,
name: eventName,
value: valueGetter(event),
shift: event.shiftKey,
modifier: this._getKeyModifier(event)
}
});
});
} else {
element.addEventListener(baseName, (event) => {
if (baseName === "blur") {
if (!elementData.focused || !event.relatedTarget) {
return;
}
elementData.focused = false;
} else if (baseName === "focus") {
if (elementData.focused) {
return;
}
elementData.focused = true;
}
if (!valueGetter) {
return;
}
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id: this.data.id,
name: eventName,
value: valueGetter(event)
}
});
});
}
}
_setEventListeners(element, elementData, names2, getter) {
for (const [baseName, eventName] of names2) {
if (eventName === "Action" || this.data.actions?.[eventName]) {
if (eventName === "Focus" || eventName === "Blur") {
elementData ||= {
focused: false
};
}
this._setEventListener(element, elementData, baseName, eventName, getter);
if (eventName === "Focus" && !this.data.actions?.Blur) {
this._setEventListener(element, elementData, "blur", "Blur", null);
} else if (eventName === "Blur" && !this.data.actions?.Focus) {
this._setEventListener(element, elementData, "focus", "Focus", null);
}
}
}
}
_setBackgroundColor(element) {
const color2 = this.data.backgroundColor || null;
element.style.backgroundColor = color2 === null ? "transparent" : Util.makeHexColor(color2[0], color2[1], color2[2]);
}
_setTextStyle(element) {
const TEXT_ALIGNMENT = ["left", "center", "right"];
const {
fontColor
} = this.data.defaultAppearanceData;
const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE;
const style = element.style;
let computedFontSize;
const BORDER_SIZE = 2;
const roundToOneDecimal = (x2) => Math.round(10 * x2) / 10;
if (this.data.multiLine) {
const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1;
const lineHeight = height / numberOfLines;
computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR));
} else {
const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR));
}
style.fontSize = `calc(${computedFontSize}px * var(--total-scale-factor))`;
style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
if (this.data.textAlignment !== null) {
style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
}
}
_setRequired(element, isRequired) {
if (isRequired) {
element.setAttribute("required", true);
} else {
element.removeAttribute("required");
}
element.setAttribute("aria-required", isRequired);
}
};
TextWidgetAnnotationElement = class extends WidgetAnnotationElement {
constructor(parameters) {
const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
super(parameters, {
isRenderable
});
}
setPropertyOnSiblings(base, key, value, keyInStorage) {
const storage2 = this.annotationStorage;
for (const element of this._getElementsByName(base.name, base.id)) {
if (element.domElement) {
element.domElement[key] = value;
}
storage2.setValue(element.id, {
[keyInStorage]: value
});
}
}
render() {
const storage2 = this.annotationStorage;
const id = this.data.id;
this.container.classList.add("textWidgetAnnotation");
let element = null;
if (this.renderForms) {
const storedData = storage2.getValue(id, {
value: this.data.fieldValue
});
let textContent = storedData.value || "";
const maxLen = storage2.getValue(id, {
charLimit: this.data.maxLen
}).charLimit;
if (maxLen && textContent.length > maxLen) {
textContent = textContent.slice(0, maxLen);
}
let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null;
if (fieldFormattedValues && this.data.comb) {
fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, "");
}
const elementData = {
userValue: textContent,
formattedValue: fieldFormattedValues,
lastCommittedValue: null,
commitKey: 1,
focused: false
};
if (this.data.multiLine) {
element = document.createElement("textarea");
element.textContent = fieldFormattedValues ?? textContent;
if (this.data.doNotScroll) {
element.style.overflowY = "hidden";
}
} else {
element = document.createElement("input");
element.type = this.data.password ? "password" : "text";
element.setAttribute("value", fieldFormattedValues ?? textContent);
if (this.data.doNotScroll) {
element.style.overflowX = "hidden";
}
}
if (this.data.hasOwnCanvas) {
element.hidden = true;
}
GetElementsByNameSet.add(element);
this.contentElement = element;
element.setAttribute("data-element-id", id);
element.disabled = this.data.readOnly;
element.name = this.data.fieldName;
element.tabIndex = 0;
const {
datetimeFormat,
datetimeType,
timeStep
} = this.data;
const hasDateOrTime = !!datetimeType && this.enableScripting;
if (datetimeFormat) {
element.title = datetimeFormat;
}
this._setRequired(element, this.data.required);
if (maxLen) {
element.maxLength = maxLen;
}
element.addEventListener("input", (event) => {
storage2.setValue(id, {
value: event.target.value
});
this.setPropertyOnSiblings(element, "value", event.target.value, "value");
elementData.formattedValue = null;
});
element.addEventListener("resetform", (event) => {
const defaultValue = this.data.defaultFieldValue ?? "";
element.value = elementData.userValue = defaultValue;
elementData.formattedValue = null;
});
let blurListener = (event) => {
const {
formattedValue
} = elementData;
if (formattedValue !== null && formattedValue !== void 0) {
event.target.value = formattedValue;
}
event.target.scrollLeft = 0;
};
if (this.enableScripting && this.hasJSActions) {
element.addEventListener("focus", (event) => {
if (elementData.focused) {
return;
}
const {
target
} = event;
if (hasDateOrTime) {
target.type = datetimeType;
if (timeStep) {
target.step = timeStep;
}
}
if (elementData.userValue) {
const value = elementData.userValue;
if (hasDateOrTime) {
if (datetimeType === "time") {
const date = new Date(value);
const parts = [date.getHours(), date.getMinutes(), date.getSeconds()];
target.value = parts.map((v4) => v4.toString().padStart(2, "0")).join(":");
} else {
target.value = new Date(value - TIMEZONE_OFFSET).toISOString().split(datetimeType === "date" ? "T" : ".", 1)[0];
}
} else {
target.value = value;
}
}
elementData.lastCommittedValue = target.value;
elementData.commitKey = 1;
if (!this.data.actions?.Focus) {
elementData.focused = true;
}
});
element.addEventListener("updatefromsandbox", (jsEvent) => {
this.showElementAndHideCanvas(jsEvent.target);
const actions = {
value(event) {
elementData.userValue = event.detail.value ?? "";
if (!hasDateOrTime) {
storage2.setValue(id, {
value: elementData.userValue.toString()
});
}
event.target.value = elementData.userValue;
},
formattedValue(event) {
const {
formattedValue
} = event.detail;
elementData.formattedValue = formattedValue;
if (formattedValue !== null && formattedValue !== void 0 && event.target !== document.activeElement) {
event.target.value = formattedValue;
}
const data = {
formattedValue
};
if (hasDateOrTime) {
data.value = formattedValue;
}
storage2.setValue(id, data);
},
selRange(event) {
event.target.setSelectionRange(...event.detail.selRange);
},
charLimit: (event) => {
const {
charLimit
} = event.detail;
const {
target
} = event;
if (charLimit === 0) {
target.removeAttribute("maxLength");
return;
}
target.setAttribute("maxLength", charLimit);
let value = elementData.userValue;
if (!value || value.length <= charLimit) {
return;
}
value = value.slice(0, charLimit);
target.value = elementData.userValue = value;
storage2.setValue(id, {
value
});
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id,
name: "Keystroke",
value,
willCommit: true,
commitKey: 1,
selStart: target.selectionStart,
selEnd: target.selectionEnd
}
});
}
};
this._dispatchEventFromSandbox(actions, jsEvent);
});
element.addEventListener("keydown", (event) => {
elementData.commitKey = 1;
let commitKey = -1;
if (event.key === "Escape") {
commitKey = 0;
} else if (event.key === "Enter" && !this.data.multiLine) {
commitKey = 2;
} else if (event.key === "Tab") {
elementData.commitKey = 3;
}
if (commitKey === -1) {
return;
}
const {
value
} = event.target;
if (elementData.lastCommittedValue === value) {
return;
}
elementData.lastCommittedValue = value;
elementData.userValue = value;
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id,
name: "Keystroke",
value,
willCommit: true,
commitKey,
selStart: event.target.selectionStart,
selEnd: event.target.selectionEnd
}
});
});
const _blurListener = blurListener;
blurListener = null;
element.addEventListener("blur", (event) => {
if (!elementData.focused || !event.relatedTarget) {
return;
}
if (!this.data.actions?.Blur) {
elementData.focused = false;
}
const {
target
} = event;
let {
value
} = target;
if (hasDateOrTime) {
if (value && datetimeType === "time") {
const parts = value.split(":").map((v4) => parseInt(v4, 10));
value = new Date(2e3, 0, 1, parts[0], parts[1], parts[2] || 0).valueOf();
target.step = "";
} else {
if (!value.includes("T")) {
value = `${value}T00:00`;
}
value = new Date(value).valueOf();
}
target.type = "text";
}
elementData.userValue = value;
if (elementData.lastCommittedValue !== value) {
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id,
name: "Keystroke",
value,
willCommit: true,
commitKey: elementData.commitKey,
selStart: event.target.selectionStart,
selEnd: event.target.selectionEnd
}
});
}
_blurListener(event);
});
if (this.data.actions?.Keystroke) {
element.addEventListener("beforeinput", (event) => {
elementData.lastCommittedValue = null;
const {
data,
target
} = event;
const {
value,
selectionStart,
selectionEnd
} = target;
let selStart = selectionStart, selEnd = selectionEnd;
switch (event.inputType) {
case "deleteWordBackward": {
const match2 = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
if (match2) {
selStart -= match2[0].length;
}
break;
}
case "deleteWordForward": {
const match2 = value.substring(selectionStart).match(/^[^\w]*\w*/);
if (match2) {
selEnd += match2[0].length;
}
break;
}
case "deleteContentBackward":
if (selectionStart === selectionEnd) {
selStart -= 1;
}
break;
case "deleteContentForward":
if (selectionStart === selectionEnd) {
selEnd += 1;
}
break;
}
event.preventDefault();
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id,
name: "Keystroke",
value,
change: data || "",
willCommit: false,
selStart,
selEnd
}
});
});
}
this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], (event) => event.target.value);
}
if (blurListener) {
element.addEventListener("blur", blurListener);
}
if (this.data.comb) {
const fieldWidth = this.data.rect[2] - this.data.rect[0];
const combWidth = fieldWidth / maxLen;
element.classList.add("comb");
element.style.letterSpacing = `calc(${combWidth}px * var(--total-scale-factor) - 1ch)`;
}
} else {
element = document.createElement("div");
element.textContent = this.data.fieldValue;
element.style.verticalAlign = "middle";
element.style.display = "table-cell";
if (this.data.hasOwnCanvas) {
element.hidden = true;
}
}
this._setTextStyle(element);
this._setBackgroundColor(element);
this._setDefaultPropertiesFromJS(element);
this.container.append(element);
return this.container;
}
};
SignatureWidgetAnnotationElement = class extends WidgetAnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: !!parameters.data.hasOwnCanvas
});
}
};
CheckboxWidgetAnnotationElement = class extends WidgetAnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: parameters.renderForms
});
}
render() {
const storage2 = this.annotationStorage;
const data = this.data;
const id = data.id;
let value = storage2.getValue(id, {
value: data.exportValue === data.fieldValue
}).value;
if (typeof value === "string") {
value = value !== "Off";
storage2.setValue(id, {
value
});
}
this.container.classList.add("buttonWidgetAnnotation", "checkBox");
const element = document.createElement("input");
GetElementsByNameSet.add(element);
element.setAttribute("data-element-id", id);
element.disabled = data.readOnly;
this._setRequired(element, this.data.required);
element.type = "checkbox";
element.name = data.fieldName;
if (value) {
element.setAttribute("checked", true);
}
element.setAttribute("exportValue", data.exportValue);
element.tabIndex = 0;
element.addEventListener("change", (event) => {
const {
name,
checked
} = event.target;
for (const checkbox of this._getElementsByName(name, id)) {
const curChecked = checked && checkbox.exportValue === data.exportValue;
if (checkbox.domElement) {
checkbox.domElement.checked = curChecked;
}
storage2.setValue(checkbox.id, {
value: curChecked
});
}
storage2.setValue(id, {
value: checked
});
});
element.addEventListener("resetform", (event) => {
const defaultValue = data.defaultFieldValue || "Off";
event.target.checked = defaultValue === data.exportValue;
});
if (this.enableScripting && this.hasJSActions) {
element.addEventListener("updatefromsandbox", (jsEvent) => {
const actions = {
value(event) {
event.target.checked = event.detail.value !== "Off";
storage2.setValue(id, {
value: event.target.checked
});
}
};
this._dispatchEventFromSandbox(actions, jsEvent);
});
this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], (event) => event.target.checked);
}
this._setBackgroundColor(element);
this._setDefaultPropertiesFromJS(element);
this.container.append(element);
return this.container;
}
};
RadioButtonWidgetAnnotationElement = class extends WidgetAnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: parameters.renderForms
});
}
render() {
this.container.classList.add("buttonWidgetAnnotation", "radioButton");
const storage2 = this.annotationStorage;
const data = this.data;
const id = data.id;
let value = storage2.getValue(id, {
value: data.fieldValue === data.buttonValue
}).value;
if (typeof value === "string") {
value = value !== data.buttonValue;
storage2.setValue(id, {
value
});
}
if (value) {
for (const radio of this._getElementsByName(data.fieldName, id)) {
storage2.setValue(radio.id, {
value: false
});
}
}
const element = document.createElement("input");
GetElementsByNameSet.add(element);
element.setAttribute("data-element-id", id);
element.disabled = data.readOnly;
this._setRequired(element, this.data.required);
element.type = "radio";
element.name = data.fieldName;
if (value) {
element.setAttribute("checked", true);
}
element.tabIndex = 0;
element.addEventListener("change", (event) => {
const {
name,
checked
} = event.target;
for (const radio of this._getElementsByName(name, id)) {
storage2.setValue(radio.id, {
value: false
});
}
storage2.setValue(id, {
value: checked
});
});
element.addEventListener("resetform", (event) => {
const defaultValue = data.defaultFieldValue;
event.target.checked = defaultValue !== null && defaultValue !== void 0 && defaultValue === data.buttonValue;
});
if (this.enableScripting && this.hasJSActions) {
const pdfButtonValue = data.buttonValue;
element.addEventListener("updatefromsandbox", (jsEvent) => {
const actions = {
value: (event) => {
const checked = pdfButtonValue === event.detail.value;
for (const radio of this._getElementsByName(event.target.name)) {
const curChecked = checked && radio.id === id;
if (radio.domElement) {
radio.domElement.checked = curChecked;
}
storage2.setValue(radio.id, {
value: curChecked
});
}
}
};
this._dispatchEventFromSandbox(actions, jsEvent);
});
this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], (event) => event.target.checked);
}
this._setBackgroundColor(element);
this._setDefaultPropertiesFromJS(element);
this.container.append(element);
return this.container;
}
};
PushButtonWidgetAnnotationElement = class extends LinkAnnotationElement {
constructor(parameters) {
super(parameters, {
ignoreBorder: parameters.data.hasAppearance
});
}
render() {
const container = super.render();
container.classList.add("buttonWidgetAnnotation", "pushButton");
const linkElement = container.lastChild;
if (this.enableScripting && this.hasJSActions && linkElement) {
this._setDefaultPropertiesFromJS(linkElement);
linkElement.addEventListener("updatefromsandbox", (jsEvent) => {
this._dispatchEventFromSandbox({}, jsEvent);
});
}
return container;
}
};
ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: parameters.renderForms
});
}
render() {
this.container.classList.add("choiceWidgetAnnotation");
const storage2 = this.annotationStorage;
const id = this.data.id;
const storedData = storage2.getValue(id, {
value: this.data.fieldValue
});
const selectElement = document.createElement("select");
GetElementsByNameSet.add(selectElement);
selectElement.setAttribute("data-element-id", id);
selectElement.disabled = this.data.readOnly;
this._setRequired(selectElement, this.data.required);
selectElement.name = this.data.fieldName;
selectElement.tabIndex = 0;
let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
if (!this.data.combo) {
selectElement.size = this.data.options.length;
if (this.data.multiSelect) {
selectElement.multiple = true;
}
}
selectElement.addEventListener("resetform", (event) => {
const defaultValue = this.data.defaultFieldValue;
for (const option of selectElement.options) {
option.selected = option.value === defaultValue;
}
});
for (const option of this.data.options) {
const optionElement = document.createElement("option");
optionElement.textContent = option.displayValue;
optionElement.value = option.exportValue;
if (storedData.value.includes(option.exportValue)) {
optionElement.setAttribute("selected", true);
addAnEmptyEntry = false;
}
selectElement.append(optionElement);
}
let removeEmptyEntry = null;
if (addAnEmptyEntry) {
const noneOptionElement = document.createElement("option");
noneOptionElement.value = " ";
noneOptionElement.setAttribute("hidden", true);
noneOptionElement.setAttribute("selected", true);
selectElement.prepend(noneOptionElement);
removeEmptyEntry = () => {
noneOptionElement.remove();
selectElement.removeEventListener("input", removeEmptyEntry);
removeEmptyEntry = null;
};
selectElement.addEventListener("input", removeEmptyEntry);
}
const getValue = (isExport) => {
const name = isExport ? "value" : "textContent";
const {
options,
multiple
} = selectElement;
if (!multiple) {
return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
}
return Array.prototype.filter.call(options, (option) => option.selected).map((option) => option[name]);
};
let selectedValues = getValue(false);
const getItems = (event) => {
const options = event.target.options;
return Array.prototype.map.call(options, (option) => ({
displayValue: option.textContent,
exportValue: option.value
}));
};
if (this.enableScripting && this.hasJSActions) {
selectElement.addEventListener("updatefromsandbox", (jsEvent) => {
const actions = {
value(event) {
removeEmptyEntry?.();
const value = event.detail.value;
const values2 = new Set(Array.isArray(value) ? value : [value]);
for (const option of selectElement.options) {
option.selected = values2.has(option.value);
}
storage2.setValue(id, {
value: getValue(true)
});
selectedValues = getValue(false);
},
multipleSelection(event) {
selectElement.multiple = true;
},
remove(event) {
const options = selectElement.options;
const index2 = event.detail.remove;
options[index2].selected = false;
selectElement.remove(index2);
if (options.length > 0) {
const i7 = Array.prototype.findIndex.call(options, (option) => option.selected);
if (i7 === -1) {
options[0].selected = true;
}
}
storage2.setValue(id, {
value: getValue(true),
items: getItems(event)
});
selectedValues = getValue(false);
},
clear(event) {
while (selectElement.length !== 0) {
selectElement.remove(0);
}
storage2.setValue(id, {
value: null,
items: []
});
selectedValues = getValue(false);
},
insert(event) {
const {
index: index2,
displayValue,
exportValue
} = event.detail.insert;
const selectChild = selectElement.children[index2];
const optionElement = document.createElement("option");
optionElement.textContent = displayValue;
optionElement.value = exportValue;
if (selectChild) {
selectChild.before(optionElement);
} else {
selectElement.append(optionElement);
}
storage2.setValue(id, {
value: getValue(true),
items: getItems(event)
});
selectedValues = getValue(false);
},
items(event) {
const {
items
} = event.detail;
while (selectElement.length !== 0) {
selectElement.remove(0);
}
for (const item of items) {
const {
displayValue,
exportValue
} = item;
const optionElement = document.createElement("option");
optionElement.textContent = displayValue;
optionElement.value = exportValue;
selectElement.append(optionElement);
}
if (selectElement.options.length > 0) {
selectElement.options[0].selected = true;
}
storage2.setValue(id, {
value: getValue(true),
items: getItems(event)
});
selectedValues = getValue(false);
},
indices(event) {
const indices = new Set(event.detail.indices);
for (const option of event.target.options) {
option.selected = indices.has(option.index);
}
storage2.setValue(id, {
value: getValue(true)
});
selectedValues = getValue(false);
},
editable(event) {
event.target.disabled = !event.detail.editable;
}
};
this._dispatchEventFromSandbox(actions, jsEvent);
});
selectElement.addEventListener("input", (event) => {
const exportValue = getValue(true);
const change = getValue(false);
storage2.setValue(id, {
value: exportValue
});
event.preventDefault();
this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
source: this,
detail: {
id,
name: "Keystroke",
value: selectedValues,
change,
changeEx: exportValue,
willCommit: false,
commitKey: 1,
keyDown: false
}
});
});
this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], (event) => event.target.value);
} else {
selectElement.addEventListener("input", function(event) {
storage2.setValue(id, {
value: getValue(true)
});
});
}
if (this.data.combo) {
this._setTextStyle(selectElement);
} else {
}
this._setBackgroundColor(selectElement);
this._setDefaultPropertiesFromJS(selectElement);
this.container.append(selectElement);
return this.container;
}
};
PopupAnnotationElement = class extends AnnotationElement {
constructor(parameters) {
const {
data,
elements: elements2,
parent
} = parameters;
const hasCommentManager = !!parent._commentManager;
super(parameters, {
isRenderable: !hasCommentManager && AnnotationElement._hasPopupData(data)
});
this.elements = elements2;
if (hasCommentManager && AnnotationElement._hasPopupData(data)) {
const popup = this.popup = this.#createPopup();
for (const element of elements2) {
element.popup = popup;
}
} else {
this.popup = null;
}
}
#createPopup() {
return new PopupElement({
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() {
const {
container
} = this;
container.classList.add("popupAnnotation");
container.role = "comment";
const popup = this.popup = this.#createPopup();
const elementIds = [];
for (const element of this.elements) {
element.popup = popup;
element.container.ariaHasPopup = "dialog";
elementIds.push(element.data.id);
element.addHighlightArea();
}
this.container.setAttribute("aria-controls", elementIds.map((id) => `${AnnotationPrefix}${id}`).join(","));
return this.container;
}
};
PopupElement = class {
#commentManager = null;
#boundKeyDown = this.#keyDown.bind(this);
#boundHide = this.#hide.bind(this);
#boundShow = this.#show.bind(this);
#boundToggle = this.#toggle.bind(this);
#color = null;
#container = null;
#contentsObj = null;
#dateObj = null;
#elements = null;
#parent = null;
#parentRect = null;
#pinned = false;
#popup = null;
#popupAbortController = null;
#position = null;
#commentButton = null;
#commentButtonPosition = null;
#popupPosition = null;
#rect = null;
#richText = null;
#titleObj = null;
#updates = null;
#wasVisible = false;
#firstElement = null;
#commentText = null;
constructor({
container,
color: color2,
elements: elements2,
titleObj,
modificationDate,
contentsObj,
richText,
parent,
rect,
parentRect,
open: open2,
commentManager = null
}) {
this.#container = container;
this.#titleObj = titleObj;
this.#contentsObj = contentsObj;
this.#richText = richText;
this.#parent = parent;
this.#color = color2;
this.#rect = rect;
this.#parentRect = parentRect;
this.#elements = elements2;
this.#commentManager = commentManager;
this.#firstElement = elements2[0];
this.#dateObj = PDFDateString.toDateObject(modificationDate);
this.trigger = elements2.flatMap((e9) => e9.getElementsToTriggerPopup());
if (!commentManager) {
this.#addEventListeners();
this.#container.hidden = true;
if (open2) {
this.#toggle();
}
}
}
#addEventListeners() {
if (this.#popupAbortController) {
return;
}
this.#popupAbortController = new AbortController();
const {
signal
} = this.#popupAbortController;
for (const element of this.trigger) {
element.addEventListener("click", this.#boundToggle, {
signal
});
element.addEventListener("pointerenter", this.#boundShow, {
signal
});
element.addEventListener("pointerleave", this.#boundHide, {
signal
});
element.classList.add("popupTriggerArea");
}
for (const element of this.#elements) {
element.container?.addEventListener("keydown", this.#boundKeyDown, {
signal
});
}
}
#setCommentButtonPosition() {
const element = this.#elements.find((e9) => e9.hasCommentButton);
if (!element) {
return;
}
this.#commentButtonPosition = element._normalizePoint(element.commentButtonPosition);
}
renderCommentButton() {
if (this.#commentButton) {
if (!this.#commentButton.parentNode) {
this.#firstElement.container.after(this.#commentButton);
}
return;
}
if (!this.#commentButtonPosition) {
this.#setCommentButtonPosition();
}
if (!this.#commentButtonPosition) {
return;
}
const {
signal
} = this.#popupAbortController = new AbortController();
const hasOwnButton = this.#firstElement.hasOwnCommentButton;
const togglePopup = () => {
this.#commentManager.toggleCommentPopup(this, true, void 0, !hasOwnButton);
};
const showPopup = () => {
this.#commentManager.toggleCommentPopup(this, false, true, !hasOwnButton);
};
const hidePopup = () => {
this.#commentManager.toggleCommentPopup(this, false, false);
};
if (!hasOwnButton) {
const button = this.#commentButton = document.createElement("button");
button.className = "annotationCommentButton";
const parentContainer = this.#firstElement.container;
button.style.zIndex = parentContainer.style.zIndex + 1;
button.tabIndex = 0;
button.ariaHasPopup = "dialog";
button.ariaControls = "commentPopup";
button.setAttribute("data-l10n-id", "pdfjs-show-comment-button");
this.#updateColor();
this.#updateCommentButtonPosition();
button.addEventListener("keydown", this.#boundKeyDown, {
signal
});
button.addEventListener("click", togglePopup, {
signal
});
button.addEventListener("pointerenter", showPopup, {
signal
});
button.addEventListener("pointerleave", hidePopup, {
signal
});
parentContainer.after(button);
} else {
this.#commentButton = this.#firstElement.container;
for (const element of this.trigger) {
element.ariaHasPopup = "dialog";
element.ariaControls = "commentPopup";
element.addEventListener("keydown", this.#boundKeyDown, {
signal
});
element.addEventListener("click", togglePopup, {
signal
});
element.addEventListener("pointerenter", showPopup, {
signal
});
element.addEventListener("pointerleave", hidePopup, {
signal
});
element.classList.add("popupTriggerArea");
}
}
}
#updateCommentButtonPosition() {
if (this.#firstElement.extraPopupElement && !this.#firstElement.editor) {
return;
}
if (!this.#commentButton) {
this.renderCommentButton();
}
const [x2, y4] = this.#commentButtonPosition;
const {
style
} = this.#commentButton;
style.left = `calc(${x2}%)`;
style.top = `calc(${y4}% - var(--comment-button-dim))`;
}
#updateColor() {
if (this.#firstElement.extraPopupElement) {
return;
}
if (!this.#commentButton) {
this.renderCommentButton();
}
this.#commentButton.style.backgroundColor = this.commentButtonColor || "";
}
get commentButtonColor() {
const {
color: color2,
opacity
} = this.#firstElement.commentData;
if (!color2) {
return null;
}
return this.#parent._commentManager.makeCommentColor(color2, opacity);
}
focusCommentButton() {
setTimeout(() => {
this.#commentButton?.focus();
}, 0);
}
getData() {
const {
richText,
color: color2,
opacity,
creationDate,
modificationDate
} = this.#firstElement.commentData;
return {
contentsObj: {
str: this.comment
},
richText,
color: color2,
opacity,
creationDate,
modificationDate
};
}
get elementBeforePopup() {
return this.#commentButton;
}
get comment() {
this.#commentText ||= this.#firstElement.commentText;
return this.#commentText;
}
set comment(text3) {
if (text3 === this.comment) {
return;
}
this.#firstElement.commentText = this.#commentText = text3;
}
focus() {
this.#firstElement.container?.focus();
}
get parentBoundingClientRect() {
return this.#firstElement.layer.getBoundingClientRect();
}
setCommentButtonStates({
selected,
hasPopup
}) {
if (!this.#commentButton) {
return;
}
this.#commentButton.classList.toggle("selected", selected);
this.#commentButton.ariaExpanded = hasPopup;
}
setSelectedCommentButton(selected) {
this.#commentButton.classList.toggle("selected", selected);
}
get commentPopupPosition() {
if (this.#popupPosition) {
return this.#popupPosition;
}
const {
x: x2,
y: y4,
height
} = this.#commentButton.getBoundingClientRect();
const {
x: parentX,
y: parentY,
width: parentWidth,
height: parentHeight
} = this.#firstElement.layer.getBoundingClientRect();
return [(x2 - parentX) / parentWidth, (y4 + height - parentY) / parentHeight];
}
set commentPopupPosition(pos) {
this.#popupPosition = pos;
}
hasDefaultPopupPosition() {
return this.#popupPosition === null;
}
get commentButtonPosition() {
return this.#commentButtonPosition;
}
get commentButtonWidth() {
return this.#commentButton.getBoundingClientRect().width / this.parentBoundingClientRect.width;
}
editComment(options) {
const [posX, posY] = this.#popupPosition || this.commentButtonPosition.map((x2) => x2 / 100);
const parentDimensions = this.parentBoundingClientRect;
const {
x: parentX,
y: parentY,
width: parentWidth,
height: parentHeight
} = parentDimensions;
this.#commentManager.showDialog(null, this, parentX + posX * parentWidth, parentY + posY * parentHeight, {
...options,
parentDimensions
});
}
render() {
if (this.#popup) {
return;
}
const popup = this.#popup = document.createElement("div");
popup.className = "popup";
if (this.#color) {
const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color);
popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`;
}
const header = document.createElement("span");
header.className = "header";
if (this.#titleObj?.str) {
const title = document.createElement("span");
title.className = "title";
header.append(title);
({
dir: title.dir,
str: title.textContent
} = this.#titleObj);
}
popup.append(header);
if (this.#dateObj) {
const modificationDate = document.createElement("time");
modificationDate.className = "popupDate";
modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string");
modificationDate.setAttribute("data-l10n-args", JSON.stringify({
dateObj: this.#dateObj.valueOf()
}));
modificationDate.dateTime = this.#dateObj.toISOString();
header.append(modificationDate);
}
renderRichText({
html: this.#html || this.#contentsObj.str,
dir: this.#contentsObj?.dir,
className: "popupContent"
}, popup);
this.#container.append(popup);
}
get #html() {
const richText = this.#richText;
const contentsObj = this.#contentsObj;
if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) {
return this.#richText.html || null;
}
return null;
}
get #fontSize() {
return this.#html?.attributes?.style?.fontSize || 0;
}
get #fontColor() {
return this.#html?.attributes?.style?.color || null;
}
#makePopupContent(text3) {
const popupLines = [];
const popupContent = {
str: text3,
html: {
name: "div",
attributes: {
dir: "auto"
},
children: [{
name: "p",
children: popupLines
}]
}
};
const lineAttributes = {
style: {
color: this.#fontColor,
fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--total-scale-factor))` : ""
}
};
for (const line of text3.split("\n")) {
popupLines.push({
name: "span",
value: line,
attributes: lineAttributes
});
}
return popupContent;
}
#keyDown(event) {
if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
return;
}
if (event.key === "Enter" || event.key === "Escape" && this.#pinned) {
this.#toggle();
}
}
updateEdited({
rect,
popup,
deleted
}) {
if (this.#commentManager) {
if (deleted) {
this.remove();
this.#commentText = null;
} else if (popup) {
if (popup.deleted) {
this.remove();
} else {
this.#updateColor();
this.#commentText = popup.text;
}
}
if (rect) {
this.#commentButtonPosition = null;
this.#setCommentButtonPosition();
this.#updateCommentButtonPosition();
}
return;
}
if (deleted || popup?.deleted) {
this.remove();
return;
}
this.#addEventListeners();
this.#updates ||= {
contentsObj: this.#contentsObj,
richText: this.#richText
};
if (rect) {
this.#position = null;
}
if (popup && popup.text) {
this.#richText = this.#makePopupContent(popup.text);
this.#dateObj = PDFDateString.toDateObject(popup.date);
this.#contentsObj = null;
}
this.#popup?.remove();
this.#popup = null;
}
resetEdited() {
if (!this.#updates) {
return;
}
({
contentsObj: this.#contentsObj,
richText: this.#richText
} = this.#updates);
this.#updates = null;
this.#popup?.remove();
this.#popup = null;
this.#position = null;
}
remove() {
this.#popupAbortController?.abort();
this.#popupAbortController = null;
this.#popup?.remove();
this.#popup = null;
this.#wasVisible = false;
this.#pinned = false;
this.#commentButton?.remove();
this.#commentButton = null;
if (this.trigger) {
for (const element of this.trigger) {
element.classList.remove("popupTriggerArea");
}
}
}
#setPosition() {
if (this.#position !== null) {
return;
}
const {
page: {
view
},
viewport: {
rawDims: {
pageWidth,
pageHeight,
pageX,
pageY
}
}
} = this.#parent;
let useParentRect = !!this.#parentRect;
let rect = useParentRect ? this.#parentRect : this.#rect;
for (const element of this.#elements) {
if (!rect || Util.intersect(element.data.rect, rect) !== null) {
rect = element.data.rect;
useParentRect = true;
break;
}
}
const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]);
const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5;
const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0;
const popupLeft = normalizedRect[0] + parentWidth;
const popupTop = normalizedRect[1];
this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight];
const {
style
} = this.#container;
style.left = `${this.#position[0]}%`;
style.top = `${this.#position[1]}%`;
}
#toggle() {
if (this.#commentManager) {
this.#commentManager.toggleCommentPopup(this, false);
return;
}
this.#pinned = !this.#pinned;
if (this.#pinned) {
this.#show();
this.#container.addEventListener("click", this.#boundToggle);
this.#container.addEventListener("keydown", this.#boundKeyDown);
} else {
this.#hide();
this.#container.removeEventListener("click", this.#boundToggle);
this.#container.removeEventListener("keydown", this.#boundKeyDown);
}
}
#show() {
if (!this.#popup) {
this.render();
}
if (!this.isVisible) {
this.#setPosition();
this.#container.hidden = false;
this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1e3;
} else if (this.#pinned) {
this.#container.classList.add("focused");
}
}
#hide() {
this.#container.classList.remove("focused");
if (this.#pinned || !this.isVisible) {
return;
}
this.#container.hidden = true;
this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1e3;
}
forceHide() {
this.#wasVisible = this.isVisible;
if (!this.#wasVisible) {
return;
}
this.#container.hidden = true;
}
maybeShow() {
if (this.#commentManager) {
return;
}
this.#addEventListeners();
if (!this.#wasVisible) {
return;
}
if (!this.#popup) {
this.#show();
}
this.#wasVisible = false;
this.#container.hidden = false;
}
get isVisible() {
if (this.#commentManager) {
return false;
}
return this.#container.hidden === false;
}
};
FreeTextAnnotationElement = class extends AnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true
});
this.textContent = parameters.data.textContent;
this.textPosition = parameters.data.textPosition;
this.annotationEditorType = AnnotationEditorType.FREETEXT;
}
render() {
this.container.classList.add("freeTextAnnotation");
if (this.textContent) {
const content = this.contentElement = document.createElement("div");
content.classList.add("annotationTextContent");
content.setAttribute("role", "comment");
for (const line of this.textContent) {
const lineSpan = document.createElement("span");
lineSpan.textContent = line;
content.append(lineSpan);
}
this.container.append(content);
}
if (!this.data.popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
this._editOnDoubleClick();
return this.container;
}
};
LineAnnotationElement = class extends AnnotationElement {
#line = null;
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true
});
}
render() {
this.container.classList.add("lineAnnotation");
const {
data,
width,
height
} = this;
const svg = this.svgFactory.create(width, height, true);
const line = this.#line = this.svgFactory.createElement("svg:line");
line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
line.setAttribute("stroke-width", data.borderStyle.width || 1);
line.setAttribute("stroke", "transparent");
line.setAttribute("fill", "transparent");
svg.append(line);
this.container.append(svg);
if (!data.popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
return this.container;
}
getElementsToTriggerPopup() {
return this.#line;
}
addHighlightArea() {
this.container.classList.add("highlightArea");
}
};
SquareAnnotationElement = class extends AnnotationElement {
#square = null;
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true
});
}
render() {
this.container.classList.add("squareAnnotation");
const {
data,
width,
height
} = this;
const svg = this.svgFactory.create(width, height, true);
const borderWidth = data.borderStyle.width;
const square = this.#square = this.svgFactory.createElement("svg:rect");
square.setAttribute("x", borderWidth / 2);
square.setAttribute("y", borderWidth / 2);
square.setAttribute("width", width - borderWidth);
square.setAttribute("height", height - borderWidth);
square.setAttribute("stroke-width", borderWidth || 1);
square.setAttribute("stroke", "transparent");
square.setAttribute("fill", "transparent");
svg.append(square);
this.container.append(svg);
if (!data.popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
return this.container;
}
getElementsToTriggerPopup() {
return this.#square;
}
addHighlightArea() {
this.container.classList.add("highlightArea");
}
};
CircleAnnotationElement = class extends AnnotationElement {
#circle = null;
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true
});
}
render() {
this.container.classList.add("circleAnnotation");
const {
data,
width,
height
} = this;
const svg = this.svgFactory.create(width, height, true);
const borderWidth = data.borderStyle.width;
const circle = this.#circle = this.svgFactory.createElement("svg:ellipse");
circle.setAttribute("cx", width / 2);
circle.setAttribute("cy", height / 2);
circle.setAttribute("rx", width / 2 - borderWidth / 2);
circle.setAttribute("ry", height / 2 - borderWidth / 2);
circle.setAttribute("stroke-width", borderWidth || 1);
circle.setAttribute("stroke", "transparent");
circle.setAttribute("fill", "transparent");
svg.append(circle);
this.container.append(svg);
if (!data.popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
return this.container;
}
getElementsToTriggerPopup() {
return this.#circle;
}
addHighlightArea() {
this.container.classList.add("highlightArea");
}
};
PolylineAnnotationElement = class extends AnnotationElement {
#polyline = null;
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true
});
this.containerClassName = "polylineAnnotation";
this.svgElementName = "svg:polyline";
}
render() {
this.container.classList.add(this.containerClassName);
const {
data: {
rect,
vertices,
borderStyle,
popupRef
},
width,
height
} = this;
if (!vertices) {
return this.container;
}
const svg = this.svgFactory.create(width, height, true);
let points = [];
for (let i7 = 0, ii = vertices.length; i7 < ii; i7 += 2) {
const x2 = vertices[i7] - rect[0];
const y4 = rect[3] - vertices[i7 + 1];
points.push(`${x2},${y4}`);
}
points = points.join(" ");
const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName);
polyline.setAttribute("points", points);
polyline.setAttribute("stroke-width", borderStyle.width || 1);
polyline.setAttribute("stroke", "transparent");
polyline.setAttribute("fill", "transparent");
svg.append(polyline);
this.container.append(svg);
if (!popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
return this.container;
}
getElementsToTriggerPopup() {
return this.#polyline;
}
addHighlightArea() {
this.container.classList.add("highlightArea");
}
};
PolygonAnnotationElement = class extends PolylineAnnotationElement {
constructor(parameters) {
super(parameters);
this.containerClassName = "polygonAnnotation";
this.svgElementName = "svg:polygon";
}
};
CaretAnnotationElement = class extends AnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true
});
}
render() {
this.container.classList.add("caretAnnotation");
if (!this.data.popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
return this.container;
}
};
InkAnnotationElement = class extends AnnotationElement {
#polylinesGroupElement = null;
#polylines = [];
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true
});
this.containerClassName = "inkAnnotation";
this.svgElementName = "svg:polyline";
this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK;
}
#getTransform(rotation, rect) {
switch (rotation) {
case 90:
return {
transform: `rotate(90) translate(${-rect[0]},${rect[1]}) scale(1,-1)`,
width: rect[3] - rect[1],
height: rect[2] - rect[0]
};
case 180:
return {
transform: `rotate(180) translate(${-rect[2]},${rect[1]}) scale(1,-1)`,
width: rect[2] - rect[0],
height: rect[3] - rect[1]
};
case 270:
return {
transform: `rotate(270) translate(${-rect[2]},${rect[3]}) scale(1,-1)`,
width: rect[3] - rect[1],
height: rect[2] - rect[0]
};
default:
return {
transform: `translate(${-rect[0]},${rect[3]}) scale(1,-1)`,
width: rect[2] - rect[0],
height: rect[3] - rect[1]
};
}
}
render() {
this.container.classList.add(this.containerClassName);
const {
data: {
rect,
rotation,
inkLists,
borderStyle,
popupRef
}
} = this;
const {
transform,
width,
height
} = this.#getTransform(rotation, rect);
const svg = this.svgFactory.create(width, height, true);
const g3 = this.#polylinesGroupElement = this.svgFactory.createElement("svg:g");
svg.append(g3);
g3.setAttribute("stroke-width", borderStyle.width || 1);
g3.setAttribute("stroke-linecap", "round");
g3.setAttribute("stroke-linejoin", "round");
g3.setAttribute("stroke-miterlimit", 10);
g3.setAttribute("stroke", "transparent");
g3.setAttribute("fill", "transparent");
g3.setAttribute("transform", transform);
for (let i7 = 0, ii = inkLists.length; i7 < ii; i7++) {
const polyline = this.svgFactory.createElement(this.svgElementName);
this.#polylines.push(polyline);
polyline.setAttribute("points", inkLists[i7].join(","));
g3.append(polyline);
}
if (!popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
this.container.append(svg);
this._editOnDoubleClick();
return this.container;
}
updateEdited(params) {
super.updateEdited(params);
const {
thickness,
points,
rect
} = params;
const g3 = this.#polylinesGroupElement;
if (thickness >= 0) {
g3.setAttribute("stroke-width", thickness || 1);
}
if (points) {
for (let i7 = 0, ii = this.#polylines.length; i7 < ii; i7++) {
this.#polylines[i7].setAttribute("points", points[i7].join(","));
}
}
if (rect) {
const {
transform,
width,
height
} = this.#getTransform(this.data.rotation, rect);
const root = g3.parentElement;
root.setAttribute("viewBox", `0 0 ${width} ${height}`);
g3.setAttribute("transform", transform);
}
}
getElementsToTriggerPopup() {
return this.#polylines;
}
addHighlightArea() {
this.container.classList.add("highlightArea");
}
};
HighlightAnnotationElement = class extends AnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true,
createQuadrilaterals: true
});
this.annotationEditorType = AnnotationEditorType.HIGHLIGHT;
}
render() {
const {
data: {
overlaidText,
popupRef
}
} = this;
if (!popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
this.container.classList.add("highlightAnnotation");
this._editOnDoubleClick();
if (overlaidText) {
const mark = document.createElement("mark");
mark.classList.add("overlaidText");
mark.textContent = overlaidText;
this.container.append(mark);
}
return this.container;
}
};
UnderlineAnnotationElement = class extends AnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true,
createQuadrilaterals: true
});
}
render() {
const {
data: {
overlaidText,
popupRef
}
} = this;
if (!popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
this.container.classList.add("underlineAnnotation");
if (overlaidText) {
const underline = document.createElement("u");
underline.classList.add("overlaidText");
underline.textContent = overlaidText;
this.container.append(underline);
}
return this.container;
}
};
SquigglyAnnotationElement = class extends AnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true,
createQuadrilaterals: true
});
}
render() {
const {
data: {
overlaidText,
popupRef
}
} = this;
if (!popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
this.container.classList.add("squigglyAnnotation");
if (overlaidText) {
const underline = document.createElement("u");
underline.classList.add("overlaidText");
underline.textContent = overlaidText;
this.container.append(underline);
}
return this.container;
}
};
StrikeOutAnnotationElement = class extends AnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true,
createQuadrilaterals: true
});
}
render() {
const {
data: {
overlaidText,
popupRef
}
} = this;
if (!popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
this.container.classList.add("strikeoutAnnotation");
if (overlaidText) {
const strikeout = document.createElement("s");
strikeout.classList.add("overlaidText");
strikeout.textContent = overlaidText;
this.container.append(strikeout);
}
return this.container;
}
};
StampAnnotationElement = class extends AnnotationElement {
constructor(parameters) {
super(parameters, {
isRenderable: true,
ignoreBorder: true
});
this.annotationEditorType = AnnotationEditorType.STAMP;
}
render() {
this.container.classList.add("stampAnnotation");
this.container.setAttribute("role", "img");
if (!this.data.popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
}
this._editOnDoubleClick();
return this.container;
}
};
FileAttachmentAnnotationElement = class extends AnnotationElement {
#trigger = null;
constructor(parameters) {
super(parameters, {
isRenderable: true
});
const {
file
} = this.data;
this.filename = file.filename;
this.content = file.content;
this.linkService.eventBus?.dispatch("fileattachmentannotation", {
source: this,
...file
});
}
render() {
this.container.classList.add("fileAttachmentAnnotation");
const {
container,
data
} = this;
let trigger;
if (data.hasAppearance || data.fillAlpha === 0) {
trigger = document.createElement("div");
} else {
trigger = document.createElement("img");
trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`;
if (data.fillAlpha && data.fillAlpha < 1) {
trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`;
}
}
trigger.addEventListener("dblclick", this.#download.bind(this));
this.#trigger = trigger;
const {
isMac
} = util_FeatureTest.platform;
container.addEventListener("keydown", (evt) => {
if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) {
this.#download();
}
});
if (!data.popupRef && this.hasPopupData) {
this.hasOwnCommentButton = true;
this._createPopup();
} else {
trigger.classList.add("popupTriggerArea");
}
container.append(trigger);
return container;
}
getElementsToTriggerPopup() {
return this.#trigger;
}
addHighlightArea() {
this.container.classList.add("highlightArea");
}
#download() {
this.downloadManager?.openOrDownloadData(this.content, this.filename);
}
};
AnnotationLayer = class _AnnotationLayer {
#accessibilityManager = null;
#annotationCanvasMap = null;
#annotationStorage = null;
#editableAnnotations = /* @__PURE__ */ new Map();
#structTreeLayer = null;
#linkService = null;
#elements = [];
#hasAriaAttributesFromStructTree = false;
constructor({
div,
accessibilityManager,
annotationCanvasMap,
annotationEditorUIManager,
page,
viewport,
structTreeLayer,
commentManager,
linkService,
annotationStorage
}) {
this.div = div;
this.#accessibilityManager = accessibilityManager;
this.#annotationCanvasMap = annotationCanvasMap;
this.#structTreeLayer = structTreeLayer || null;
this.#linkService = linkService || null;
this.#annotationStorage = annotationStorage || new AnnotationStorage();
this.page = page;
this.viewport = viewport;
this.zIndex = 0;
this._annotationEditorUIManager = annotationEditorUIManager;
this._commentManager = commentManager || null;
}
hasEditableAnnotations() {
return this.#editableAnnotations.size > 0;
}
async render(params) {
const {
annotations
} = params;
const layer = this.div;
setLayerDimensions(layer, this.viewport);
const popupToElements = /* @__PURE__ */ new Map();
const popupAnnotations = [];
const elementParams = {
data: null,
layer,
linkService: this.#linkService,
downloadManager: params.downloadManager,
imageResourcesPath: params.imageResourcesPath || "",
renderForms: params.renderForms !== false,
svgFactory: new DOMSVGFactory(),
annotationStorage: this.#annotationStorage,
enableComment: params.enableComment === true,
enableScripting: params.enableScripting === true,
hasJSActions: params.hasJSActions,
fieldObjects: params.fieldObjects,
parent: this,
elements: null
};
for (const data of annotations) {
if (data.noHTML) {
continue;
}
const isPopupAnnotation = data.annotationType === AnnotationType.POPUP;
if (!isPopupAnnotation) {
if (data.rect[2] === data.rect[0] || data.rect[3] === data.rect[1]) {
continue;
}
} else {
const elements2 = popupToElements.get(data.id);
if (!elements2) {
continue;
}
if (!this._commentManager) {
popupAnnotations.push(data);
continue;
}
elementParams.elements = elements2;
}
elementParams.data = data;
const element = AnnotationElementFactory.create(elementParams);
if (!element.isRenderable) {
continue;
}
if (!isPopupAnnotation) {
this.#elements.push(element);
if (data.popupRef) {
const elements2 = popupToElements.get(data.popupRef);
if (!elements2) {
popupToElements.set(data.popupRef, [element]);
} else {
elements2.push(element);
}
}
}
const rendered = element.render();
if (data.hidden) {
rendered.style.visibility = "hidden";
}
if (element._isEditable) {
this.#editableAnnotations.set(element.data.id, element);
this._annotationEditorUIManager?.renderAnnotationElement(element);
}
}
await this.#addElementsToDOM();
for (const data of popupAnnotations) {
const elements2 = elementParams.elements = popupToElements.get(data.id);
elementParams.data = data;
const element = AnnotationElementFactory.create(elementParams);
if (!element.isRenderable) {
continue;
}
const rendered = element.render();
element.contentElement.id = `${AnnotationPrefix}${data.id}`;
if (data.hidden) {
rendered.style.visibility = "hidden";
}
elements2.at(-1).container.after(rendered);
}
this.#setAnnotationCanvasMap();
}
async #addElementsToDOM() {
if (this.#elements.length === 0) {
return;
}
this.div.replaceChildren();
const promises = [];
if (!this.#hasAriaAttributesFromStructTree) {
this.#hasAriaAttributesFromStructTree = true;
for (const {
contentElement,
data: {
id
}
} of this.#elements) {
const annotationId = contentElement.id = `${AnnotationPrefix}${id}`;
promises.push(this.#structTreeLayer?.getAriaAttributes(annotationId).then((ariaAttributes) => {
if (ariaAttributes) {
for (const [key, value] of ariaAttributes) {
contentElement.setAttribute(key, value);
}
}
}));
}
}
this.#elements.sort(({
data: {
rect: [a0, a1, a22, a3]
}
}, {
data: {
rect: [b0, b1, b22, b32]
}
}) => {
if (a0 === a22 && a1 === a3) {
return 1;
}
if (b0 === b22 && b1 === b32) {
return -1;
}
const top1 = a3;
const bot1 = a1;
const mid1 = (a1 + a3) / 2;
const top2 = b32;
const bot2 = b1;
const mid2 = (b1 + b32) / 2;
if (mid1 >= top2 && mid2 <= bot1) {
return -1;
}
if (mid2 >= top1 && mid1 <= bot2) {
return 1;
}
const centerX1 = (a0 + a22) / 2;
const centerX2 = (b0 + b22) / 2;
return centerX1 - centerX2;
});
const fragment2 = document.createDocumentFragment();
for (const element of this.#elements) {
fragment2.append(element.container);
if (this._commentManager) {
(element.extraPopupElement?.popup || element.popup)?.renderCommentButton();
} else if (element.extraPopupElement) {
fragment2.append(element.extraPopupElement.render());
}
}
this.div.append(fragment2);
await Promise.all(promises);
if (this.#accessibilityManager) {
for (const element of this.#elements) {
this.#accessibilityManager.addPointerInTextLayer(element.contentElement, false);
}
}
}
async addLinkAnnotations(annotations) {
const elementParams = {
data: null,
layer: this.div,
linkService: this.#linkService,
svgFactory: new DOMSVGFactory(),
parent: this
};
for (const data of annotations) {
data.borderStyle ||= _AnnotationLayer._defaultBorderStyle;
elementParams.data = data;
const element = AnnotationElementFactory.create(elementParams);
if (!element.isRenderable) {
continue;
}
element.render();
element.contentElement.id = `${AnnotationPrefix}${data.id}`;
this.#elements.push(element);
}
await this.#addElementsToDOM();
}
update({
viewport
}) {
const layer = this.div;
this.viewport = viewport;
setLayerDimensions(layer, {
rotation: viewport.rotation
});
this.#setAnnotationCanvasMap();
layer.hidden = false;
}
#setAnnotationCanvasMap() {
if (!this.#annotationCanvasMap) {
return;
}
const layer = this.div;
for (const [id, canvas] of this.#annotationCanvasMap) {
const element = layer.querySelector(`[data-annotation-id="${id}"]`);
if (!element) {
continue;
}
canvas.className = "annotationContent";
const {
firstChild
} = element;
if (!firstChild) {
element.append(canvas);
} else if (firstChild.nodeName === "CANVAS") {
firstChild.replaceWith(canvas);
} else if (!firstChild.classList.contains("annotationContent")) {
firstChild.before(canvas);
} else {
firstChild.after(canvas);
}
const editableAnnotation = this.#editableAnnotations.get(id);
if (!editableAnnotation) {
continue;
}
if (editableAnnotation._hasNoCanvas) {
this._annotationEditorUIManager?.setMissingCanvas(id, element.id, canvas);
editableAnnotation._hasNoCanvas = false;
} else {
editableAnnotation.canvas = canvas;
}
}
this.#annotationCanvasMap.clear();
}
getEditableAnnotations() {
return Array.from(this.#editableAnnotations.values());
}
getEditableAnnotation(id) {
return this.#editableAnnotations.get(id);
}
addFakeAnnotation(editor) {
const {
div
} = this;
const {
id,
rotation
} = editor;
const element = new EditorAnnotationElement({
data: {
id,
rect: editor.getPDFRect(),
rotation
},
editor,
layer: div,
parent: this,
enableComment: !!this._commentManager,
linkService: this.#linkService,
annotationStorage: this.#annotationStorage
});
element.render();
element.contentElement.id = `${AnnotationPrefix}${id}`;
element.createOrUpdatePopup();
this.#elements.push(element);
return element;
}
removeAnnotation(id) {
const index2 = this.#elements.findIndex((el) => el.data.id === id);
if (index2 < 0) {
return;
}
const [element] = this.#elements.splice(index2, 1);
this.#accessibilityManager?.removePointerInTextLayer(element.contentElement);
}
updateFakeAnnotations(editors) {
if (editors.length === 0) {
return;
}
for (const editor of editors) {
editor.updateFakeAnnotationElement(this);
}
this.#addElementsToDOM();
}
togglePointerEvents(enabled = false) {
this.div.classList.toggle("disabled", !enabled);
}
static get _defaultBorderStyle() {
return shadow(this, "_defaultBorderStyle", Object.freeze({
width: 1,
rawWidth: 1,
style: AnnotationBorderStyleType.SOLID,
dashArray: [3],
horizontalCornerRadius: 0,
verticalCornerRadius: 0
}));
}
};
EOL_PATTERN = /\r\n?|\n/g;
FreeTextEditor = class _FreeTextEditor extends AnnotationEditor {
#content = "";
#editorDivId = `${this.id}-editor`;
#editModeAC = null;
#fontSize;
_colorPicker = null;
static _freeTextDefaultContent = "";
static _internalPadding = 0;
static _defaultColor = null;
static _defaultFontSize = 10;
static get _keyboardManager() {
const proto = _FreeTextEditor.prototype;
const arrowChecker = (self2) => self2.isEmpty();
const small = AnnotationEditorUIManager.TRANSLATE_SMALL;
const big = AnnotationEditorUIManager.TRANSLATE_BIG;
return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, {
bubbles: true
}], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, {
args: [-small, 0],
checker: arrowChecker
}], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, {
args: [-big, 0],
checker: arrowChecker
}], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, {
args: [small, 0],
checker: arrowChecker
}], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, {
args: [big, 0],
checker: arrowChecker
}], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, {
args: [0, -small],
checker: arrowChecker
}], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, {
args: [0, -big],
checker: arrowChecker
}], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, {
args: [0, small],
checker: arrowChecker
}], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, {
args: [0, big],
checker: arrowChecker
}]]));
}
static _type = "freetext";
static _editorType = AnnotationEditorType.FREETEXT;
constructor(params) {
super({
...params,
name: "freeTextEditor"
});
this.color = params.color || _FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor;
this.#fontSize = params.fontSize || _FreeTextEditor._defaultFontSize;
if (!this.annotationElementId) {
this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert");
}
this.canAddComment = false;
}
static initialize(l10n, uiManager) {
AnnotationEditor.initialize(l10n, uiManager);
const style = getComputedStyle(document.documentElement);
this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
}
static updateDefaultParams(type, value) {
switch (type) {
case AnnotationEditorParamsType.FREETEXT_SIZE:
_FreeTextEditor._defaultFontSize = value;
break;
case AnnotationEditorParamsType.FREETEXT_COLOR:
_FreeTextEditor._defaultColor = value;
break;
}
}
updateParams(type, value) {
switch (type) {
case AnnotationEditorParamsType.FREETEXT_SIZE:
this.#updateFontSize(value);
break;
case AnnotationEditorParamsType.FREETEXT_COLOR:
this.#updateColor(value);
break;
}
}
static get defaultPropertiesToUpdate() {
return [[AnnotationEditorParamsType.FREETEXT_SIZE, _FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, _FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]];
}
get propertiesToUpdate() {
return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.color]];
}
get toolbarButtons() {
this._colorPicker ||= new BasicColorPicker(this);
return [["colorPicker", this._colorPicker]];
}
get colorType() {
return AnnotationEditorParamsType.FREETEXT_COLOR;
}
#updateFontSize(fontSize) {
const setFontsize = (size) => {
this.editorDiv.style.fontSize = `calc(${size}px * var(--total-scale-factor))`;
this.translate(0, -(size - this.#fontSize) * this.parentScale);
this.#fontSize = size;
this.#setEditorDimensions();
};
const savedFontsize = this.#fontSize;
this.addCommands({
cmd: setFontsize.bind(this, fontSize),
undo: setFontsize.bind(this, savedFontsize),
post: this._uiManager.updateUI.bind(this._uiManager, this),
mustExec: true,
type: AnnotationEditorParamsType.FREETEXT_SIZE,
overwriteIfSameType: true,
keepUndo: true
});
}
onUpdatedColor() {
this.editorDiv.style.color = this.color;
this._colorPicker?.update(this.color);
super.onUpdatedColor();
}
#updateColor(color2) {
const setColor = (col) => {
this.color = col;
this.onUpdatedColor();
};
const savedColor = this.color;
this.addCommands({
cmd: setColor.bind(this, color2),
undo: setColor.bind(this, savedColor),
post: this._uiManager.updateUI.bind(this._uiManager, this),
mustExec: true,
type: AnnotationEditorParamsType.FREETEXT_COLOR,
overwriteIfSameType: true,
keepUndo: true
});
}
_translateEmpty(x2, y4) {
this._uiManager.translateSelectedEditors(x2, y4, true);
}
getInitialTranslation() {
const scale = this.parentScale;
return [-_FreeTextEditor._internalPadding * scale, -(_FreeTextEditor._internalPadding + this.#fontSize) * scale];
}
rebuild() {
if (!this.parent) {
return;
}
super.rebuild();
if (this.div === null) {
return;
}
if (!this.isAttachedToDOM) {
this.parent.add(this);
}
}
enableEditMode() {
if (!super.enableEditMode()) {
return false;
}
this.overlayDiv.classList.remove("enabled");
this.editorDiv.contentEditable = true;
this._isDraggable = false;
this.div.removeAttribute("aria-activedescendant");
this.#editModeAC = new AbortController();
const signal = this._uiManager.combinedSignal(this.#editModeAC);
this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), {
signal
});
this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), {
signal
});
this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), {
signal
});
this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), {
signal
});
this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), {
signal
});
return true;
}
disableEditMode() {
if (!super.disableEditMode()) {
return false;
}
this.overlayDiv.classList.add("enabled");
this.editorDiv.contentEditable = false;
this.div.setAttribute("aria-activedescendant", this.#editorDivId);
this._isDraggable = true;
this.#editModeAC?.abort();
this.#editModeAC = null;
this.div.focus({
preventScroll: true
});
this.isEditing = false;
this.parent.div.classList.add("freetextEditing");
return true;
}
focusin(event) {
if (!this._focusEventsAllowed) {
return;
}
super.focusin(event);
if (event.target !== this.editorDiv) {
this.editorDiv.focus();
}
}
onceAdded(focus) {
if (this.width) {
return;
}
this.enableEditMode();
if (focus) {
this.editorDiv.focus();
}
if (this._initialOptions?.isCentered) {
this.center();
}
this._initialOptions = null;
}
isEmpty() {
return !this.editorDiv || this.editorDiv.innerText.trim() === "";
}
remove() {
this.isEditing = false;
if (this.parent) {
this.parent.setEditingState(true);
this.parent.div.classList.add("freetextEditing");
}
super.remove();
}
#extractText() {
const buffer = [];
this.editorDiv.normalize();
let prevChild = null;
for (const child of this.editorDiv.childNodes) {
if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") {
continue;
}
buffer.push(_FreeTextEditor.#getNodeContent(child));
prevChild = child;
}
return buffer.join("\n");
}
#setEditorDimensions() {
const [parentWidth, parentHeight] = this.parentDimensions;
let rect;
if (this.isAttachedToDOM) {
rect = this.div.getBoundingClientRect();
} else {
const {
currentLayer,
div
} = this;
const savedDisplay = div.style.display;
const savedVisibility = div.classList.contains("hidden");
div.classList.remove("hidden");
div.style.display = "hidden";
currentLayer.div.append(this.div);
rect = div.getBoundingClientRect();
div.remove();
div.style.display = savedDisplay;
div.classList.toggle("hidden", savedVisibility);
}
if (this.rotation % 180 === this.parentRotation % 180) {
this.width = rect.width / parentWidth;
this.height = rect.height / parentHeight;
} else {
this.width = rect.height / parentWidth;
this.height = rect.width / parentHeight;
}
this.fixAndSetPosition();
}
commit() {
if (!this.isInEditMode()) {
return;
}
super.commit();
this.disableEditMode();
const savedText = this.#content;
const newText = this.#content = this.#extractText().trimEnd();
if (savedText === newText) {
return;
}
const setText = (text3) => {
this.#content = text3;
if (!text3) {
this.remove();
return;
}
this.#setContent();
this._uiManager.rebuild(this);
this.#setEditorDimensions();
};
this.addCommands({
cmd: () => {
setText(newText);
},
undo: () => {
setText(savedText);
},
mustExec: false
});
this.#setEditorDimensions();
}
shouldGetKeyboardEvents() {
return this.isInEditMode();
}
enterInEditMode() {
this.enableEditMode();
this.editorDiv.focus();
}
keydown(event) {
if (event.target === this.div && event.key === "Enter") {
this.enterInEditMode();
event.preventDefault();
}
}
editorDivKeydown(event) {
_FreeTextEditor._keyboardManager.exec(this, event);
}
editorDivFocus(event) {
this.isEditing = true;
}
editorDivBlur(event) {
this.isEditing = false;
}
editorDivInput(event) {
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", true);
}
get canChangeContent() {
return true;
}
render() {
if (this.div) {
return this.div;
}
let baseX, baseY;
if (this._isCopy || this.annotationElementId) {
baseX = this.x;
baseY = this.y;
}
super.render();
this.editorDiv = document.createElement("div");
this.editorDiv.className = "internal";
this.editorDiv.setAttribute("id", this.#editorDivId);
this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text2");
this.editorDiv.setAttribute("data-l10n-attrs", "default-content");
this.enableEditing();
this.editorDiv.contentEditable = true;
const {
style
} = this.editorDiv;
style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`;
style.color = this.color;
this.div.append(this.editorDiv);
this.overlayDiv = document.createElement("div");
this.overlayDiv.classList.add("overlay", "enabled");
this.div.append(this.overlayDiv);
if (this._isCopy || this.annotationElementId) {
const [parentWidth, parentHeight] = this.parentDimensions;
if (this.annotationElementId) {
const {
position
} = this._initialData;
let [tx, ty] = this.getInitialTranslation();
[tx, ty] = this.pageTranslationToScreen(tx, ty);
const [pageWidth, pageHeight] = this.pageDimensions;
const [pageX, pageY] = this.pageTranslation;
let posX, posY;
switch (this.rotation) {
case 0:
posX = baseX + (position[0] - pageX) / pageWidth;
posY = baseY + this.height - (position[1] - pageY) / pageHeight;
break;
case 90:
posX = baseX + (position[0] - pageX) / pageWidth;
posY = baseY - (position[1] - pageY) / pageHeight;
[tx, ty] = [ty, -tx];
break;
case 180:
posX = baseX - this.width + (position[0] - pageX) / pageWidth;
posY = baseY - (position[1] - pageY) / pageHeight;
[tx, ty] = [-tx, -ty];
break;
case 270:
posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth;
posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight;
[tx, ty] = [-ty, tx];
break;
}
this.setAt(posX * parentWidth, posY * parentHeight, tx, ty);
} else {
this._moveAfterPaste(baseX, baseY);
}
this.#setContent();
this._isDraggable = true;
this.editorDiv.contentEditable = false;
} else {
this._isDraggable = false;
this.editorDiv.contentEditable = true;
}
return this.div;
}
static #getNodeContent(node) {
return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, "");
}
editorDivPaste(event) {
const clipboardData = event.clipboardData || window.clipboardData;
const {
types: types2
} = clipboardData;
if (types2.length === 1 && types2[0] === "text/plain") {
return;
}
event.preventDefault();
const paste = _FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n");
if (!paste) {
return;
}
const selection = window.getSelection();
if (!selection.rangeCount) {
return;
}
this.editorDiv.normalize();
selection.deleteFromDocument();
const range2 = selection.getRangeAt(0);
if (!paste.includes("\n")) {
range2.insertNode(document.createTextNode(paste));
this.editorDiv.normalize();
selection.collapseToStart();
return;
}
const {
startContainer,
startOffset
} = range2;
const bufferBefore = [];
const bufferAfter = [];
if (startContainer.nodeType === Node.TEXT_NODE) {
const parent = startContainer.parentElement;
bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, ""));
if (parent !== this.editorDiv) {
let buffer = bufferBefore;
for (const child of this.editorDiv.childNodes) {
if (child === parent) {
buffer = bufferAfter;
continue;
}
buffer.push(_FreeTextEditor.#getNodeContent(child));
}
}
bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, ""));
} else if (startContainer === this.editorDiv) {
let buffer = bufferBefore;
let i7 = 0;
for (const child of this.editorDiv.childNodes) {
if (i7++ === startOffset) {
buffer = bufferAfter;
}
buffer.push(_FreeTextEditor.#getNodeContent(child));
}
}
this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`;
this.#setContent();
const newRange = new Range();
let beforeLength = Math.sumPrecise(bufferBefore.map((line) => line.length));
for (const {
firstChild
} of this.editorDiv.childNodes) {
if (firstChild.nodeType === Node.TEXT_NODE) {
const length = firstChild.nodeValue.length;
if (beforeLength <= length) {
newRange.setStart(firstChild, beforeLength);
newRange.setEnd(firstChild, beforeLength);
break;
}
beforeLength -= length;
}
}
selection.removeAllRanges();
selection.addRange(newRange);
}
#setContent() {
this.editorDiv.replaceChildren();
if (!this.#content) {
return;
}
for (const line of this.#content.split("\n")) {
const div = document.createElement("div");
div.append(line ? document.createTextNode(line) : document.createElement("br"));
this.editorDiv.append(div);
}
}
#serializeContent() {
return this.#content.replaceAll("\xA0", " ");
}
static #deserializeContent(content) {
return content.replaceAll(" ", "\xA0");
}
get contentDiv() {
return this.editorDiv;
}
getPDFRect() {
const padding = _FreeTextEditor._internalPadding * this.parentScale;
return this.getRect(padding, padding);
}
static async deserialize(data, parent, uiManager) {
let initialData = null;
if (data instanceof FreeTextAnnotationElement) {
const {
data: {
defaultAppearanceData: {
fontSize,
fontColor
},
rect,
rotation,
id,
popupRef,
richText,
contentsObj,
creationDate,
modificationDate
},
textContent,
textPosition,
parent: {
page: {
pageNumber
}
}
} = data;
if (!textContent || textContent.length === 0) {
return null;
}
initialData = data = {
annotationType: AnnotationEditorType.FREETEXT,
color: Array.from(fontColor),
fontSize,
value: textContent.join("\n"),
position: textPosition,
pageIndex: pageNumber - 1,
rect: rect.slice(0),
rotation,
annotationElementId: id,
id,
deleted: false,
popupRef,
comment: contentsObj?.str || null,
richText,
creationDate,
modificationDate
};
}
const editor = await super.deserialize(data, parent, uiManager);
editor.#fontSize = data.fontSize;
editor.color = Util.makeHexColor(...data.color);
editor.#content = _FreeTextEditor.#deserializeContent(data.value);
editor._initialData = initialData;
if (data.comment) {
editor.setCommentData(data);
}
return editor;
}
serialize(isForCopying = false) {
if (this.isEmpty()) {
return null;
}
if (this.deleted) {
return this.serializeDeleted();
}
const color2 = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.color);
const serialized = Object.assign(super.serialize(isForCopying), {
color: color2,
fontSize: this.#fontSize,
value: this.#serializeContent()
});
this.addComment(serialized);
if (isForCopying) {
serialized.isCopy = true;
return serialized;
}
if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
return null;
}
serialized.id = this.annotationElementId;
return serialized;
}
#hasElementChanged(serialized) {
const {
value,
fontSize,
color: color2,
pageIndex
} = this._initialData;
return this.hasEditedComment || this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c6, i7) => c6 !== color2[i7]) || serialized.pageIndex !== pageIndex;
}
renderAnnotationElement(annotation) {
const content = super.renderAnnotationElement(annotation);
if (!content) {
return null;
}
const {
style
} = content;
style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`;
style.color = this.color;
content.replaceChildren();
for (const line of this.#content.split("\n")) {
const div = document.createElement("div");
div.append(line ? document.createTextNode(line) : document.createElement("br"));
content.append(div);
}
annotation.updateEdited({
rect: this.getPDFRect(),
popup: this._uiManager.hasCommentManager() || this.hasEditedComment ? this.comment : {
text: this.#content
}
});
return content;
}
resetAnnotationElement(annotation) {
super.resetAnnotationElement(annotation);
annotation.resetEdited();
}
};
Outline = class {
static PRECISION = 1e-4;
toSVGPath() {
unreachable("Abstract method `toSVGPath` must be implemented.");
}
get box() {
unreachable("Abstract getter `box` must be implemented.");
}
serialize(_bbox, _rotation) {
unreachable("Abstract method `serialize` must be implemented.");
}
static _rescale(src, tx, ty, sx, sy, dest) {
dest ||= new Float32Array(src.length);
for (let i7 = 0, ii = src.length; i7 < ii; i7 += 2) {
dest[i7] = tx + src[i7] * sx;
dest[i7 + 1] = ty + src[i7 + 1] * sy;
}
return dest;
}
static _rescaleAndSwap(src, tx, ty, sx, sy, dest) {
dest ||= new Float32Array(src.length);
for (let i7 = 0, ii = src.length; i7 < ii; i7 += 2) {
dest[i7] = tx + src[i7 + 1] * sx;
dest[i7 + 1] = ty + src[i7] * sy;
}
return dest;
}
static _translate(src, tx, ty, dest) {
dest ||= new Float32Array(src.length);
for (let i7 = 0, ii = src.length; i7 < ii; i7 += 2) {
dest[i7] = tx + src[i7];
dest[i7 + 1] = ty + src[i7 + 1];
}
return dest;
}
static svgRound(x2) {
return Math.round(x2 * 1e4);
}
static _normalizePoint(x2, y4, parentWidth, parentHeight, rotation) {
switch (rotation) {
case 90:
return [1 - y4 / parentWidth, x2 / parentHeight];
case 180:
return [1 - x2 / parentWidth, 1 - y4 / parentHeight];
case 270:
return [y4 / parentWidth, 1 - x2 / parentHeight];
default:
return [x2 / parentWidth, y4 / parentHeight];
}
}
static _normalizePagePoint(x2, y4, rotation) {
switch (rotation) {
case 90:
return [1 - y4, x2];
case 180:
return [1 - x2, 1 - y4];
case 270:
return [y4, 1 - x2];
default:
return [x2, y4];
}
}
static createBezierPoints(x1, y1, x2, y22, x3, y32) {
return [(x1 + 5 * x2) / 6, (y1 + 5 * y22) / 6, (5 * x2 + x3) / 6, (5 * y22 + y32) / 6, (x2 + x3) / 2, (y22 + y32) / 2];
}
};
FreeDrawOutliner = class _FreeDrawOutliner {
#box;
#bottom = [];
#innerMargin;
#isLTR;
#top = [];
#last = new Float32Array(18);
#lastX;
#lastY;
#min;
#min_dist;
#scaleFactor;
#thickness;
#points = [];
static #MIN_DIST = 8;
static #MIN_DIFF = 2;
static #MIN = _FreeDrawOutliner.#MIN_DIST + _FreeDrawOutliner.#MIN_DIFF;
constructor({
x: x2,
y: y4
}, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
this.#box = box;
this.#thickness = thickness * scaleFactor;
this.#isLTR = isLTR;
this.#last.set([NaN, NaN, NaN, NaN, x2, y4], 6);
this.#innerMargin = innerMargin;
this.#min_dist = _FreeDrawOutliner.#MIN_DIST * scaleFactor;
this.#min = _FreeDrawOutliner.#MIN * scaleFactor;
this.#scaleFactor = scaleFactor;
this.#points.push(x2, y4);
}
isEmpty() {
return isNaN(this.#last[8]);
}
#getLastCoords() {
const lastTop = this.#last.subarray(4, 6);
const lastBottom = this.#last.subarray(16, 18);
const [x2, y4, width, height] = this.#box;
return [(this.#lastX + (lastTop[0] - lastBottom[0]) / 2 - x2) / width, (this.#lastY + (lastTop[1] - lastBottom[1]) / 2 - y4) / height, (this.#lastX + (lastBottom[0] - lastTop[0]) / 2 - x2) / width, (this.#lastY + (lastBottom[1] - lastTop[1]) / 2 - y4) / height];
}
add({
x: x2,
y: y4
}) {
this.#lastX = x2;
this.#lastY = y4;
const [layerX, layerY, layerWidth, layerHeight] = this.#box;
let [x1, y1, x22, y22] = this.#last.subarray(8, 12);
const diffX = x2 - x22;
const diffY = y4 - y22;
const d4 = Math.hypot(diffX, diffY);
if (d4 < this.#min) {
return false;
}
const diffD = d4 - this.#min_dist;
const K2 = diffD / d4;
const shiftX = K2 * diffX;
const shiftY = K2 * diffY;
let x0 = x1;
let y0 = y1;
x1 = x22;
y1 = y22;
x22 += shiftX;
y22 += shiftY;
this.#points?.push(x2, y4);
const nX = -shiftY / diffD;
const nY = shiftX / diffD;
const thX = nX * this.#thickness;
const thY = nY * this.#thickness;
this.#last.set(this.#last.subarray(2, 8), 0);
this.#last.set([x22 + thX, y22 + thY], 4);
this.#last.set(this.#last.subarray(14, 18), 12);
this.#last.set([x22 - thX, y22 - thY], 16);
if (isNaN(this.#last[6])) {
if (this.#top.length === 0) {
this.#last.set([x1 + thX, y1 + thY], 2);
this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight);
this.#last.set([x1 - thX, y1 - thY], 14);
this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight);
}
this.#last.set([x0, y0, x1, y1, x22, y22], 6);
return !this.isEmpty();
}
this.#last.set([x0, y0, x1, y1, x22, y22], 6);
const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX));
if (angle < Math.PI / 2) {
[x1, y1, x22, y22] = this.#last.subarray(2, 6);
this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x22) / 2 - layerX) / layerWidth, ((y1 + y22) / 2 - layerY) / layerHeight);
[x1, y1, x0, y0] = this.#last.subarray(14, 18);
this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight);
return true;
}
[x0, y0, x1, y1, x22, y22] = this.#last.subarray(0, 6);
this.#top.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x22) / 6 - layerX) / layerWidth, ((5 * y1 + y22) / 6 - layerY) / layerHeight, ((x1 + x22) / 2 - layerX) / layerWidth, ((y1 + y22) / 2 - layerY) / layerHeight);
[x22, y22, x1, y1, x0, y0] = this.#last.subarray(12, 18);
this.#bottom.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x22) / 6 - layerX) / layerWidth, ((5 * y1 + y22) / 6 - layerY) / layerHeight, ((x1 + x22) / 2 - layerX) / layerWidth, ((y1 + y22) / 2 - layerY) / layerHeight);
return true;
}
toSVGPath() {
if (this.isEmpty()) {
return "";
}
const top = this.#top;
const bottom = this.#bottom;
if (isNaN(this.#last[6]) && !this.isEmpty()) {
return this.#toSVGPathTwoPoints();
}
const buffer = [];
buffer.push(`M${top[4]} ${top[5]}`);
for (let i7 = 6; i7 < top.length; i7 += 6) {
if (isNaN(top[i7])) {
buffer.push(`L${top[i7 + 4]} ${top[i7 + 5]}`);
} else {
buffer.push(`C${top[i7]} ${top[i7 + 1]} ${top[i7 + 2]} ${top[i7 + 3]} ${top[i7 + 4]} ${top[i7 + 5]}`);
}
}
this.#toSVGPathEnd(buffer);
for (let i7 = bottom.length - 6; i7 >= 6; i7 -= 6) {
if (isNaN(bottom[i7])) {
buffer.push(`L${bottom[i7 + 4]} ${bottom[i7 + 5]}`);
} else {
buffer.push(`C${bottom[i7]} ${bottom[i7 + 1]} ${bottom[i7 + 2]} ${bottom[i7 + 3]} ${bottom[i7 + 4]} ${bottom[i7 + 5]}`);
}
}
this.#toSVGPathStart(buffer);
return buffer.join(" ");
}
#toSVGPathTwoPoints() {
const [x2, y4, width, height] = this.#box;
const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
return `M${(this.#last[2] - x2) / width} ${(this.#last[3] - y4) / height} L${(this.#last[4] - x2) / width} ${(this.#last[5] - y4) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(this.#last[16] - x2) / width} ${(this.#last[17] - y4) / height} L${(this.#last[14] - x2) / width} ${(this.#last[15] - y4) / height} Z`;
}
#toSVGPathStart(buffer) {
const bottom = this.#bottom;
buffer.push(`L${bottom[4]} ${bottom[5]} Z`);
}
#toSVGPathEnd(buffer) {
const [x2, y4, width, height] = this.#box;
const lastTop = this.#last.subarray(4, 6);
const lastBottom = this.#last.subarray(16, 18);
const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
buffer.push(`L${(lastTop[0] - x2) / width} ${(lastTop[1] - y4) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(lastBottom[0] - x2) / width} ${(lastBottom[1] - y4) / height}`);
}
newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {
return new FreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR);
}
getOutlines() {
const top = this.#top;
const bottom = this.#bottom;
const last = this.#last;
const [layerX, layerY, layerWidth, layerHeight] = this.#box;
const points = new Float32Array((this.#points?.length ?? 0) + 2);
for (let i7 = 0, ii = points.length - 2; i7 < ii; i7 += 2) {
points[i7] = (this.#points[i7] - layerX) / layerWidth;
points[i7 + 1] = (this.#points[i7 + 1] - layerY) / layerHeight;
}
points[points.length - 2] = (this.#lastX - layerX) / layerWidth;
points[points.length - 1] = (this.#lastY - layerY) / layerHeight;
if (isNaN(last[6]) && !this.isEmpty()) {
return this.#getOutlineTwoPoints(points);
}
const outline = new Float32Array(this.#top.length + 24 + this.#bottom.length);
let N3 = top.length;
for (let i7 = 0; i7 < N3; i7 += 2) {
if (isNaN(top[i7])) {
outline[i7] = outline[i7 + 1] = NaN;
continue;
}
outline[i7] = top[i7];
outline[i7 + 1] = top[i7 + 1];
}
N3 = this.#getOutlineEnd(outline, N3);
for (let i7 = bottom.length - 6; i7 >= 6; i7 -= 6) {
for (let j3 = 0; j3 < 6; j3 += 2) {
if (isNaN(bottom[i7 + j3])) {
outline[N3] = outline[N3 + 1] = NaN;
N3 += 2;
continue;
}
outline[N3] = bottom[i7 + j3];
outline[N3 + 1] = bottom[i7 + j3 + 1];
N3 += 2;
}
}
this.#getOutlineStart(outline, N3);
return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
}
#getOutlineTwoPoints(points) {
const last = this.#last;
const [layerX, layerY, layerWidth, layerHeight] = this.#box;
const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
const outline = new Float32Array(36);
outline.set([NaN, NaN, NaN, NaN, (last[2] - layerX) / layerWidth, (last[3] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[4] - layerX) / layerWidth, (last[5] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (last[16] - layerX) / layerWidth, (last[17] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[14] - layerX) / layerWidth, (last[15] - layerY) / layerHeight], 0);
return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR);
}
#getOutlineStart(outline, pos) {
const bottom = this.#bottom;
outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], pos);
return pos += 6;
}
#getOutlineEnd(outline, pos) {
const lastTop = this.#last.subarray(4, 6);
const lastBottom = this.#last.subarray(16, 18);
const [layerX, layerY, layerWidth, layerHeight] = this.#box;
const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords();
outline.set([NaN, NaN, NaN, NaN, (lastTop[0] - layerX) / layerWidth, (lastTop[1] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (lastBottom[0] - layerX) / layerWidth, (lastBottom[1] - layerY) / layerHeight], pos);
return pos += 24;
}
};
FreeDrawOutline = class extends Outline {
#box;
#bbox = new Float32Array(4);
#innerMargin;
#isLTR;
#points;
#scaleFactor;
#outline;
constructor(outline, points, box, scaleFactor, innerMargin, isLTR) {
super();
this.#outline = outline;
this.#points = points;
this.#box = box;
this.#scaleFactor = scaleFactor;
this.#innerMargin = innerMargin;
this.#isLTR = isLTR;
this.firstPoint = [NaN, NaN];
this.lastPoint = [NaN, NaN];
this.#computeMinMax(isLTR);
const [x2, y4, width, height] = this.#bbox;
for (let i7 = 0, ii = outline.length; i7 < ii; i7 += 2) {
outline[i7] = (outline[i7] - x2) / width;
outline[i7 + 1] = (outline[i7 + 1] - y4) / height;
}
for (let i7 = 0, ii = points.length; i7 < ii; i7 += 2) {
points[i7] = (points[i7] - x2) / width;
points[i7 + 1] = (points[i7 + 1] - y4) / height;
}
}
toSVGPath() {
const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`];
for (let i7 = 6, ii = this.#outline.length; i7 < ii; i7 += 6) {
if (isNaN(this.#outline[i7])) {
buffer.push(`L${this.#outline[i7 + 4]} ${this.#outline[i7 + 5]}`);
continue;
}
buffer.push(`C${this.#outline[i7]} ${this.#outline[i7 + 1]} ${this.#outline[i7 + 2]} ${this.#outline[i7 + 3]} ${this.#outline[i7 + 4]} ${this.#outline[i7 + 5]}`);
}
buffer.push("Z");
return buffer.join(" ");
}
serialize([blX, blY, trX, trY], rotation) {
const width = trX - blX;
const height = trY - blY;
let outline;
let points;
switch (rotation) {
case 0:
outline = Outline._rescale(this.#outline, blX, trY, width, -height);
points = Outline._rescale(this.#points, blX, trY, width, -height);
break;
case 90:
outline = Outline._rescaleAndSwap(this.#outline, blX, blY, width, height);
points = Outline._rescaleAndSwap(this.#points, blX, blY, width, height);
break;
case 180:
outline = Outline._rescale(this.#outline, trX, blY, -width, height);
points = Outline._rescale(this.#points, trX, blY, -width, height);
break;
case 270:
outline = Outline._rescaleAndSwap(this.#outline, trX, trY, -width, -height);
points = Outline._rescaleAndSwap(this.#points, trX, trY, -width, -height);
break;
}
return {
outline: Array.from(outline),
points: [Array.from(points)]
};
}
#computeMinMax(isLTR) {
const outline = this.#outline;
let lastX = outline[4];
let lastY = outline[5];
const minMax = [lastX, lastY, lastX, lastY];
let firstPointX = lastX;
let firstPointY = lastY;
let lastPointX = lastX;
let lastPointY = lastY;
const ltrCallback = isLTR ? Math.max : Math.min;
const bezierBbox = new Float32Array(4);
for (let i7 = 6, ii = outline.length; i7 < ii; i7 += 6) {
const x2 = outline[i7 + 4], y4 = outline[i7 + 5];
if (isNaN(outline[i7])) {
Util.pointBoundingBox(x2, y4, minMax);
if (firstPointY > y4) {
firstPointX = x2;
firstPointY = y4;
} else if (firstPointY === y4) {
firstPointX = ltrCallback(firstPointX, x2);
}
if (lastPointY < y4) {
lastPointX = x2;
lastPointY = y4;
} else if (lastPointY === y4) {
lastPointX = ltrCallback(lastPointX, x2);
}
} else {
bezierBbox[0] = bezierBbox[1] = Infinity;
bezierBbox[2] = bezierBbox[3] = -Infinity;
Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i7, i7 + 6), bezierBbox);
Util.rectBoundingBox(bezierBbox[0], bezierBbox[1], bezierBbox[2], bezierBbox[3], minMax);
if (firstPointY > bezierBbox[1]) {
firstPointX = bezierBbox[0];
firstPointY = bezierBbox[1];
} else if (firstPointY === bezierBbox[1]) {
firstPointX = ltrCallback(firstPointX, bezierBbox[0]);
}
if (lastPointY < bezierBbox[3]) {
lastPointX = bezierBbox[2];
lastPointY = bezierBbox[3];
} else if (lastPointY === bezierBbox[3]) {
lastPointX = ltrCallback(lastPointX, bezierBbox[2]);
}
}
lastX = x2;
lastY = y4;
}
const bbox = this.#bbox;
bbox[0] = minMax[0] - this.#innerMargin;
bbox[1] = minMax[1] - this.#innerMargin;
bbox[2] = minMax[2] - minMax[0] + 2 * this.#innerMargin;
bbox[3] = minMax[3] - minMax[1] + 2 * this.#innerMargin;
this.firstPoint = [firstPointX, firstPointY];
this.lastPoint = [lastPointX, lastPointY];
}
get box() {
return this.#bbox;
}
newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
return new FreeDrawOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);
}
getNewOutline(thickness, innerMargin) {
const [x2, y4, width, height] = this.#bbox;
const [layerX, layerY, layerWidth, layerHeight] = this.#box;
const sx = width * layerWidth;
const sy = height * layerHeight;
const tx = x2 * layerWidth + layerX;
const ty = y4 * layerHeight + layerY;
const outliner = this.newOutliner({
x: this.#points[0] * sx + tx,
y: this.#points[1] * sy + ty
}, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin);
for (let i7 = 2; i7 < this.#points.length; i7 += 2) {
outliner.add({
x: this.#points[i7] * sx + tx,
y: this.#points[i7 + 1] * sy + ty
});
}
return outliner.getOutlines();
}
};
HighlightOutliner = class {
#box;
#firstPoint;
#lastPoint;
#verticalEdges = [];
#intervals = [];
constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) {
const minMax = [Infinity, Infinity, -Infinity, -Infinity];
const NUMBER_OF_DIGITS = 4;
const EPSILON2 = 10 ** -NUMBER_OF_DIGITS;
for (const {
x: x2,
y: y4,
width,
height
} of boxes) {
const x1 = Math.floor((x2 - borderWidth) / EPSILON2) * EPSILON2;
const x22 = Math.ceil((x2 + width + borderWidth) / EPSILON2) * EPSILON2;
const y1 = Math.floor((y4 - borderWidth) / EPSILON2) * EPSILON2;
const y22 = Math.ceil((y4 + height + borderWidth) / EPSILON2) * EPSILON2;
const left = [x1, y1, y22, true];
const right = [x22, y1, y22, false];
this.#verticalEdges.push(left, right);
Util.rectBoundingBox(x1, y1, x22, y22, minMax);
}
const bboxWidth = minMax[2] - minMax[0] + 2 * innerMargin;
const bboxHeight = minMax[3] - minMax[1] + 2 * innerMargin;
const shiftedMinX = minMax[0] - innerMargin;
const shiftedMinY = minMax[1] - innerMargin;
let firstPointX = isLTR ? -Infinity : Infinity;
let firstPointY = Infinity;
const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2);
const lastPoint = [lastEdge[0], lastEdge[2]];
for (const edge of this.#verticalEdges) {
const [x2, y1, y22, left] = edge;
if (!left && isLTR) {
if (y1 < firstPointY) {
firstPointY = y1;
firstPointX = x2;
} else if (y1 === firstPointY) {
firstPointX = Math.max(firstPointX, x2);
}
} else if (left && !isLTR) {
if (y1 < firstPointY) {
firstPointY = y1;
firstPointX = x2;
} else if (y1 === firstPointY) {
firstPointX = Math.min(firstPointX, x2);
}
}
edge[0] = (x2 - shiftedMinX) / bboxWidth;
edge[1] = (y1 - shiftedMinY) / bboxHeight;
edge[2] = (y22 - shiftedMinY) / bboxHeight;
}
this.#box = new Float32Array([shiftedMinX, shiftedMinY, bboxWidth, bboxHeight]);
this.#firstPoint = [firstPointX, firstPointY];
this.#lastPoint = lastPoint;
}
getOutlines() {
this.#verticalEdges.sort((a3, b4) => a3[0] - b4[0] || a3[1] - b4[1] || a3[2] - b4[2]);
const outlineVerticalEdges = [];
for (const edge of this.#verticalEdges) {
if (edge[3]) {
outlineVerticalEdges.push(...this.#breakEdge(edge));
this.#insert(edge);
} else {
this.#remove(edge);
outlineVerticalEdges.push(...this.#breakEdge(edge));
}
}
return this.#getOutlines(outlineVerticalEdges);
}
#getOutlines(outlineVerticalEdges) {
const edges = [];
const allEdges = /* @__PURE__ */ new Set();
for (const edge of outlineVerticalEdges) {
const [x2, y1, y22] = edge;
edges.push([x2, y1, edge], [x2, y22, edge]);
}
edges.sort((a3, b4) => a3[1] - b4[1] || a3[0] - b4[0]);
for (let i7 = 0, ii = edges.length; i7 < ii; i7 += 2) {
const edge1 = edges[i7][2];
const edge2 = edges[i7 + 1][2];
edge1.push(edge2);
edge2.push(edge1);
allEdges.add(edge1);
allEdges.add(edge2);
}
const outlines = [];
let outline;
while (allEdges.size > 0) {
const edge = allEdges.values().next().value;
let [x2, y1, y22, edge1, edge2] = edge;
allEdges.delete(edge);
let lastPointX = x2;
let lastPointY = y1;
outline = [x2, y22];
outlines.push(outline);
while (true) {
let e9;
if (allEdges.has(edge1)) {
e9 = edge1;
} else if (allEdges.has(edge2)) {
e9 = edge2;
} else {
break;
}
allEdges.delete(e9);
[x2, y1, y22, edge1, edge2] = e9;
if (lastPointX !== x2) {
outline.push(lastPointX, lastPointY, x2, lastPointY === y1 ? y1 : y22);
lastPointX = x2;
}
lastPointY = lastPointY === y1 ? y22 : y1;
}
outline.push(lastPointX, lastPointY);
}
return new HighlightOutline(outlines, this.#box, this.#firstPoint, this.#lastPoint);
}
#binarySearch(y4) {
const array = this.#intervals;
let start = 0;
let end = array.length - 1;
while (start <= end) {
const middle = start + end >> 1;
const y1 = array[middle][0];
if (y1 === y4) {
return middle;
}
if (y1 < y4) {
start = middle + 1;
} else {
end = middle - 1;
}
}
return end + 1;
}
#insert([, y1, y22]) {
const index2 = this.#binarySearch(y1);
this.#intervals.splice(index2, 0, [y1, y22]);
}
#remove([, y1, y22]) {
const index2 = this.#binarySearch(y1);
for (let i7 = index2; i7 < this.#intervals.length; i7++) {
const [start, end] = this.#intervals[i7];
if (start !== y1) {
break;
}
if (start === y1 && end === y22) {
this.#intervals.splice(i7, 1);
return;
}
}
for (let i7 = index2 - 1; i7 >= 0; i7--) {
const [start, end] = this.#intervals[i7];
if (start !== y1) {
break;
}
if (start === y1 && end === y22) {
this.#intervals.splice(i7, 1);
return;
}
}
}
#breakEdge(edge) {
const [x2, y1, y22] = edge;
const results = [[x2, y1, y22]];
const index2 = this.#binarySearch(y22);
for (let i7 = 0; i7 < index2; i7++) {
const [start, end] = this.#intervals[i7];
for (let j3 = 0, jj = results.length; j3 < jj; j3++) {
const [, y32, y4] = results[j3];
if (end <= y32 || y4 <= start) {
continue;
}
if (y32 >= start) {
if (y4 > end) {
results[j3][1] = end;
} else {
if (jj === 1) {
return [];
}
results.splice(j3, 1);
j3--;
jj--;
}
continue;
}
results[j3][2] = start;
if (y4 > end) {
results.push([x2, end, y4]);
}
}
}
return results;
}
};
HighlightOutline = class extends Outline {
#box;
#outlines;
constructor(outlines, box, firstPoint, lastPoint) {
super();
this.#outlines = outlines;
this.#box = box;
this.firstPoint = firstPoint;
this.lastPoint = lastPoint;
}
toSVGPath() {
const buffer = [];
for (const polygon of this.#outlines) {
let [prevX, prevY] = polygon;
buffer.push(`M${prevX} ${prevY}`);
for (let i7 = 2; i7 < polygon.length; i7 += 2) {
const x2 = polygon[i7];
const y4 = polygon[i7 + 1];
if (x2 === prevX) {
buffer.push(`V${y4}`);
prevY = y4;
} else if (y4 === prevY) {
buffer.push(`H${x2}`);
prevX = x2;
}
}
buffer.push("Z");
}
return buffer.join(" ");
}
serialize([blX, blY, trX, trY], _rotation) {
const outlines = [];
const width = trX - blX;
const height = trY - blY;
for (const outline of this.#outlines) {
const points = new Array(outline.length);
for (let i7 = 0; i7 < outline.length; i7 += 2) {
points[i7] = blX + outline[i7] * width;
points[i7 + 1] = trY - outline[i7 + 1] * height;
}
outlines.push(points);
}
return outlines;
}
get box() {
return this.#box;
}
get classNamesForOutlining() {
return ["highlightOutline"];
}
};
FreeHighlightOutliner = class extends FreeDrawOutliner {
newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) {
return new FreeHighlightOutline(outline, points, box, scaleFactor, innerMargin, isLTR);
}
};
FreeHighlightOutline = class extends FreeDrawOutline {
newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) {
return new FreeHighlightOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin);
}
};
HighlightEditor = class _HighlightEditor extends AnnotationEditor {
#anchorNode = null;
#anchorOffset = 0;
#boxes;
#clipPathId = null;
#colorPicker = null;
#focusOutlines = null;
#focusNode = null;
#focusOffset = 0;
#highlightDiv = null;
#highlightOutlines = null;
#id = null;
#isFreeHighlight = false;
#firstPoint = null;
#lastPoint = null;
#outlineId = null;
#text = "";
#thickness;
#methodOfCreation = "";
static _defaultColor = null;
static _defaultOpacity = 1;
static _defaultThickness = 12;
static _type = "highlight";
static _editorType = AnnotationEditorType.HIGHLIGHT;
static _freeHighlightId = -1;
static _freeHighlight = null;
static _freeHighlightClipId = "";
static get _keyboardManager() {
const proto = _HighlightEditor.prototype;
return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, {
args: [0]
}], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, {
args: [1]
}], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, {
args: [2]
}], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, {
args: [3]
}]]));
}
constructor(params) {
super({
...params,
name: "highlightEditor"
});
this.color = params.color || _HighlightEditor._defaultColor;
this.#thickness = params.thickness || _HighlightEditor._defaultThickness;
this.opacity = params.opacity || _HighlightEditor._defaultOpacity;
this.#boxes = params.boxes || null;
this.#methodOfCreation = params.methodOfCreation || "";
this.#text = params.text || "";
this._isDraggable = false;
this.defaultL10nId = "pdfjs-editor-highlight-editor";
if (params.highlightId > -1) {
this.#isFreeHighlight = true;
this.#createFreeOutlines(params);
this.#addToDrawLayer();
} else if (this.#boxes) {
this.#anchorNode = params.anchorNode;
this.#anchorOffset = params.anchorOffset;
this.#focusNode = params.focusNode;
this.#focusOffset = params.focusOffset;
this.#createOutlines();
this.#addToDrawLayer();
this.rotate(this.rotation);
}
if (!this.annotationElementId) {
this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert");
}
}
get telemetryInitialData() {
return {
action: "added",
type: this.#isFreeHighlight ? "free_highlight" : "highlight",
color: this._uiManager.getNonHCMColorName(this.color),
thickness: this.#thickness,
methodOfCreation: this.#methodOfCreation
};
}
get telemetryFinalData() {
return {
type: "highlight",
color: this._uiManager.getNonHCMColorName(this.color)
};
}
static computeTelemetryFinalData(data) {
return {
numberOfColors: data.get("color").size
};
}
#createOutlines() {
const outliner = new HighlightOutliner(this.#boxes, 1e-3);
this.#highlightOutlines = outliner.getOutlines();
[this.x, this.y, this.width, this.height] = this.#highlightOutlines.box;
const outlinerForOutline = new HighlightOutliner(this.#boxes, 25e-4, 1e-3, this._uiManager.direction === "ltr");
this.#focusOutlines = outlinerForOutline.getOutlines();
const {
firstPoint
} = this.#highlightOutlines;
this.#firstPoint = [(firstPoint[0] - this.x) / this.width, (firstPoint[1] - this.y) / this.height];
const {
lastPoint
} = this.#focusOutlines;
this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height];
}
#createFreeOutlines({
highlightOutlines,
highlightId,
clipPathId
}) {
this.#highlightOutlines = highlightOutlines;
const extraThickness = 1.5;
this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 25e-4);
if (highlightId >= 0) {
this.#id = highlightId;
this.#clipPathId = clipPathId;
this.parent.drawLayer.finalizeDraw(highlightId, {
bbox: highlightOutlines.box,
path: {
d: highlightOutlines.toSVGPath()
}
});
this.#outlineId = this.parent.drawLayer.drawOutline({
rootClass: {
highlightOutline: true,
free: true
},
bbox: this.#focusOutlines.box,
path: {
d: this.#focusOutlines.toSVGPath()
}
}, true);
} else if (this.parent) {
const angle = this.parent.viewport.rotation;
this.parent.drawLayer.updateProperties(this.#id, {
bbox: _HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360),
path: {
d: highlightOutlines.toSVGPath()
}
});
this.parent.drawLayer.updateProperties(this.#outlineId, {
bbox: _HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle),
path: {
d: this.#focusOutlines.toSVGPath()
}
});
}
const [x2, y4, width, height] = highlightOutlines.box;
switch (this.rotation) {
case 0:
this.x = x2;
this.y = y4;
this.width = width;
this.height = height;
break;
case 90: {
const [pageWidth, pageHeight] = this.parentDimensions;
this.x = y4;
this.y = 1 - x2;
this.width = width * pageHeight / pageWidth;
this.height = height * pageWidth / pageHeight;
break;
}
case 180:
this.x = 1 - x2;
this.y = 1 - y4;
this.width = width;
this.height = height;
break;
case 270: {
const [pageWidth, pageHeight] = this.parentDimensions;
this.x = 1 - y4;
this.y = x2;
this.width = width * pageHeight / pageWidth;
this.height = height * pageWidth / pageHeight;
break;
}
}
const {
firstPoint
} = highlightOutlines;
this.#firstPoint = [(firstPoint[0] - x2) / width, (firstPoint[1] - y4) / height];
const {
lastPoint
} = this.#focusOutlines;
this.#lastPoint = [(lastPoint[0] - x2) / width, (lastPoint[1] - y4) / height];
}
static initialize(l10n, uiManager) {
AnnotationEditor.initialize(l10n, uiManager);
_HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066";
}
static updateDefaultParams(type, value) {
switch (type) {
case AnnotationEditorParamsType.HIGHLIGHT_COLOR:
_HighlightEditor._defaultColor = value;
break;
case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
_HighlightEditor._defaultThickness = value;
break;
}
}
translateInPage(x2, y4) {
}
get toolbarPosition() {
return this.#lastPoint;
}
get commentButtonPosition() {
return this.#firstPoint;
}
updateParams(type, value) {
switch (type) {
case AnnotationEditorParamsType.HIGHLIGHT_COLOR:
this.#updateColor(value);
break;
case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:
this.#updateThickness(value);
break;
}
}
static get defaultPropertiesToUpdate() {
return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, _HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, _HighlightEditor._defaultThickness]];
}
get propertiesToUpdate() {
return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || _HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || _HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]];
}
onUpdatedColor() {
this.parent?.drawLayer.updateProperties(this.#id, {
root: {
fill: this.color,
"fill-opacity": this.opacity
}
});
this.#colorPicker?.updateColor(this.color);
super.onUpdatedColor();
}
#updateColor(color2) {
const setColorAndOpacity = (col, opa) => {
this.color = col;
this.opacity = opa;
this.onUpdatedColor();
};
const savedColor = this.color;
const savedOpacity = this.opacity;
this.addCommands({
cmd: setColorAndOpacity.bind(this, color2, _HighlightEditor._defaultOpacity),
undo: setColorAndOpacity.bind(this, savedColor, savedOpacity),
post: this._uiManager.updateUI.bind(this._uiManager, this),
mustExec: true,
type: AnnotationEditorParamsType.HIGHLIGHT_COLOR,
overwriteIfSameType: true,
keepUndo: true
});
this._reportTelemetry({
action: "color_changed",
color: this._uiManager.getNonHCMColorName(color2)
}, true);
}
#updateThickness(thickness) {
const savedThickness = this.#thickness;
const setThickness = (th) => {
this.#thickness = th;
this.#changeThickness(th);
};
this.addCommands({
cmd: setThickness.bind(this, thickness),
undo: setThickness.bind(this, savedThickness),
post: this._uiManager.updateUI.bind(this._uiManager, this),
mustExec: true,
type: AnnotationEditorParamsType.INK_THICKNESS,
overwriteIfSameType: true,
keepUndo: true
});
this._reportTelemetry({
action: "thickness_changed",
thickness
}, true);
}
get toolbarButtons() {
if (this._uiManager.highlightColors) {
const colorPicker = this.#colorPicker = new ColorPicker({
editor: this
});
return [["colorPicker", colorPicker]];
}
return super.toolbarButtons;
}
disableEditing() {
super.disableEditing();
this.div.classList.toggle("disabled", true);
}
enableEditing() {
super.enableEditing();
this.div.classList.toggle("disabled", false);
}
fixAndSetPosition() {
return super.fixAndSetPosition(this.#getRotation());
}
getBaseTranslation() {
return [0, 0];
}
getRect(tx, ty) {
return super.getRect(tx, ty, this.#getRotation());
}
onceAdded(focus) {
if (!this.annotationElementId) {
this.parent.addUndoableEditor(this);
}
if (focus) {
this.div.focus();
}
}
remove() {
this.#cleanDrawLayer();
this._reportTelemetry({
action: "deleted"
});
super.remove();
}
rebuild() {
if (!this.parent) {
return;
}
super.rebuild();
if (this.div === null) {
return;
}
this.#addToDrawLayer();
if (!this.isAttachedToDOM) {
this.parent.add(this);
}
}
setParent(parent) {
let mustBeSelected = false;
if (this.parent && !parent) {
this.#cleanDrawLayer();
} else if (parent) {
this.#addToDrawLayer(parent);
mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
}
super.setParent(parent);
this.show(this._isVisible);
if (mustBeSelected) {
this.select();
}
}
#changeThickness(thickness) {
if (!this.#isFreeHighlight) {
return;
}
this.#createFreeOutlines({
highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2)
});
this.fixAndSetPosition();
this.setDims();
}
#cleanDrawLayer() {
if (this.#id === null || !this.parent) {
return;
}
this.parent.drawLayer.remove(this.#id);
this.#id = null;
this.parent.drawLayer.remove(this.#outlineId);
this.#outlineId = null;
}
#addToDrawLayer(parent = this.parent) {
if (this.#id !== null) {
return;
}
({
id: this.#id,
clipPathId: this.#clipPathId
} = parent.drawLayer.draw({
bbox: this.#highlightOutlines.box,
root: {
viewBox: "0 0 1 1",
fill: this.color,
"fill-opacity": this.opacity
},
rootClass: {
highlight: true,
free: this.#isFreeHighlight
},
path: {
d: this.#highlightOutlines.toSVGPath()
}
}, false, true));
this.#outlineId = parent.drawLayer.drawOutline({
rootClass: {
highlightOutline: true,
free: this.#isFreeHighlight
},
bbox: this.#focusOutlines.box,
path: {
d: this.#focusOutlines.toSVGPath()
}
}, this.#isFreeHighlight);
if (this.#highlightDiv) {
this.#highlightDiv.style.clipPath = this.#clipPathId;
}
}
static #rotateBbox([x2, y4, width, height], angle) {
switch (angle) {
case 90:
return [1 - y4 - height, x2, height, width];
case 180:
return [1 - x2 - width, 1 - y4 - height, width, height];
case 270:
return [y4, 1 - x2 - width, height, width];
}
return [x2, y4, width, height];
}
rotate(angle) {
const {
drawLayer
} = this.parent;
let box;
if (this.#isFreeHighlight) {
angle = (angle - this.rotation + 360) % 360;
box = _HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle);
} else {
box = _HighlightEditor.#rotateBbox([this.x, this.y, this.width, this.height], angle);
}
drawLayer.updateProperties(this.#id, {
bbox: box,
root: {
"data-main-rotation": angle
}
});
drawLayer.updateProperties(this.#outlineId, {
bbox: _HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle),
root: {
"data-main-rotation": angle
}
});
}
render() {
if (this.div) {
return this.div;
}
const div = super.render();
if (this.#text) {
div.setAttribute("aria-label", this.#text);
div.setAttribute("role", "mark");
}
if (this.#isFreeHighlight) {
div.classList.add("free");
} else {
this.div.addEventListener("keydown", this.#keydown.bind(this), {
signal: this._uiManager._signal
});
}
const highlightDiv = this.#highlightDiv = document.createElement("div");
div.append(highlightDiv);
highlightDiv.setAttribute("aria-hidden", "true");
highlightDiv.className = "internal";
highlightDiv.style.clipPath = this.#clipPathId;
this.setDims();
bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]);
this.enableEditing();
return div;
}
pointerover() {
if (!this.isSelected) {
this.parent?.drawLayer.updateProperties(this.#outlineId, {
rootClass: {
hovered: true
}
});
}
}
pointerleave() {
if (!this.isSelected) {
this.parent?.drawLayer.updateProperties(this.#outlineId, {
rootClass: {
hovered: false
}
});
}
}
#keydown(event) {
_HighlightEditor._keyboardManager.exec(this, event);
}
_moveCaret(direction) {
this.parent.unselect(this);
switch (direction) {
case 0:
case 2:
this.#setCaret(true);
break;
case 1:
case 3:
this.#setCaret(false);
break;
}
}
#setCaret(start) {
if (!this.#anchorNode) {
return;
}
const selection = window.getSelection();
if (start) {
selection.setPosition(this.#anchorNode, this.#anchorOffset);
} else {
selection.setPosition(this.#focusNode, this.#focusOffset);
}
}
select() {
super.select();
if (!this.#outlineId) {
return;
}
this.parent?.drawLayer.updateProperties(this.#outlineId, {
rootClass: {
hovered: false,
selected: true
}
});
}
unselect() {
super.unselect();
if (!this.#outlineId) {
return;
}
this.parent?.drawLayer.updateProperties(this.#outlineId, {
rootClass: {
selected: false
}
});
if (!this.#isFreeHighlight) {
this.#setCaret(false);
}
}
get _mustFixPosition() {
return !this.#isFreeHighlight;
}
show(visible = this._isVisible) {
super.show(visible);
if (this.parent) {
this.parent.drawLayer.updateProperties(this.#id, {
rootClass: {
hidden: !visible
}
});
this.parent.drawLayer.updateProperties(this.#outlineId, {
rootClass: {
hidden: !visible
}
});
}
}
#getRotation() {
return this.#isFreeHighlight ? this.rotation : 0;
}
#serializeBoxes() {
if (this.#isFreeHighlight) {
return null;
}
const [pageWidth, pageHeight] = this.pageDimensions;
const [pageX, pageY] = this.pageTranslation;
const boxes = this.#boxes;
const quadPoints = new Float32Array(boxes.length * 8);
let i7 = 0;
for (const {
x: x2,
y: y4,
width,
height
} of boxes) {
const sx = x2 * pageWidth + pageX;
const sy = (1 - y4) * pageHeight + pageY;
quadPoints[i7] = quadPoints[i7 + 4] = sx;
quadPoints[i7 + 1] = quadPoints[i7 + 3] = sy;
quadPoints[i7 + 2] = quadPoints[i7 + 6] = sx + width * pageWidth;
quadPoints[i7 + 5] = quadPoints[i7 + 7] = sy - height * pageHeight;
i7 += 8;
}
return quadPoints;
}
#serializeOutlines(rect) {
return this.#highlightOutlines.serialize(rect, this.#getRotation());
}
static startHighlighting(parent, isLTR, {
target: textLayer,
x: x2,
y: y4
}) {
const {
x: layerX,
y: layerY,
width: parentWidth,
height: parentHeight
} = textLayer.getBoundingClientRect();
const ac = new AbortController();
const signal = parent.combinedSignal(ac);
const pointerUpCallback = (e9) => {
ac.abort();
this.#endHighlight(parent, e9);
};
window.addEventListener("blur", pointerUpCallback, {
signal
});
window.addEventListener("pointerup", pointerUpCallback, {
signal
});
window.addEventListener("pointerdown", stopEvent, {
capture: true,
passive: false,
signal
});
window.addEventListener("contextmenu", noContextMenu, {
signal
});
textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), {
signal
});
this._freeHighlight = new FreeHighlightOutliner({
x: x2,
y: y4
}, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 1e-3);
({
id: this._freeHighlightId,
clipPathId: this._freeHighlightClipId
} = parent.drawLayer.draw({
bbox: [0, 0, 1, 1],
root: {
viewBox: "0 0 1 1",
fill: this._defaultColor,
"fill-opacity": this._defaultOpacity
},
rootClass: {
highlight: true,
free: true
},
path: {
d: this._freeHighlight.toSVGPath()
}
}, true, true));
}
static #highlightMove(parent, event) {
if (this._freeHighlight.add(event)) {
parent.drawLayer.updateProperties(this._freeHighlightId, {
path: {
d: this._freeHighlight.toSVGPath()
}
});
}
}
static #endHighlight(parent, event) {
if (!this._freeHighlight.isEmpty()) {
parent.createAndAddNewEditor(event, false, {
highlightId: this._freeHighlightId,
highlightOutlines: this._freeHighlight.getOutlines(),
clipPathId: this._freeHighlightClipId,
methodOfCreation: "main_toolbar"
});
} else {
parent.drawLayer.remove(this._freeHighlightId);
}
this._freeHighlightId = -1;
this._freeHighlight = null;
this._freeHighlightClipId = "";
}
static async deserialize(data, parent, uiManager) {
let initialData = null;
if (data instanceof HighlightAnnotationElement) {
const {
data: {
quadPoints: quadPoints2,
rect,
rotation,
id,
color: color3,
opacity: opacity2,
popupRef,
richText,
contentsObj,
creationDate,
modificationDate
},
parent: {
page: {
pageNumber
}
}
} = data;
initialData = data = {
annotationType: AnnotationEditorType.HIGHLIGHT,
color: Array.from(color3),
opacity: opacity2,
quadPoints: quadPoints2,
boxes: null,
pageIndex: pageNumber - 1,
rect: rect.slice(0),
rotation,
annotationElementId: id,
id,
deleted: false,
popupRef,
richText,
comment: contentsObj?.str || null,
creationDate,
modificationDate
};
} else if (data instanceof InkAnnotationElement) {
const {
data: {
inkLists: inkLists2,
rect,
rotation,
id,
color: color3,
borderStyle: {
rawWidth: thickness
},
popupRef,
richText,
contentsObj,
creationDate,
modificationDate
},
parent: {
page: {
pageNumber
}
}
} = data;
initialData = data = {
annotationType: AnnotationEditorType.HIGHLIGHT,
color: Array.from(color3),
thickness,
inkLists: inkLists2,
boxes: null,
pageIndex: pageNumber - 1,
rect: rect.slice(0),
rotation,
annotationElementId: id,
id,
deleted: false,
popupRef,
richText,
comment: contentsObj?.str || null,
creationDate,
modificationDate
};
}
const {
color: color2,
quadPoints,
inkLists,
opacity
} = data;
const editor = await super.deserialize(data, parent, uiManager);
editor.color = Util.makeHexColor(...color2);
editor.opacity = opacity || 1;
if (inkLists) {
editor.#thickness = data.thickness;
}
editor._initialData = initialData;
if (data.comment) {
editor.setCommentData(data);
}
const [pageWidth, pageHeight] = editor.pageDimensions;
const [pageX, pageY] = editor.pageTranslation;
if (quadPoints) {
const boxes = editor.#boxes = [];
for (let i7 = 0; i7 < quadPoints.length; i7 += 8) {
boxes.push({
x: (quadPoints[i7] - pageX) / pageWidth,
y: 1 - (quadPoints[i7 + 1] - pageY) / pageHeight,
width: (quadPoints[i7 + 2] - quadPoints[i7]) / pageWidth,
height: (quadPoints[i7 + 1] - quadPoints[i7 + 5]) / pageHeight
});
}
editor.#createOutlines();
editor.#addToDrawLayer();
editor.rotate(editor.rotation);
} else if (inkLists) {
editor.#isFreeHighlight = true;
const points = inkLists[0];
const point = {
x: points[0] - pageX,
y: pageHeight - (points[1] - pageY)
};
const outliner = new FreeHighlightOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 1e-3);
for (let i7 = 0, ii = points.length; i7 < ii; i7 += 2) {
point.x = points[i7] - pageX;
point.y = pageHeight - (points[i7 + 1] - pageY);
outliner.add(point);
}
const {
id,
clipPathId
} = parent.drawLayer.draw({
bbox: [0, 0, 1, 1],
root: {
viewBox: "0 0 1 1",
fill: editor.color,
"fill-opacity": editor._defaultOpacity
},
rootClass: {
highlight: true,
free: true
},
path: {
d: outliner.toSVGPath()
}
}, true, true);
editor.#createFreeOutlines({
highlightOutlines: outliner.getOutlines(),
highlightId: id,
clipPathId
});
editor.#addToDrawLayer();
editor.rotate(editor.parentRotation);
}
return editor;
}
serialize(isForCopying = false) {
if (this.isEmpty() || isForCopying) {
return null;
}
if (this.deleted) {
return this.serializeDeleted();
}
const color2 = AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color));
const serialized = super.serialize(isForCopying);
Object.assign(serialized, {
color: color2,
opacity: this.opacity,
thickness: this.#thickness,
quadPoints: this.#serializeBoxes(),
outlines: this.#serializeOutlines(serialized.rect)
});
this.addComment(serialized);
if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
return null;
}
serialized.id = this.annotationElementId;
return serialized;
}
#hasElementChanged(serialized) {
const {
color: color2
} = this._initialData;
return this.hasEditedComment || serialized.color.some((c6, i7) => c6 !== color2[i7]);
}
renderAnnotationElement(annotation) {
if (this.deleted) {
annotation.hide();
return null;
}
annotation.updateEdited({
rect: this.getPDFRect(),
popup: this.comment
});
return null;
}
static canCreateNewEmptyEditor() {
return false;
}
};
DrawingOptions = class {
#svgProperties = /* @__PURE__ */ Object.create(null);
updateProperty(name, value) {
this[name] = value;
this.updateSVGProperty(name, value);
}
updateProperties(properties) {
if (!properties) {
return;
}
for (const [name, value] of Object.entries(properties)) {
if (!name.startsWith("_")) {
this.updateProperty(name, value);
}
}
}
updateSVGProperty(name, value) {
this.#svgProperties[name] = value;
}
toSVGProperties() {
const root = this.#svgProperties;
this.#svgProperties = /* @__PURE__ */ Object.create(null);
return {
root
};
}
reset() {
this.#svgProperties = /* @__PURE__ */ Object.create(null);
}
updateAll(options = this) {
this.updateProperties(options);
}
clone() {
unreachable("Not implemented");
}
};
DrawingEditor = class _DrawingEditor extends AnnotationEditor {
#drawOutlines = null;
#mustBeCommitted;
_colorPicker = null;
_drawId = null;
static _currentDrawId = -1;
static _currentParent = null;
static #currentDraw = null;
static #currentDrawingAC = null;
static #currentDrawingOptions = null;
static _INNER_MARGIN = 3;
constructor(params) {
super(params);
this.#mustBeCommitted = params.mustBeCommitted || false;
this._addOutlines(params);
}
onUpdatedColor() {
this._colorPicker?.update(this.color);
super.onUpdatedColor();
}
_addOutlines(params) {
if (params.drawOutlines) {
this.#createDrawOutlines(params);
this.#addToDrawLayer();
}
}
#createDrawOutlines({
drawOutlines,
drawId,
drawingOptions
}) {
this.#drawOutlines = drawOutlines;
this._drawingOptions ||= drawingOptions;
if (!this.annotationElementId) {
this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`);
}
if (drawId >= 0) {
this._drawId = drawId;
this.parent.drawLayer.finalizeDraw(drawId, drawOutlines.defaultProperties);
} else {
this._drawId = this.#createDrawing(drawOutlines, this.parent);
}
this.#updateBbox(drawOutlines.box);
}
#createDrawing(drawOutlines, parent) {
const {
id
} = parent.drawLayer.draw(_DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(), drawOutlines.defaultSVGProperties), false, false);
return id;
}
static _mergeSVGProperties(p1, p22) {
const p1Keys = new Set(Object.keys(p1));
for (const [key, value] of Object.entries(p22)) {
if (p1Keys.has(key)) {
Object.assign(p1[key], value);
} else {
p1[key] = value;
}
}
return p1;
}
static getDefaultDrawingOptions(_options) {
unreachable("Not implemented");
}
static get typesMap() {
unreachable("Not implemented");
}
static get isDrawer() {
return true;
}
static get supportMultipleDrawings() {
return false;
}
static updateDefaultParams(type, value) {
const propertyName = this.typesMap.get(type);
if (propertyName) {
this._defaultDrawingOptions.updateProperty(propertyName, value);
}
if (this._currentParent) {
_DrawingEditor.#currentDraw.updateProperty(propertyName, value);
this._currentParent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties());
}
}
updateParams(type, value) {
const propertyName = this.constructor.typesMap.get(type);
if (propertyName) {
this._updateProperty(type, propertyName, value);
}
}
static get defaultPropertiesToUpdate() {
const properties = [];
const options = this._defaultDrawingOptions;
for (const [type, name] of this.typesMap) {
properties.push([type, options[name]]);
}
return properties;
}
get propertiesToUpdate() {
const properties = [];
const {
_drawingOptions
} = this;
for (const [type, name] of this.constructor.typesMap) {
properties.push([type, _drawingOptions[name]]);
}
return properties;
}
_updateProperty(type, name, value) {
const options = this._drawingOptions;
const savedValue = options[name];
const setter = (val2) => {
options.updateProperty(name, val2);
const bbox = this.#drawOutlines.updateProperty(name, val2);
if (bbox) {
this.#updateBbox(bbox);
}
this.parent?.drawLayer.updateProperties(this._drawId, options.toSVGProperties());
if (type === this.colorType) {
this.onUpdatedColor();
}
};
this.addCommands({
cmd: setter.bind(this, value),
undo: setter.bind(this, savedValue),
post: this._uiManager.updateUI.bind(this._uiManager, this),
mustExec: true,
type,
overwriteIfSameType: true,
keepUndo: true
});
}
_onResizing() {
this.parent?.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizingSVGProperties(this.#convertToDrawSpace()), {
bbox: this.#rotateBox()
}));
}
_onResized() {
this.parent?.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizedSVGProperties(this.#convertToDrawSpace()), {
bbox: this.#rotateBox()
}));
}
_onTranslating(_x2, _y2) {
this.parent?.drawLayer.updateProperties(this._drawId, {
bbox: this.#rotateBox()
});
}
_onTranslated() {
this.parent?.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathTranslatedSVGProperties(this.#convertToDrawSpace(), this.parentDimensions), {
bbox: this.#rotateBox()
}));
}
_onStartDragging() {
this.parent?.drawLayer.updateProperties(this._drawId, {
rootClass: {
moving: true
}
});
}
_onStopDragging() {
this.parent?.drawLayer.updateProperties(this._drawId, {
rootClass: {
moving: false
}
});
}
commit() {
super.commit();
this.disableEditMode();
this.disableEditing();
}
disableEditing() {
super.disableEditing();
this.div.classList.toggle("disabled", true);
}
enableEditing() {
super.enableEditing();
this.div.classList.toggle("disabled", false);
}
getBaseTranslation() {
return [0, 0];
}
get isResizable() {
return true;
}
onceAdded(focus) {
if (!this.annotationElementId) {
this.parent.addUndoableEditor(this);
}
this._isDraggable = true;
if (this.#mustBeCommitted) {
this.#mustBeCommitted = false;
this.commit();
this.parent.setSelected(this);
if (focus && this.isOnScreen) {
this.div.focus();
}
}
}
remove() {
this.#cleanDrawLayer();
super.remove();
}
rebuild() {
if (!this.parent) {
return;
}
super.rebuild();
if (this.div === null) {
return;
}
this.#addToDrawLayer();
this.#updateBbox(this.#drawOutlines.box);
if (!this.isAttachedToDOM) {
this.parent.add(this);
}
}
setParent(parent) {
let mustBeSelected = false;
if (this.parent && !parent) {
this._uiManager.removeShouldRescale(this);
this.#cleanDrawLayer();
} else if (parent) {
this._uiManager.addShouldRescale(this);
this.#addToDrawLayer(parent);
mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor");
}
super.setParent(parent);
if (mustBeSelected) {
this.select();
}
}
#cleanDrawLayer() {
if (this._drawId === null || !this.parent) {
return;
}
this.parent.drawLayer.remove(this._drawId);
this._drawId = null;
this._drawingOptions.reset();
}
#addToDrawLayer(parent = this.parent) {
if (this._drawId !== null && this.parent === parent) {
return;
}
if (this._drawId !== null) {
this.parent.drawLayer.updateParent(this._drawId, parent.drawLayer);
return;
}
this._drawingOptions.updateAll();
this._drawId = this.#createDrawing(this.#drawOutlines, parent);
}
#convertToParentSpace([x2, y4, width, height]) {
const {
parentDimensions: [pW, pH],
rotation
} = this;
switch (rotation) {
case 90:
return [y4, 1 - x2, width * (pH / pW), height * (pW / pH)];
case 180:
return [1 - x2, 1 - y4, width, height];
case 270:
return [1 - y4, x2, width * (pH / pW), height * (pW / pH)];
default:
return [x2, y4, width, height];
}
}
#convertToDrawSpace() {
const {
x: x2,
y: y4,
width,
height,
parentDimensions: [pW, pH],
rotation
} = this;
switch (rotation) {
case 90:
return [1 - y4, x2, width * (pW / pH), height * (pH / pW)];
case 180:
return [1 - x2, 1 - y4, width, height];
case 270:
return [y4, 1 - x2, width * (pW / pH), height * (pH / pW)];
default:
return [x2, y4, width, height];
}
}
#updateBbox(bbox) {
[this.x, this.y, this.width, this.height] = this.#convertToParentSpace(bbox);
if (this.div) {
this.fixAndSetPosition();
this.setDims();
}
this._onResized();
}
#rotateBox() {
const {
x: x2,
y: y4,
width,
height,
rotation,
parentRotation,
parentDimensions: [pW, pH]
} = this;
switch ((rotation * 4 + parentRotation) / 90) {
case 1:
return [1 - y4 - height, x2, height, width];
case 2:
return [1 - x2 - width, 1 - y4 - height, width, height];
case 3:
return [y4, 1 - x2 - width, height, width];
case 4:
return [x2, y4 - width * (pW / pH), height * (pH / pW), width * (pW / pH)];
case 5:
return [1 - y4, x2, width * (pW / pH), height * (pH / pW)];
case 6:
return [1 - x2 - height * (pH / pW), 1 - y4, height * (pH / pW), width * (pW / pH)];
case 7:
return [y4 - width * (pW / pH), 1 - x2 - height * (pH / pW), width * (pW / pH), height * (pH / pW)];
case 8:
return [x2 - width, y4 - height, width, height];
case 9:
return [1 - y4, x2 - width, height, width];
case 10:
return [1 - x2, 1 - y4, width, height];
case 11:
return [y4 - height, 1 - x2, height, width];
case 12:
return [x2 - height * (pH / pW), y4, height * (pH / pW), width * (pW / pH)];
case 13:
return [1 - y4 - width * (pW / pH), x2 - height * (pH / pW), width * (pW / pH), height * (pH / pW)];
case 14:
return [1 - x2, 1 - y4 - width * (pW / pH), height * (pH / pW), width * (pW / pH)];
case 15:
return [y4, 1 - x2, width * (pW / pH), height * (pH / pW)];
default:
return [x2, y4, width, height];
}
}
rotate() {
if (!this.parent) {
return;
}
this.parent.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties({
bbox: this.#rotateBox()
}, this.#drawOutlines.updateRotation((this.parentRotation - this.rotation + 360) % 360)));
}
onScaleChanging() {
if (!this.parent) {
return;
}
this.#updateBbox(this.#drawOutlines.updateParentDimensions(this.parentDimensions, this.parent.scale));
}
static onScaleChangingWhenDrawing() {
}
render() {
if (this.div) {
return this.div;
}
let baseX, baseY;
if (this._isCopy) {
baseX = this.x;
baseY = this.y;
}
const div = super.render();
div.classList.add("draw");
const drawDiv = document.createElement("div");
div.append(drawDiv);
drawDiv.setAttribute("aria-hidden", "true");
drawDiv.className = "internal";
this.setDims();
this._uiManager.addShouldRescale(this);
this.disableEditing();
if (this._isCopy) {
this._moveAfterPaste(baseX, baseY);
}
return div;
}
static createDrawerInstance(_x2, _y2, _parentWidth, _parentHeight, _rotation) {
unreachable("Not implemented");
}
static startDrawing(parent, uiManager, _isLTR, event) {
const {
target,
offsetX: x2,
offsetY: y4,
pointerId,
pointerType
} = event;
if (CurrentPointers.isInitializedAndDifferentPointerType(pointerType)) {
return;
}
const {
viewport: {
rotation
}
} = parent;
const {
width: parentWidth,
height: parentHeight
} = target.getBoundingClientRect();
const ac = _DrawingEditor.#currentDrawingAC = new AbortController();
const signal = parent.combinedSignal(ac);
CurrentPointers.setPointer(pointerType, pointerId);
window.addEventListener("pointerup", (e9) => {
if (CurrentPointers.isSamePointerIdOrRemove(e9.pointerId)) {
this._endDraw(e9);
}
}, {
signal
});
window.addEventListener("pointercancel", (e9) => {
if (CurrentPointers.isSamePointerIdOrRemove(e9.pointerId)) {
this._currentParent.endDrawingSession();
}
}, {
signal
});
window.addEventListener("pointerdown", (e9) => {
if (!CurrentPointers.isSamePointerType(e9.pointerType)) {
return;
}
CurrentPointers.initializeAndAddPointerId(e9.pointerId);
if (_DrawingEditor.#currentDraw.isCancellable()) {
_DrawingEditor.#currentDraw.removeLastElement();
if (_DrawingEditor.#currentDraw.isEmpty()) {
this._currentParent.endDrawingSession(true);
} else {
this._endDraw(null);
}
}
}, {
capture: true,
passive: false,
signal
});
window.addEventListener("contextmenu", noContextMenu, {
signal
});
target.addEventListener("pointermove", this._drawMove.bind(this), {
signal
});
target.addEventListener("touchmove", (e9) => {
if (CurrentPointers.isSameTimeStamp(e9.timeStamp)) {
stopEvent(e9);
}
}, {
signal
});
parent.toggleDrawing();
uiManager._editorUndoBar?.hide();
if (_DrawingEditor.#currentDraw) {
parent.drawLayer.updateProperties(this._currentDrawId, _DrawingEditor.#currentDraw.startNew(x2, y4, parentWidth, parentHeight, rotation));
return;
}
uiManager.updateUIForDefaultProperties(this);
_DrawingEditor.#currentDraw = this.createDrawerInstance(x2, y4, parentWidth, parentHeight, rotation);
_DrawingEditor.#currentDrawingOptions = this.getDefaultDrawingOptions();
this._currentParent = parent;
({
id: this._currentDrawId
} = parent.drawLayer.draw(this._mergeSVGProperties(_DrawingEditor.#currentDrawingOptions.toSVGProperties(), _DrawingEditor.#currentDraw.defaultSVGProperties), true, false));
}
static _drawMove(event) {
CurrentPointers.isSameTimeStamp(event.timeStamp);
if (!_DrawingEditor.#currentDraw) {
return;
}
const {
offsetX,
offsetY,
pointerId
} = event;
if (!CurrentPointers.isSamePointerId(pointerId)) {
return;
}
if (CurrentPointers.isUsingMultiplePointers()) {
this._endDraw(event);
return;
}
this._currentParent.drawLayer.updateProperties(this._currentDrawId, _DrawingEditor.#currentDraw.add(offsetX, offsetY));
CurrentPointers.setTimeStamp(event.timeStamp);
stopEvent(event);
}
static _cleanup(all) {
if (all) {
this._currentDrawId = -1;
this._currentParent = null;
_DrawingEditor.#currentDraw = null;
_DrawingEditor.#currentDrawingOptions = null;
CurrentPointers.clearPointerType();
CurrentPointers.clearTimeStamp();
}
if (_DrawingEditor.#currentDrawingAC) {
_DrawingEditor.#currentDrawingAC.abort();
_DrawingEditor.#currentDrawingAC = null;
CurrentPointers.clearPointerIds();
}
}
static _endDraw(event) {
const parent = this._currentParent;
if (!parent) {
return;
}
parent.toggleDrawing(true);
this._cleanup(false);
if (event?.target === parent.div) {
parent.drawLayer.updateProperties(this._currentDrawId, _DrawingEditor.#currentDraw.end(event.offsetX, event.offsetY));
}
if (this.supportMultipleDrawings) {
const draw2 = _DrawingEditor.#currentDraw;
const drawId = this._currentDrawId;
const lastElement = draw2.getLastElement();
parent.addCommands({
cmd: () => {
parent.drawLayer.updateProperties(drawId, draw2.setLastElement(lastElement));
},
undo: () => {
parent.drawLayer.updateProperties(drawId, draw2.removeLastElement());
},
mustExec: false,
type: AnnotationEditorParamsType.DRAW_STEP
});
return;
}
this.endDrawing(false);
}
static endDrawing(isAborted3) {
const parent = this._currentParent;
if (!parent) {
return null;
}
parent.toggleDrawing(true);
parent.cleanUndoStack(AnnotationEditorParamsType.DRAW_STEP);
if (!_DrawingEditor.#currentDraw.isEmpty()) {
const {
pageDimensions: [pageWidth, pageHeight],
scale
} = parent;
const editor = parent.createAndAddNewEditor({
offsetX: 0,
offsetY: 0
}, false, {
drawId: this._currentDrawId,
drawOutlines: _DrawingEditor.#currentDraw.getOutlines(pageWidth * scale, pageHeight * scale, scale, this._INNER_MARGIN),
drawingOptions: _DrawingEditor.#currentDrawingOptions,
mustBeCommitted: !isAborted3
});
this._cleanup(true);
return editor;
}
parent.drawLayer.remove(this._currentDrawId);
this._cleanup(true);
return null;
}
createDrawingOptions(_data) {
}
static deserializeDraw(_pageX, _pageY, _pageWidth, _pageHeight, _innerWidth, _data) {
unreachable("Not implemented");
}
static async deserialize(data, parent, uiManager) {
const {
rawDims: {
pageWidth,
pageHeight,
pageX,
pageY
}
} = parent.viewport;
const drawOutlines = this.deserializeDraw(pageX, pageY, pageWidth, pageHeight, this._INNER_MARGIN, data);
const editor = await super.deserialize(data, parent, uiManager);
editor.createDrawingOptions(data);
editor.#createDrawOutlines({
drawOutlines
});
editor.#addToDrawLayer();
editor.onScaleChanging();
editor.rotate();
return editor;
}
serializeDraw(isForCopying) {
const [pageX, pageY] = this.pageTranslation;
const [pageWidth, pageHeight] = this.pageDimensions;
return this.#drawOutlines.serialize([pageX, pageY, pageWidth, pageHeight], isForCopying);
}
renderAnnotationElement(annotation) {
annotation.updateEdited({
rect: this.getPDFRect()
});
return null;
}
static canCreateNewEmptyEditor() {
return false;
}
};
InkDrawOutliner = class {
#last = new Float64Array(6);
#line;
#lines;
#rotation;
#thickness;
#points;
#lastSVGPath = "";
#lastIndex = 0;
#outlines = new InkDrawOutline();
#parentWidth;
#parentHeight;
constructor(x2, y4, parentWidth, parentHeight, rotation, thickness) {
this.#parentWidth = parentWidth;
this.#parentHeight = parentHeight;
this.#rotation = rotation;
this.#thickness = thickness;
[x2, y4] = this.#normalizePoint(x2, y4);
const line = this.#line = [NaN, NaN, NaN, NaN, x2, y4];
this.#points = [x2, y4];
this.#lines = [{
line,
points: this.#points
}];
this.#last.set(line, 0);
}
updateProperty(name, value) {
if (name === "stroke-width") {
this.#thickness = value;
}
}
#normalizePoint(x2, y4) {
return Outline._normalizePoint(x2, y4, this.#parentWidth, this.#parentHeight, this.#rotation);
}
isEmpty() {
return !this.#lines || this.#lines.length === 0;
}
isCancellable() {
return this.#points.length <= 10;
}
add(x2, y4) {
[x2, y4] = this.#normalizePoint(x2, y4);
const [x1, y1, x22, y22] = this.#last.subarray(2, 6);
const diffX = x2 - x22;
const diffY = y4 - y22;
const d4 = Math.hypot(this.#parentWidth * diffX, this.#parentHeight * diffY);
if (d4 <= 2) {
return null;
}
this.#points.push(x2, y4);
if (isNaN(x1)) {
this.#last.set([x22, y22, x2, y4], 2);
this.#line.push(NaN, NaN, NaN, NaN, x2, y4);
return {
path: {
d: this.toSVGPath()
}
};
}
if (isNaN(this.#last[0])) {
this.#line.splice(6, 6);
}
this.#last.set([x1, y1, x22, y22, x2, y4], 0);
this.#line.push(...Outline.createBezierPoints(x1, y1, x22, y22, x2, y4));
return {
path: {
d: this.toSVGPath()
}
};
}
end(x2, y4) {
const change = this.add(x2, y4);
if (change) {
return change;
}
if (this.#points.length === 2) {
return {
path: {
d: this.toSVGPath()
}
};
}
return null;
}
startNew(x2, y4, parentWidth, parentHeight, rotation) {
this.#parentWidth = parentWidth;
this.#parentHeight = parentHeight;
this.#rotation = rotation;
[x2, y4] = this.#normalizePoint(x2, y4);
const line = this.#line = [NaN, NaN, NaN, NaN, x2, y4];
this.#points = [x2, y4];
const last = this.#lines.at(-1);
if (last) {
last.line = new Float32Array(last.line);
last.points = new Float32Array(last.points);
}
this.#lines.push({
line,
points: this.#points
});
this.#last.set(line, 0);
this.#lastIndex = 0;
this.toSVGPath();
return null;
}
getLastElement() {
return this.#lines.at(-1);
}
setLastElement(element) {
if (!this.#lines) {
return this.#outlines.setLastElement(element);
}
this.#lines.push(element);
this.#line = element.line;
this.#points = element.points;
this.#lastIndex = 0;
return {
path: {
d: this.toSVGPath()
}
};
}
removeLastElement() {
if (!this.#lines) {
return this.#outlines.removeLastElement();
}
this.#lines.pop();
this.#lastSVGPath = "";
for (let i7 = 0, ii = this.#lines.length; i7 < ii; i7++) {
const {
line,
points
} = this.#lines[i7];
this.#line = line;
this.#points = points;
this.#lastIndex = 0;
this.toSVGPath();
}
return {
path: {
d: this.#lastSVGPath
}
};
}
toSVGPath() {
const firstX = Outline.svgRound(this.#line[4]);
const firstY = Outline.svgRound(this.#line[5]);
if (this.#points.length === 2) {
this.#lastSVGPath = `${this.#lastSVGPath} M ${firstX} ${firstY} Z`;
return this.#lastSVGPath;
}
if (this.#points.length <= 6) {
const i7 = this.#lastSVGPath.lastIndexOf("M");
this.#lastSVGPath = `${this.#lastSVGPath.slice(0, i7)} M ${firstX} ${firstY}`;
this.#lastIndex = 6;
}
if (this.#points.length === 4) {
const secondX = Outline.svgRound(this.#line[10]);
const secondY = Outline.svgRound(this.#line[11]);
this.#lastSVGPath = `${this.#lastSVGPath} L ${secondX} ${secondY}`;
this.#lastIndex = 12;
return this.#lastSVGPath;
}
const buffer = [];
if (this.#lastIndex === 0) {
buffer.push(`M ${firstX} ${firstY}`);
this.#lastIndex = 6;
}
for (let i7 = this.#lastIndex, ii = this.#line.length; i7 < ii; i7 += 6) {
const [c1x, c1y, c2x, c2y, x2, y4] = this.#line.slice(i7, i7 + 6).map(Outline.svgRound);
buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x2} ${y4}`);
}
this.#lastSVGPath += buffer.join(" ");
this.#lastIndex = this.#line.length;
return this.#lastSVGPath;
}
getOutlines(parentWidth, parentHeight, scale, innerMargin) {
const last = this.#lines.at(-1);
last.line = new Float32Array(last.line);
last.points = new Float32Array(last.points);
this.#outlines.build(this.#lines, parentWidth, parentHeight, scale, this.#rotation, this.#thickness, innerMargin);
this.#last = null;
this.#line = null;
this.#lines = null;
this.#lastSVGPath = null;
return this.#outlines;
}
get defaultSVGProperties() {
return {
root: {
viewBox: "0 0 10000 10000"
},
rootClass: {
draw: true
},
bbox: [0, 0, 1, 1]
};
}
};
InkDrawOutline = class extends Outline {
#bbox;
#currentRotation = 0;
#innerMargin;
#lines;
#parentWidth;
#parentHeight;
#parentScale;
#rotation;
#thickness;
build(lines, parentWidth, parentHeight, parentScale, rotation, thickness, innerMargin) {
this.#parentWidth = parentWidth;
this.#parentHeight = parentHeight;
this.#parentScale = parentScale;
this.#rotation = rotation;
this.#thickness = thickness;
this.#innerMargin = innerMargin ?? 0;
this.#lines = lines;
this.#computeBbox();
}
get thickness() {
return this.#thickness;
}
setLastElement(element) {
this.#lines.push(element);
return {
path: {
d: this.toSVGPath()
}
};
}
removeLastElement() {
this.#lines.pop();
return {
path: {
d: this.toSVGPath()
}
};
}
toSVGPath() {
const buffer = [];
for (const {
line
} of this.#lines) {
buffer.push(`M${Outline.svgRound(line[4])} ${Outline.svgRound(line[5])}`);
if (line.length === 6) {
buffer.push("Z");
continue;
}
if (line.length === 12 && isNaN(line[6])) {
buffer.push(`L${Outline.svgRound(line[10])} ${Outline.svgRound(line[11])}`);
continue;
}
for (let i7 = 6, ii = line.length; i7 < ii; i7 += 6) {
const [c1x, c1y, c2x, c2y, x2, y4] = line.subarray(i7, i7 + 6).map(Outline.svgRound);
buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x2} ${y4}`);
}
}
return buffer.join("");
}
serialize([pageX, pageY, pageWidth, pageHeight], isForCopying) {
const serializedLines = [];
const serializedPoints = [];
const [x2, y4, width, height] = this.#getBBoxWithNoMargin();
let tx, ty, sx, sy, x1, y1, x22, y22, rescaleFn;
switch (this.#rotation) {
case 0:
rescaleFn = Outline._rescale;
tx = pageX;
ty = pageY + pageHeight;
sx = pageWidth;
sy = -pageHeight;
x1 = pageX + x2 * pageWidth;
y1 = pageY + (1 - y4 - height) * pageHeight;
x22 = pageX + (x2 + width) * pageWidth;
y22 = pageY + (1 - y4) * pageHeight;
break;
case 90:
rescaleFn = Outline._rescaleAndSwap;
tx = pageX;
ty = pageY;
sx = pageWidth;
sy = pageHeight;
x1 = pageX + y4 * pageWidth;
y1 = pageY + x2 * pageHeight;
x22 = pageX + (y4 + height) * pageWidth;
y22 = pageY + (x2 + width) * pageHeight;
break;
case 180:
rescaleFn = Outline._rescale;
tx = pageX + pageWidth;
ty = pageY;
sx = -pageWidth;
sy = pageHeight;
x1 = pageX + (1 - x2 - width) * pageWidth;
y1 = pageY + y4 * pageHeight;
x22 = pageX + (1 - x2) * pageWidth;
y22 = pageY + (y4 + height) * pageHeight;
break;
case 270:
rescaleFn = Outline._rescaleAndSwap;
tx = pageX + pageWidth;
ty = pageY + pageHeight;
sx = -pageWidth;
sy = -pageHeight;
x1 = pageX + (1 - y4 - height) * pageWidth;
y1 = pageY + (1 - x2 - width) * pageHeight;
x22 = pageX + (1 - y4) * pageWidth;
y22 = pageY + (1 - x2) * pageHeight;
break;
}
for (const {
line,
points
} of this.#lines) {
serializedLines.push(rescaleFn(line, tx, ty, sx, sy, isForCopying ? new Array(line.length) : null));
serializedPoints.push(rescaleFn(points, tx, ty, sx, sy, isForCopying ? new Array(points.length) : null));
}
return {
lines: serializedLines,
points: serializedPoints,
rect: [x1, y1, x22, y22]
};
}
static deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, {
paths: {
lines,
points
},
rotation,
thickness
}) {
const newLines = [];
let tx, ty, sx, sy, rescaleFn;
switch (rotation) {
case 0:
rescaleFn = Outline._rescale;
tx = -pageX / pageWidth;
ty = pageY / pageHeight + 1;
sx = 1 / pageWidth;
sy = -1 / pageHeight;
break;
case 90:
rescaleFn = Outline._rescaleAndSwap;
tx = -pageY / pageHeight;
ty = -pageX / pageWidth;
sx = 1 / pageHeight;
sy = 1 / pageWidth;
break;
case 180:
rescaleFn = Outline._rescale;
tx = pageX / pageWidth + 1;
ty = -pageY / pageHeight;
sx = -1 / pageWidth;
sy = 1 / pageHeight;
break;
case 270:
rescaleFn = Outline._rescaleAndSwap;
tx = pageY / pageHeight + 1;
ty = pageX / pageWidth + 1;
sx = -1 / pageHeight;
sy = -1 / pageWidth;
break;
}
if (!lines) {
lines = [];
for (const point of points) {
const len = point.length;
if (len === 2) {
lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1]]));
continue;
}
if (len === 4) {
lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1], NaN, NaN, NaN, NaN, point[2], point[3]]));
continue;
}
const line = new Float32Array(3 * (len - 2));
lines.push(line);
let [x1, y1, x2, y22] = point.subarray(0, 4);
line.set([NaN, NaN, NaN, NaN, x1, y1], 0);
for (let i7 = 4; i7 < len; i7 += 2) {
const x3 = point[i7];
const y4 = point[i7 + 1];
line.set(Outline.createBezierPoints(x1, y1, x2, y22, x3, y4), (i7 - 2) * 3);
[x1, y1, x2, y22] = [x2, y22, x3, y4];
}
}
}
for (let i7 = 0, ii = lines.length; i7 < ii; i7++) {
newLines.push({
line: rescaleFn(lines[i7].map((x2) => x2 ?? NaN), tx, ty, sx, sy),
points: rescaleFn(points[i7].map((x2) => x2 ?? NaN), tx, ty, sx, sy)
});
}
const outlines = new this.prototype.constructor();
outlines.build(newLines, pageWidth, pageHeight, 1, rotation, thickness, innerMargin);
return outlines;
}
#getMarginComponents(thickness = this.#thickness) {
const margin = this.#innerMargin + thickness / 2 * this.#parentScale;
return this.#rotation % 180 === 0 ? [margin / this.#parentWidth, margin / this.#parentHeight] : [margin / this.#parentHeight, margin / this.#parentWidth];
}
#getBBoxWithNoMargin() {
const [x2, y4, width, height] = this.#bbox;
const [marginX, marginY] = this.#getMarginComponents(0);
return [x2 + marginX, y4 + marginY, width - 2 * marginX, height - 2 * marginY];
}
#computeBbox() {
const bbox = this.#bbox = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
for (const {
line
} of this.#lines) {
if (line.length <= 12) {
for (let i7 = 4, ii = line.length; i7 < ii; i7 += 6) {
Util.pointBoundingBox(line[i7], line[i7 + 1], bbox);
}
continue;
}
let lastX = line[4], lastY = line[5];
for (let i7 = 6, ii = line.length; i7 < ii; i7 += 6) {
const [c1x, c1y, c2x, c2y, x2, y4] = line.subarray(i7, i7 + 6);
Util.bezierBoundingBox(lastX, lastY, c1x, c1y, c2x, c2y, x2, y4, bbox);
lastX = x2;
lastY = y4;
}
}
const [marginX, marginY] = this.#getMarginComponents();
bbox[0] = MathClamp(bbox[0] - marginX, 0, 1);
bbox[1] = MathClamp(bbox[1] - marginY, 0, 1);
bbox[2] = MathClamp(bbox[2] + marginX, 0, 1);
bbox[3] = MathClamp(bbox[3] + marginY, 0, 1);
bbox[2] -= bbox[0];
bbox[3] -= bbox[1];
}
get box() {
return this.#bbox;
}
updateProperty(name, value) {
if (name === "stroke-width") {
return this.#updateThickness(value);
}
return null;
}
#updateThickness(thickness) {
const [oldMarginX, oldMarginY] = this.#getMarginComponents();
this.#thickness = thickness;
const [newMarginX, newMarginY] = this.#getMarginComponents();
const [diffMarginX, diffMarginY] = [newMarginX - oldMarginX, newMarginY - oldMarginY];
const bbox = this.#bbox;
bbox[0] -= diffMarginX;
bbox[1] -= diffMarginY;
bbox[2] += 2 * diffMarginX;
bbox[3] += 2 * diffMarginY;
return bbox;
}
updateParentDimensions([width, height], scale) {
const [oldMarginX, oldMarginY] = this.#getMarginComponents();
this.#parentWidth = width;
this.#parentHeight = height;
this.#parentScale = scale;
const [newMarginX, newMarginY] = this.#getMarginComponents();
const diffMarginX = newMarginX - oldMarginX;
const diffMarginY = newMarginY - oldMarginY;
const bbox = this.#bbox;
bbox[0] -= diffMarginX;
bbox[1] -= diffMarginY;
bbox[2] += 2 * diffMarginX;
bbox[3] += 2 * diffMarginY;
return bbox;
}
updateRotation(rotation) {
this.#currentRotation = rotation;
return {
path: {
transform: this.rotationTransform
}
};
}
get viewBox() {
return this.#bbox.map(Outline.svgRound).join(" ");
}
get defaultProperties() {
const [x2, y4] = this.#bbox;
return {
root: {
viewBox: this.viewBox
},
path: {
"transform-origin": `${Outline.svgRound(x2)} ${Outline.svgRound(y4)}`
}
};
}
get rotationTransform() {
const [, , width, height] = this.#bbox;
let a3 = 0, b4 = 0, c6 = 0, d4 = 0, e9 = 0, f4 = 0;
switch (this.#currentRotation) {
case 90:
b4 = height / width;
c6 = -width / height;
e9 = width;
break;
case 180:
a3 = -1;
d4 = -1;
e9 = width;
f4 = height;
break;
case 270:
b4 = -height / width;
c6 = width / height;
f4 = height;
break;
default:
return "";
}
return `matrix(${a3} ${b4} ${c6} ${d4} ${Outline.svgRound(e9)} ${Outline.svgRound(f4)})`;
}
getPathResizingSVGProperties([newX, newY, newWidth, newHeight]) {
const [marginX, marginY] = this.#getMarginComponents();
const [x2, y4, width, height] = this.#bbox;
if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) {
const tx = newX + newWidth / 2 - (x2 + width / 2);
const ty = newY + newHeight / 2 - (y4 + height / 2);
return {
path: {
"transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
transform: `${this.rotationTransform} translate(${tx} ${ty})`
}
};
}
const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX);
const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY);
const s2x = width / newWidth;
const s2y = height / newHeight;
return {
path: {
"transform-origin": `${Outline.svgRound(x2)} ${Outline.svgRound(y4)}`,
transform: `${this.rotationTransform} scale(${s2x} ${s2y}) translate(${Outline.svgRound(marginX)} ${Outline.svgRound(marginY)}) scale(${s1x} ${s1y}) translate(${Outline.svgRound(-marginX)} ${Outline.svgRound(-marginY)})`
}
};
}
getPathResizedSVGProperties([newX, newY, newWidth, newHeight]) {
const [marginX, marginY] = this.#getMarginComponents();
const bbox = this.#bbox;
const [x2, y4, width, height] = bbox;
bbox[0] = newX;
bbox[1] = newY;
bbox[2] = newWidth;
bbox[3] = newHeight;
if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) {
const tx2 = newX + newWidth / 2 - (x2 + width / 2);
const ty2 = newY + newHeight / 2 - (y4 + height / 2);
for (const {
line,
points
} of this.#lines) {
Outline._translate(line, tx2, ty2, line);
Outline._translate(points, tx2, ty2, points);
}
return {
root: {
viewBox: this.viewBox
},
path: {
"transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
transform: this.rotationTransform || null,
d: this.toSVGPath()
}
};
}
const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX);
const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY);
const tx = -s1x * (x2 + marginX) + newX + marginX;
const ty = -s1y * (y4 + marginY) + newY + marginY;
if (s1x !== 1 || s1y !== 1 || tx !== 0 || ty !== 0) {
for (const {
line,
points
} of this.#lines) {
Outline._rescale(line, tx, ty, s1x, s1y, line);
Outline._rescale(points, tx, ty, s1x, s1y, points);
}
}
return {
root: {
viewBox: this.viewBox
},
path: {
"transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`,
transform: this.rotationTransform || null,
d: this.toSVGPath()
}
};
}
getPathTranslatedSVGProperties([newX, newY], parentDimensions) {
const [newParentWidth, newParentHeight] = parentDimensions;
const bbox = this.#bbox;
const tx = newX - bbox[0];
const ty = newY - bbox[1];
if (this.#parentWidth === newParentWidth && this.#parentHeight === newParentHeight) {
for (const {
line,
points
} of this.#lines) {
Outline._translate(line, tx, ty, line);
Outline._translate(points, tx, ty, points);
}
} else {
const sx = this.#parentWidth / newParentWidth;
const sy = this.#parentHeight / newParentHeight;
this.#parentWidth = newParentWidth;
this.#parentHeight = newParentHeight;
for (const {
line,
points
} of this.#lines) {
Outline._rescale(line, tx, ty, sx, sy, line);
Outline._rescale(points, tx, ty, sx, sy, points);
}
bbox[2] *= sx;
bbox[3] *= sy;
}
bbox[0] = newX;
bbox[1] = newY;
return {
root: {
viewBox: this.viewBox
},
path: {
d: this.toSVGPath(),
"transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`
}
};
}
get defaultSVGProperties() {
const bbox = this.#bbox;
return {
root: {
viewBox: this.viewBox
},
rootClass: {
draw: true
},
path: {
d: this.toSVGPath(),
"transform-origin": `${Outline.svgRound(bbox[0])} ${Outline.svgRound(bbox[1])}`,
transform: this.rotationTransform || null
},
bbox
};
}
};
InkDrawingOptions = class _InkDrawingOptions extends DrawingOptions {
constructor(viewerParameters) {
super();
this._viewParameters = viewerParameters;
super.updateProperties({
fill: "none",
stroke: AnnotationEditor._defaultLineColor,
"stroke-opacity": 1,
"stroke-width": 1,
"stroke-linecap": "round",
"stroke-linejoin": "round",
"stroke-miterlimit": 10
});
}
updateSVGProperty(name, value) {
if (name === "stroke-width") {
value ??= this["stroke-width"];
value *= this._viewParameters.realScale;
}
super.updateSVGProperty(name, value);
}
clone() {
const clone3 = new _InkDrawingOptions(this._viewParameters);
clone3.updateAll(this);
return clone3;
}
};
InkEditor = class _InkEditor extends DrawingEditor {
static _type = "ink";
static _editorType = AnnotationEditorType.INK;
static _defaultDrawingOptions = null;
constructor(params) {
super({
...params,
name: "inkEditor"
});
this._willKeepAspectRatio = true;
this.defaultL10nId = "pdfjs-editor-ink-editor";
}
static initialize(l10n, uiManager) {
AnnotationEditor.initialize(l10n, uiManager);
this._defaultDrawingOptions = new InkDrawingOptions(uiManager.viewParameters);
}
static getDefaultDrawingOptions(options) {
const clone3 = this._defaultDrawingOptions.clone();
clone3.updateProperties(options);
return clone3;
}
static get supportMultipleDrawings() {
return true;
}
static get typesMap() {
return shadow(this, "typesMap", /* @__PURE__ */ new Map([[AnnotationEditorParamsType.INK_THICKNESS, "stroke-width"], [AnnotationEditorParamsType.INK_COLOR, "stroke"], [AnnotationEditorParamsType.INK_OPACITY, "stroke-opacity"]]));
}
static createDrawerInstance(x2, y4, parentWidth, parentHeight, rotation) {
return new InkDrawOutliner(x2, y4, parentWidth, parentHeight, rotation, this._defaultDrawingOptions["stroke-width"]);
}
static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) {
return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);
}
static async deserialize(data, parent, uiManager) {
let initialData = null;
if (data instanceof InkAnnotationElement) {
const {
data: {
inkLists,
rect,
rotation,
id,
color: color2,
opacity,
borderStyle: {
rawWidth: thickness
},
popupRef,
richText,
contentsObj,
creationDate,
modificationDate
},
parent: {
page: {
pageNumber
}
}
} = data;
initialData = data = {
annotationType: AnnotationEditorType.INK,
color: Array.from(color2),
thickness,
opacity,
paths: {
points: inkLists
},
boxes: null,
pageIndex: pageNumber - 1,
rect: rect.slice(0),
rotation,
annotationElementId: id,
id,
deleted: false,
popupRef,
richText,
comment: contentsObj?.str || null,
creationDate,
modificationDate
};
}
const editor = await super.deserialize(data, parent, uiManager);
editor._initialData = initialData;
if (data.comment) {
editor.setCommentData(data);
}
return editor;
}
get toolbarButtons() {
this._colorPicker ||= new BasicColorPicker(this);
return [["colorPicker", this._colorPicker]];
}
get colorType() {
return AnnotationEditorParamsType.INK_COLOR;
}
get color() {
return this._drawingOptions.stroke;
}
get opacity() {
return this._drawingOptions["stroke-opacity"];
}
onScaleChanging() {
if (!this.parent) {
return;
}
super.onScaleChanging();
const {
_drawId,
_drawingOptions,
parent
} = this;
_drawingOptions.updateSVGProperty("stroke-width");
parent.drawLayer.updateProperties(_drawId, _drawingOptions.toSVGProperties());
}
static onScaleChangingWhenDrawing() {
const parent = this._currentParent;
if (!parent) {
return;
}
super.onScaleChangingWhenDrawing();
this._defaultDrawingOptions.updateSVGProperty("stroke-width");
parent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties());
}
createDrawingOptions({
color: color2,
thickness,
opacity
}) {
this._drawingOptions = _InkEditor.getDefaultDrawingOptions({
stroke: Util.makeHexColor(...color2),
"stroke-width": thickness,
"stroke-opacity": opacity
});
}
serialize(isForCopying = false) {
if (this.isEmpty()) {
return null;
}
if (this.deleted) {
return this.serializeDeleted();
}
const {
lines,
points
} = this.serializeDraw(isForCopying);
const {
_drawingOptions: {
stroke,
"stroke-opacity": opacity,
"stroke-width": thickness
}
} = this;
const serialized = Object.assign(super.serialize(isForCopying), {
color: AnnotationEditor._colorManager.convert(stroke),
opacity,
thickness,
paths: {
lines,
points
}
});
this.addComment(serialized);
if (isForCopying) {
serialized.isCopy = true;
return serialized;
}
if (this.annotationElementId && !this.#hasElementChanged(serialized)) {
return null;
}
serialized.id = this.annotationElementId;
return serialized;
}
#hasElementChanged(serialized) {
const {
color: color2,
thickness,
opacity,
pageIndex
} = this._initialData;
return this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized || serialized.color.some((c6, i7) => c6 !== color2[i7]) || serialized.thickness !== thickness || serialized.opacity !== opacity || serialized.pageIndex !== pageIndex;
}
renderAnnotationElement(annotation) {
if (this.deleted) {
annotation.hide();
return null;
}
const {
points,
rect
} = this.serializeDraw(false);
annotation.updateEdited({
rect,
thickness: this._drawingOptions["stroke-width"],
points,
popup: this.comment
});
return null;
}
};
ContourDrawOutline = class extends InkDrawOutline {
toSVGPath() {
let path6 = super.toSVGPath();
if (!path6.endsWith("Z")) {
path6 += "Z";
}
return path6;
}
};
BASE_HEADER_LENGTH = 8;
POINTS_PROPERTIES_NUMBER = 3;
SignatureExtractor = class {
static #PARAMETERS = {
maxDim: 512,
sigmaSFactor: 0.02,
sigmaR: 25,
kernelSize: 16
};
static #neighborIndexToId(i0, j0, i7, j3) {
i7 -= i0;
j3 -= j0;
if (i7 === 0) {
return j3 > 0 ? 0 : 4;
}
if (i7 === 1) {
return j3 + 6;
}
return 2 - j3;
}
static #neighborIdToIndex = new Int32Array([0, 1, -1, 1, -1, 0, -1, -1, 0, -1, 1, -1, 1, 0, 1, 1]);
static #clockwiseNonZero(buf, width, i0, j0, i7, j3, offset) {
const id = this.#neighborIndexToId(i0, j0, i7, j3);
for (let k2 = 0; k2 < 8; k2++) {
const kk = (-k2 + id - offset + 16) % 8;
const shiftI = this.#neighborIdToIndex[2 * kk];
const shiftJ = this.#neighborIdToIndex[2 * kk + 1];
if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) {
return kk;
}
}
return -1;
}
static #counterClockwiseNonZero(buf, width, i0, j0, i7, j3, offset) {
const id = this.#neighborIndexToId(i0, j0, i7, j3);
for (let k2 = 0; k2 < 8; k2++) {
const kk = (k2 + id + offset + 16) % 8;
const shiftI = this.#neighborIdToIndex[2 * kk];
const shiftJ = this.#neighborIdToIndex[2 * kk + 1];
if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) {
return kk;
}
}
return -1;
}
static #findContours(buf, width, height, threshold) {
const N3 = buf.length;
const types2 = new Int32Array(N3);
for (let i7 = 0; i7 < N3; i7++) {
types2[i7] = buf[i7] <= threshold ? 1 : 0;
}
for (let i7 = 1; i7 < height - 1; i7++) {
types2[i7 * width] = types2[i7 * width + width - 1] = 0;
}
for (let i7 = 0; i7 < width; i7++) {
types2[i7] = types2[width * height - 1 - i7] = 0;
}
let nbd = 1;
let lnbd;
const contours = [];
for (let i7 = 1; i7 < height - 1; i7++) {
lnbd = 1;
for (let j3 = 1; j3 < width - 1; j3++) {
const ij = i7 * width + j3;
const pix = types2[ij];
if (pix === 0) {
continue;
}
let i22 = i7;
let j22 = j3;
if (pix === 1 && types2[ij - 1] === 0) {
nbd += 1;
j22 -= 1;
} else if (pix >= 1 && types2[ij + 1] === 0) {
nbd += 1;
j22 += 1;
if (pix > 1) {
lnbd = pix;
}
} else {
if (pix !== 1) {
lnbd = Math.abs(pix);
}
continue;
}
const points = [j3, i7];
const isHole = j22 === j3 + 1;
const contour = {
isHole,
points,
id: nbd,
parent: 0
};
contours.push(contour);
let contour0;
for (const c6 of contours) {
if (c6.id === lnbd) {
contour0 = c6;
break;
}
}
if (!contour0) {
contour.parent = isHole ? lnbd : 0;
} else if (contour0.isHole) {
contour.parent = isHole ? contour0.parent : lnbd;
} else {
contour.parent = isHole ? lnbd : contour0.parent;
}
const k2 = this.#clockwiseNonZero(types2, width, i7, j3, i22, j22, 0);
if (k2 === -1) {
types2[ij] = -nbd;
if (types2[ij] !== 1) {
lnbd = Math.abs(types2[ij]);
}
continue;
}
let shiftI = this.#neighborIdToIndex[2 * k2];
let shiftJ = this.#neighborIdToIndex[2 * k2 + 1];
const i1 = i7 + shiftI;
const j1 = j3 + shiftJ;
i22 = i1;
j22 = j1;
let i32 = i7;
let j32 = j3;
while (true) {
const kk = this.#counterClockwiseNonZero(types2, width, i32, j32, i22, j22, 1);
shiftI = this.#neighborIdToIndex[2 * kk];
shiftJ = this.#neighborIdToIndex[2 * kk + 1];
const i42 = i32 + shiftI;
const j4 = j32 + shiftJ;
points.push(j4, i42);
const ij3 = i32 * width + j32;
if (types2[ij3 + 1] === 0) {
types2[ij3] = -nbd;
} else if (types2[ij3] === 1) {
types2[ij3] = nbd;
}
if (i42 === i7 && j4 === j3 && i32 === i1 && j32 === j1) {
if (types2[ij] !== 1) {
lnbd = Math.abs(types2[ij]);
}
break;
} else {
i22 = i32;
j22 = j32;
i32 = i42;
j32 = j4;
}
}
}
}
return contours;
}
static #douglasPeuckerHelper(points, start, end, output) {
if (end - start <= 4) {
for (let i7 = start; i7 < end - 2; i7 += 2) {
output.push(points[i7], points[i7 + 1]);
}
return;
}
const ax = points[start];
const ay = points[start + 1];
const abx = points[end - 4] - ax;
const aby = points[end - 3] - ay;
const dist = Math.hypot(abx, aby);
const nabx = abx / dist;
const naby = aby / dist;
const aa = nabx * ay - naby * ax;
const m4 = aby / abx;
const invS = 1 / dist;
const phi = Math.atan(m4);
const cosPhi = Math.cos(phi);
const sinPhi = Math.sin(phi);
const tmax = invS * (Math.abs(cosPhi) + Math.abs(sinPhi));
const poly = invS * (1 - tmax + tmax ** 2);
const partialPhi = Math.max(Math.atan(Math.abs(sinPhi + cosPhi) * poly), Math.atan(Math.abs(sinPhi - cosPhi) * poly));
let dmax = 0;
let index2 = start;
for (let i7 = start + 2; i7 < end - 2; i7 += 2) {
const d4 = Math.abs(aa - nabx * points[i7 + 1] + naby * points[i7]);
if (d4 > dmax) {
index2 = i7;
dmax = d4;
}
}
if (dmax > (dist * partialPhi) ** 2) {
this.#douglasPeuckerHelper(points, start, index2 + 2, output);
this.#douglasPeuckerHelper(points, index2, end, output);
} else {
output.push(ax, ay);
}
}
static #douglasPeucker(points) {
const output = [];
const len = points.length;
this.#douglasPeuckerHelper(points, 0, len, output);
output.push(points[len - 2], points[len - 1]);
return output.length <= 4 ? null : output;
}
static #bilateralFilter(buf, width, height, sigmaS, sigmaR, kernelSize) {
const kernel = new Float32Array(kernelSize ** 2);
const sigmaS2 = -2 * sigmaS ** 2;
const halfSize = kernelSize >> 1;
for (let i7 = 0; i7 < kernelSize; i7++) {
const x2 = (i7 - halfSize) ** 2;
for (let j3 = 0; j3 < kernelSize; j3++) {
kernel[i7 * kernelSize + j3] = Math.exp((x2 + (j3 - halfSize) ** 2) / sigmaS2);
}
}
const rangeValues = new Float32Array(256);
const sigmaR2 = -2 * sigmaR ** 2;
for (let i7 = 0; i7 < 256; i7++) {
rangeValues[i7] = Math.exp(i7 ** 2 / sigmaR2);
}
const N3 = buf.length;
const out = new Uint8Array(N3);
const histogram = new Uint32Array(256);
for (let i7 = 0; i7 < height; i7++) {
for (let j3 = 0; j3 < width; j3++) {
const ij = i7 * width + j3;
const center = buf[ij];
let sum = 0;
let norm2 = 0;
for (let k2 = 0; k2 < kernelSize; k2++) {
const y4 = i7 + k2 - halfSize;
if (y4 < 0 || y4 >= height) {
continue;
}
for (let l5 = 0; l5 < kernelSize; l5++) {
const x2 = j3 + l5 - halfSize;
if (x2 < 0 || x2 >= width) {
continue;
}
const neighbour = buf[y4 * width + x2];
const w3 = kernel[k2 * kernelSize + l5] * rangeValues[Math.abs(neighbour - center)];
sum += neighbour * w3;
norm2 += w3;
}
}
const pix = out[ij] = Math.round(sum / norm2);
histogram[pix]++;
}
}
return [out, histogram];
}
static #getHistogram(buf) {
const histogram = new Uint32Array(256);
for (const g3 of buf) {
histogram[g3]++;
}
return histogram;
}
static #toUint8(buf) {
const N3 = buf.length;
const out = new Uint8ClampedArray(N3 >> 2);
let max = -Infinity;
let min = Infinity;
for (let i7 = 0, ii = out.length; i7 < ii; i7++) {
const pix = out[i7] = buf[i7 << 2];
max = Math.max(max, pix);
min = Math.min(min, pix);
}
const ratio = 255 / (max - min);
for (let i7 = 0, ii = out.length; i7 < ii; i7++) {
out[i7] = (out[i7] - min) * ratio;
}
return out;
}
static #guessThreshold(histogram) {
let i7;
let M4 = -Infinity;
let L3 = -Infinity;
const min = histogram.findIndex((v4) => v4 !== 0);
let pos = min;
let spos = min;
for (i7 = min; i7 < 256; i7++) {
const v4 = histogram[i7];
if (v4 > M4) {
if (i7 - pos > L3) {
L3 = i7 - pos;
spos = i7 - 1;
}
M4 = v4;
pos = i7;
}
}
for (i7 = spos - 1; i7 >= 0; i7--) {
if (histogram[i7] > histogram[i7 + 1]) {
break;
}
}
return i7;
}
static #getGrayPixels(bitmap) {
const originalBitmap = bitmap;
const {
width,
height
} = bitmap;
const {
maxDim
} = this.#PARAMETERS;
let newWidth = width;
let newHeight = height;
if (width > maxDim || height > maxDim) {
let prevWidth = width;
let prevHeight = height;
let steps2 = Math.log2(Math.max(width, height) / maxDim);
const isteps = Math.floor(steps2);
steps2 = steps2 === isteps ? isteps - 1 : isteps;
for (let i7 = 0; i7 < steps2; i7++) {
newWidth = Math.ceil(prevWidth / 2);
newHeight = Math.ceil(prevHeight / 2);
const offscreen2 = new OffscreenCanvas(newWidth, newHeight);
const ctx2 = offscreen2.getContext("2d");
ctx2.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
prevWidth = newWidth;
prevHeight = newHeight;
if (bitmap !== originalBitmap) {
bitmap.close();
}
bitmap = offscreen2.transferToImageBitmap();
}
const ratio = Math.min(maxDim / newWidth, maxDim / newHeight);
newWidth = Math.round(newWidth * ratio);
newHeight = Math.round(newHeight * ratio);
}
const offscreen = new OffscreenCanvas(newWidth, newHeight);
const ctx = offscreen.getContext("2d", {
willReadFrequently: true
});
ctx.fillStyle = "white";
ctx.fillRect(0, 0, newWidth, newHeight);
ctx.filter = "grayscale(1)";
ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, newWidth, newHeight);
const grayImage = ctx.getImageData(0, 0, newWidth, newHeight).data;
const uint8Buf = this.#toUint8(grayImage);
return [uint8Buf, newWidth, newHeight];
}
static extractContoursFromText(text3, {
fontFamily,
fontStyle,
fontWeight
}, pageWidth, pageHeight, rotation, innerMargin) {
let canvas = new OffscreenCanvas(1, 1);
let ctx = canvas.getContext("2d", {
alpha: false
});
const fontSize = 200;
const font = ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;
const {
actualBoundingBoxLeft,
actualBoundingBoxRight,
actualBoundingBoxAscent,
actualBoundingBoxDescent,
fontBoundingBoxAscent,
fontBoundingBoxDescent,
width
} = ctx.measureText(text3);
const SCALE = 1.5;
const canvasWidth = Math.ceil(Math.max(Math.abs(actualBoundingBoxLeft) + Math.abs(actualBoundingBoxRight) || 0, width) * SCALE);
const canvasHeight = Math.ceil(Math.max(Math.abs(actualBoundingBoxAscent) + Math.abs(actualBoundingBoxDescent) || fontSize, Math.abs(fontBoundingBoxAscent) + Math.abs(fontBoundingBoxDescent) || fontSize) * SCALE);
canvas = new OffscreenCanvas(canvasWidth, canvasHeight);
ctx = canvas.getContext("2d", {
alpha: true,
willReadFrequently: true
});
ctx.font = font;
ctx.filter = "grayscale(1)";
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
ctx.fillStyle = "black";
ctx.fillText(text3, canvasWidth * (SCALE - 1) / 2, canvasHeight * (3 - SCALE) / 2);
const uint8Buf = this.#toUint8(ctx.getImageData(0, 0, canvasWidth, canvasHeight).data);
const histogram = this.#getHistogram(uint8Buf);
const threshold = this.#guessThreshold(histogram);
const contourList = this.#findContours(uint8Buf, canvasWidth, canvasHeight, threshold);
return this.processDrawnLines({
lines: {
curves: contourList,
width: canvasWidth,
height: canvasHeight
},
pageWidth,
pageHeight,
rotation,
innerMargin,
mustSmooth: true,
areContours: true
});
}
static process(bitmap, pageWidth, pageHeight, rotation, innerMargin) {
const [uint8Buf, width, height] = this.#getGrayPixels(bitmap);
const [buffer, histogram] = this.#bilateralFilter(uint8Buf, width, height, Math.hypot(width, height) * this.#PARAMETERS.sigmaSFactor, this.#PARAMETERS.sigmaR, this.#PARAMETERS.kernelSize);
const threshold = this.#guessThreshold(histogram);
const contourList = this.#findContours(buffer, width, height, threshold);
return this.processDrawnLines({
lines: {
curves: contourList,
width,
height
},
pageWidth,
pageHeight,
rotation,
innerMargin,
mustSmooth: true,
areContours: true
});
}
static processDrawnLines({
lines,
pageWidth,
pageHeight,
rotation,
innerMargin,
mustSmooth,
areContours
}) {
if (rotation % 180 !== 0) {
[pageWidth, pageHeight] = [pageHeight, pageWidth];
}
const {
curves,
width,
height
} = lines;
const thickness = lines.thickness ?? 0;
const linesAndPoints = [];
const ratio = Math.min(pageWidth / width, pageHeight / height);
const xScale = ratio / pageWidth;
const yScale = ratio / pageHeight;
const newCurves = [];
for (const {
points
} of curves) {
const reducedPoints = mustSmooth ? this.#douglasPeucker(points) : points;
if (!reducedPoints) {
continue;
}
newCurves.push(reducedPoints);
const len = reducedPoints.length;
const newPoints = new Float32Array(len);
const line = new Float32Array(3 * (len === 2 ? 2 : len - 2));
linesAndPoints.push({
line,
points: newPoints
});
if (len === 2) {
newPoints[0] = reducedPoints[0] * xScale;
newPoints[1] = reducedPoints[1] * yScale;
line.set([NaN, NaN, NaN, NaN, newPoints[0], newPoints[1]], 0);
continue;
}
let [x1, y1, x2, y22] = reducedPoints;
x1 *= xScale;
y1 *= yScale;
x2 *= xScale;
y22 *= yScale;
newPoints.set([x1, y1, x2, y22], 0);
line.set([NaN, NaN, NaN, NaN, x1, y1], 0);
for (let i7 = 4; i7 < len; i7 += 2) {
const x3 = newPoints[i7] = reducedPoints[i7] * xScale;
const y4 = newPoints[i7 + 1] = reducedPoints[i7 + 1] * yScale;
line.set(Outline.createBezierPoints(x1, y1, x2, y22, x3, y4), (i7 - 2) * 3);
[x1, y1, x2, y22] = [x2, y22, x3, y4];
}
}
if (linesAndPoints.length === 0) {
return null;
}
const outline = areContours ? new ContourDrawOutline() : new InkDrawOutline();
outline.build(linesAndPoints, pageWidth, pageHeight, 1, rotation, areContours ? 0 : thickness, innerMargin);
return {
outline,
newCurves,
areContours,
thickness,
width,
height
};
}
static async compressSignature({
outlines,
areContours,
thickness,
width,
height
}) {
let minDiff = Infinity;
let maxDiff = -Infinity;
let outlinesLength = 0;
for (const points of outlines) {
outlinesLength += points.length;
for (let i7 = 2, ii = points.length; i7 < ii; i7++) {
const dx = points[i7] - points[i7 - 2];
minDiff = Math.min(minDiff, dx);
maxDiff = Math.max(maxDiff, dx);
}
}
let bufferType;
if (minDiff >= -128 && maxDiff <= 127) {
bufferType = Int8Array;
} else if (minDiff >= -32768 && maxDiff <= 32767) {
bufferType = Int16Array;
} else {
bufferType = Int32Array;
}
const len = outlines.length;
const headerLength = BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * len;
const header = new Uint32Array(headerLength);
let offset = 0;
header[offset++] = headerLength * Uint32Array.BYTES_PER_ELEMENT + (outlinesLength - 2 * len) * bufferType.BYTES_PER_ELEMENT;
header[offset++] = 0;
header[offset++] = width;
header[offset++] = height;
header[offset++] = areContours ? 0 : 1;
header[offset++] = Math.max(0, Math.floor(thickness ?? 0));
header[offset++] = len;
header[offset++] = bufferType.BYTES_PER_ELEMENT;
for (const points of outlines) {
header[offset++] = points.length - 2;
header[offset++] = points[0];
header[offset++] = points[1];
}
const cs = new CompressionStream("deflate-raw");
const writer = cs.writable.getWriter();
await writer.ready;
writer.write(header);
const BufferCtor = bufferType.prototype.constructor;
for (const points of outlines) {
const diffs = new BufferCtor(points.length - 2);
for (let i7 = 2, ii = points.length; i7 < ii; i7++) {
diffs[i7 - 2] = points[i7] - points[i7 - 2];
}
writer.write(diffs);
}
writer.close();
const buf = await new Response(cs.readable).arrayBuffer();
const bytes = new Uint8Array(buf);
return toBase64Util(bytes);
}
static async decompressSignature(signatureData) {
try {
const bytes = fromBase64Util(signatureData);
const {
readable,
writable
} = new DecompressionStream("deflate-raw");
const writer = writable.getWriter();
await writer.ready;
writer.write(bytes).then(async () => {
await writer.ready;
await writer.close();
}).catch(() => {
});
let data = null;
let offset = 0;
for await (const chunk of readable) {
data ||= new Uint8Array(new Uint32Array(chunk.buffer, 0, 4)[0]);
data.set(chunk, offset);
offset += chunk.length;
}
const header = new Uint32Array(data.buffer, 0, data.length >> 2);
const version6 = header[1];
if (version6 !== 0) {
throw new Error(`Invalid version: ${version6}`);
}
const width = header[2];
const height = header[3];
const areContours = header[4] === 0;
const thickness = header[5];
const numberOfDrawings = header[6];
const bufferType = header[7];
const outlines = [];
const diffsOffset = (BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * numberOfDrawings) * Uint32Array.BYTES_PER_ELEMENT;
let diffs;
switch (bufferType) {
case Int8Array.BYTES_PER_ELEMENT:
diffs = new Int8Array(data.buffer, diffsOffset);
break;
case Int16Array.BYTES_PER_ELEMENT:
diffs = new Int16Array(data.buffer, diffsOffset);
break;
case Int32Array.BYTES_PER_ELEMENT:
diffs = new Int32Array(data.buffer, diffsOffset);
break;
}
offset = 0;
for (let i7 = 0; i7 < numberOfDrawings; i7++) {
const len = header[POINTS_PROPERTIES_NUMBER * i7 + BASE_HEADER_LENGTH];
const points = new Float32Array(len + 2);
outlines.push(points);
for (let j3 = 0; j3 < POINTS_PROPERTIES_NUMBER - 1; j3++) {
points[j3] = header[POINTS_PROPERTIES_NUMBER * i7 + BASE_HEADER_LENGTH + j3 + 1];
}
for (let j3 = 0; j3 < len; j3++) {
points[j3 + 2] = points[j3] + diffs[offset++];
}
}
return {
areContours,
thickness,
outlines,
width,
height
};
} catch (e9) {
warn(`decompressSignature: ${e9}`);
return null;
}
}
};
SignatureOptions = class _SignatureOptions extends DrawingOptions {
constructor() {
super();
super.updateProperties({
fill: AnnotationEditor._defaultLineColor,
"stroke-width": 0
});
}
clone() {
const clone3 = new _SignatureOptions();
clone3.updateAll(this);
return clone3;
}
};
DrawnSignatureOptions = class _DrawnSignatureOptions extends InkDrawingOptions {
constructor(viewerParameters) {
super(viewerParameters);
super.updateProperties({
stroke: AnnotationEditor._defaultLineColor,
"stroke-width": 1
});
}
clone() {
const clone3 = new _DrawnSignatureOptions(this._viewParameters);
clone3.updateAll(this);
return clone3;
}
};
SignatureEditor = class _SignatureEditor extends DrawingEditor {
#isExtracted = false;
#description = null;
#signatureData = null;
#signatureUUID = null;
static _type = "signature";
static _editorType = AnnotationEditorType.SIGNATURE;
static _defaultDrawingOptions = null;
constructor(params) {
super({
...params,
mustBeCommitted: true,
name: "signatureEditor"
});
this._willKeepAspectRatio = true;
this.#signatureData = params.signatureData || null;
this.#description = null;
this.defaultL10nId = "pdfjs-editor-signature-editor1";
}
static initialize(l10n, uiManager) {
AnnotationEditor.initialize(l10n, uiManager);
this._defaultDrawingOptions = new SignatureOptions();
this._defaultDrawnSignatureOptions = new DrawnSignatureOptions(uiManager.viewParameters);
}
static getDefaultDrawingOptions(options) {
const clone3 = this._defaultDrawingOptions.clone();
clone3.updateProperties(options);
return clone3;
}
static get supportMultipleDrawings() {
return false;
}
static get typesMap() {
return shadow(this, "typesMap", /* @__PURE__ */ new Map());
}
static get isDrawer() {
return false;
}
get telemetryFinalData() {
return {
type: "signature",
hasDescription: !!this.#description
};
}
static computeTelemetryFinalData(data) {
const hasDescriptionStats = data.get("hasDescription");
return {
hasAltText: hasDescriptionStats.get(true) ?? 0,
hasNoAltText: hasDescriptionStats.get(false) ?? 0
};
}
get isResizable() {
return true;
}
onScaleChanging() {
if (this._drawId === null) {
return;
}
super.onScaleChanging();
}
render() {
if (this.div) {
return this.div;
}
let baseX, baseY;
const {
_isCopy
} = this;
if (_isCopy) {
this._isCopy = false;
baseX = this.x;
baseY = this.y;
}
super.render();
if (this._drawId === null) {
if (this.#signatureData) {
const {
lines,
mustSmooth,
areContours,
description,
uuid,
heightInPage
} = this.#signatureData;
const {
rawDims: {
pageWidth,
pageHeight
},
rotation
} = this.parent.viewport;
const outline = SignatureExtractor.processDrawnLines({
lines,
pageWidth,
pageHeight,
rotation,
innerMargin: _SignatureEditor._INNER_MARGIN,
mustSmooth,
areContours
});
this.addSignature(outline, heightInPage, description, uuid);
} else {
this.div.setAttribute("data-l10n-args", JSON.stringify({
description: ""
}));
this.div.hidden = true;
this._uiManager.getSignature(this);
}
} else {
this.div.setAttribute("data-l10n-args", JSON.stringify({
description: this.#description || ""
}));
}
if (_isCopy) {
this._isCopy = true;
this._moveAfterPaste(baseX, baseY);
}
return this.div;
}
setUuid(uuid) {
this.#signatureUUID = uuid;
this.addEditToolbar();
}
getUuid() {
return this.#signatureUUID;
}
get description() {
return this.#description;
}
set description(description) {
this.#description = description;
if (!this.div) {
return;
}
this.div.setAttribute("data-l10n-args", JSON.stringify({
description
}));
super.addEditToolbar().then((toolbar) => {
toolbar?.updateEditSignatureButton(description);
});
}
getSignaturePreview() {
const {
newCurves,
areContours,
thickness,
width,
height
} = this.#signatureData;
const maxDim = Math.max(width, height);
const outlineData = SignatureExtractor.processDrawnLines({
lines: {
curves: newCurves.map((points) => ({
points
})),
thickness,
width,
height
},
pageWidth: maxDim,
pageHeight: maxDim,
rotation: 0,
innerMargin: 0,
mustSmooth: false,
areContours
});
return {
areContours,
outline: outlineData.outline
};
}
get toolbarButtons() {
if (this._uiManager.signatureManager) {
return [["editSignature", this._uiManager.signatureManager]];
}
return super.toolbarButtons;
}
addSignature(data, heightInPage, description, uuid) {
const {
x: savedX,
y: savedY
} = this;
const {
outline
} = this.#signatureData = data;
this.#isExtracted = outline instanceof ContourDrawOutline;
this.description = description;
let drawingOptions;
if (this.#isExtracted) {
drawingOptions = _SignatureEditor.getDefaultDrawingOptions();
} else {
drawingOptions = _SignatureEditor._defaultDrawnSignatureOptions.clone();
drawingOptions.updateProperties({
"stroke-width": outline.thickness
});
}
this._addOutlines({
drawOutlines: outline,
drawingOptions
});
const [, pageHeight] = this.pageDimensions;
let newHeight = heightInPage / pageHeight;
newHeight = newHeight >= 1 ? 0.5 : newHeight;
this.width *= newHeight / this.height;
if (this.width >= 1) {
newHeight *= 0.9 / this.width;
this.width = 0.9;
}
this.height = newHeight;
this.setDims();
this.x = savedX;
this.y = savedY;
this.center();
this._onResized();
this.onScaleChanging();
this.rotate();
this._uiManager.addToAnnotationStorage(this);
this.setUuid(uuid);
this._reportTelemetry({
action: "pdfjs.signature.inserted",
data: {
hasBeenSaved: !!uuid,
hasDescription: !!description
}
});
this.div.hidden = false;
}
getFromImage(bitmap) {
const {
rawDims: {
pageWidth,
pageHeight
},
rotation
} = this.parent.viewport;
return SignatureExtractor.process(bitmap, pageWidth, pageHeight, rotation, _SignatureEditor._INNER_MARGIN);
}
getFromText(text3, fontInfo) {
const {
rawDims: {
pageWidth,
pageHeight
},
rotation
} = this.parent.viewport;
return SignatureExtractor.extractContoursFromText(text3, fontInfo, pageWidth, pageHeight, rotation, _SignatureEditor._INNER_MARGIN);
}
getDrawnSignature(curves) {
const {
rawDims: {
pageWidth,
pageHeight
},
rotation
} = this.parent.viewport;
return SignatureExtractor.processDrawnLines({
lines: curves,
pageWidth,
pageHeight,
rotation,
innerMargin: _SignatureEditor._INNER_MARGIN,
mustSmooth: false,
areContours: false
});
}
createDrawingOptions({
areContours,
thickness
}) {
if (areContours) {
this._drawingOptions = _SignatureEditor.getDefaultDrawingOptions();
} else {
this._drawingOptions = _SignatureEditor._defaultDrawnSignatureOptions.clone();
this._drawingOptions.updateProperties({
"stroke-width": thickness
});
}
}
serialize(isForCopying = false) {
if (this.isEmpty()) {
return null;
}
const {
lines,
points
} = this.serializeDraw(isForCopying);
const {
_drawingOptions: {
"stroke-width": thickness
}
} = this;
const serialized = Object.assign(super.serialize(isForCopying), {
isSignature: true,
areContours: this.#isExtracted,
color: [0, 0, 0],
thickness: this.#isExtracted ? 0 : thickness
});
this.addComment(serialized);
if (isForCopying) {
serialized.paths = {
lines,
points
};
serialized.uuid = this.#signatureUUID;
serialized.isCopy = true;
} else {
serialized.lines = lines;
}
if (this.#description) {
serialized.accessibilityData = {
type: "Figure",
alt: this.#description
};
}
return serialized;
}
static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) {
if (data.areContours) {
return ContourDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);
}
return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data);
}
static async deserialize(data, parent, uiManager) {
const editor = await super.deserialize(data, parent, uiManager);
editor.#isExtracted = data.areContours;
editor.description = data.accessibilityData?.alt || "";
editor.#signatureUUID = data.uuid;
return editor;
}
};
StampEditor = class extends AnnotationEditor {
#bitmap = null;
#bitmapId = null;
#bitmapPromise = null;
#bitmapUrl = null;
#bitmapFile = null;
#bitmapFileName = "";
#canvas = null;
#missingCanvas = false;
#resizeTimeoutId = null;
#isSvg = false;
#hasBeenAddedInUndoStack = false;
static _type = "stamp";
static _editorType = AnnotationEditorType.STAMP;
constructor(params) {
super({
...params,
name: "stampEditor"
});
this.#bitmapUrl = params.bitmapUrl;
this.#bitmapFile = params.bitmapFile;
this.defaultL10nId = "pdfjs-editor-stamp-editor";
}
static initialize(l10n, uiManager) {
AnnotationEditor.initialize(l10n, uiManager);
}
static isHandlingMimeForPasting(mime) {
return SupportedImageMimeTypes.includes(mime);
}
static paste(item, parent) {
parent.pasteEditor({
mode: AnnotationEditorType.STAMP
}, {
bitmapFile: item.getAsFile()
});
}
altTextFinish() {
if (this._uiManager.useNewAltTextFlow) {
this.div.hidden = false;
}
super.altTextFinish();
}
get telemetryFinalData() {
return {
type: "stamp",
hasAltText: !!this.altTextData?.altText
};
}
static computeTelemetryFinalData(data) {
const hasAltTextStats = data.get("hasAltText");
return {
hasAltText: hasAltTextStats.get(true) ?? 0,
hasNoAltText: hasAltTextStats.get(false) ?? 0
};
}
#getBitmapFetched(data, fromId = false) {
if (!data) {
this.remove();
return;
}
this.#bitmap = data.bitmap;
if (!fromId) {
this.#bitmapId = data.id;
this.#isSvg = data.isSvg;
}
if (data.file) {
this.#bitmapFileName = data.file.name;
}
this.#createCanvas();
}
#getBitmapDone() {
this.#bitmapPromise = null;
this._uiManager.enableWaiting(false);
if (!this.#canvas) {
return;
}
if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
this.addEditToolbar().then(() => {
this._editToolbar.hide();
this._uiManager.editAltText(this, true);
});
return;
}
if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) {
this._reportTelemetry({
action: "pdfjs.image.image_added",
data: {
alt_text_modal: false,
alt_text_type: "empty"
}
});
try {
this.mlGuessAltText();
} catch {
}
}
this.div.focus();
}
async mlGuessAltText(imageData = null, updateAltTextData = true) {
if (this.hasAltTextData()) {
return null;
}
const {
mlManager
} = this._uiManager;
if (!mlManager) {
throw new Error("No ML.");
}
if (!await mlManager.isEnabledFor("altText")) {
throw new Error("ML isn't enabled for alt text.");
}
const {
data,
width,
height
} = imageData || this.copyCanvas(null, null, true).imageData;
const response = await mlManager.guess({
name: "altText",
request: {
data,
width,
height,
channels: data.length / (width * height)
}
});
if (!response) {
throw new Error("No response from the AI service.");
}
if (response.error) {
throw new Error("Error from the AI service.");
}
if (response.cancel) {
return null;
}
if (!response.output) {
throw new Error("No valid response from the AI service.");
}
const altText = response.output;
await this.setGuessedAltText(altText);
if (updateAltTextData && !this.hasAltTextData()) {
this.altTextData = {
alt: altText,
decorative: false
};
}
return altText;
}
#getBitmap() {
if (this.#bitmapId) {
this._uiManager.enableWaiting(true);
this._uiManager.imageManager.getFromId(this.#bitmapId).then((data) => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone());
return;
}
if (this.#bitmapUrl) {
const url = this.#bitmapUrl;
this.#bitmapUrl = null;
this._uiManager.enableWaiting(true);
this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then((data) => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
return;
}
if (this.#bitmapFile) {
const file = this.#bitmapFile;
this.#bitmapFile = null;
this._uiManager.enableWaiting(true);
this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then((data) => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone());
return;
}
const input = document.createElement("input");
input.type = "file";
input.accept = SupportedImageMimeTypes.join(",");
const signal = this._uiManager._signal;
this.#bitmapPromise = new Promise((resolve2) => {
input.addEventListener("change", async () => {
if (!input.files || input.files.length === 0) {
this.remove();
} else {
this._uiManager.enableWaiting(true);
const data = await this._uiManager.imageManager.getFromFile(input.files[0]);
this._reportTelemetry({
action: "pdfjs.image.image_selected",
data: {
alt_text_modal: this._uiManager.useNewAltTextFlow
}
});
this.#getBitmapFetched(data);
}
resolve2();
}, {
signal
});
input.addEventListener("cancel", () => {
this.remove();
resolve2();
}, {
signal
});
}).finally(() => this.#getBitmapDone());
input.click();
}
remove() {
if (this.#bitmapId) {
this.#bitmap = null;
this._uiManager.imageManager.deleteId(this.#bitmapId);
this.#canvas?.remove();
this.#canvas = null;
if (this.#resizeTimeoutId) {
clearTimeout(this.#resizeTimeoutId);
this.#resizeTimeoutId = null;
}
}
super.remove();
}
rebuild() {
if (!this.parent) {
if (this.#bitmapId) {
this.#getBitmap();
}
return;
}
super.rebuild();
if (this.div === null) {
return;
}
if (this.#bitmapId && this.#canvas === null) {
this.#getBitmap();
}
if (!this.isAttachedToDOM) {
this.parent.add(this);
}
}
onceAdded(focus) {
this._isDraggable = true;
if (focus) {
this.div.focus();
}
}
isEmpty() {
return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId || this.#missingCanvas);
}
get toolbarButtons() {
return [["altText", this.createAltText()]];
}
get isResizable() {
return true;
}
render() {
if (this.div) {
return this.div;
}
let baseX, baseY;
if (this._isCopy) {
baseX = this.x;
baseY = this.y;
}
super.render();
this.div.hidden = true;
this.createAltText();
if (!this.#missingCanvas) {
if (this.#bitmap) {
this.#createCanvas();
} else {
this.#getBitmap();
}
}
if (this._isCopy) {
this._moveAfterPaste(baseX, baseY);
}
this._uiManager.addShouldRescale(this);
return this.div;
}
setCanvas(annotationElementId, canvas) {
const {
id: bitmapId,
bitmap
} = this._uiManager.imageManager.getFromCanvas(annotationElementId, canvas);
canvas.remove();
if (bitmapId && this._uiManager.imageManager.isValidId(bitmapId)) {
this.#bitmapId = bitmapId;
if (bitmap) {
this.#bitmap = bitmap;
}
this.#missingCanvas = false;
this.#createCanvas();
}
}
_onResized() {
this.onScaleChanging();
}
onScaleChanging() {
if (!this.parent) {
return;
}
if (this.#resizeTimeoutId !== null) {
clearTimeout(this.#resizeTimeoutId);
}
const TIME_TO_WAIT = 200;
this.#resizeTimeoutId = setTimeout(() => {
this.#resizeTimeoutId = null;
this.#drawBitmap();
}, TIME_TO_WAIT);
}
#createCanvas() {
const {
div
} = this;
let {
width,
height
} = this.#bitmap;
const [pageWidth, pageHeight] = this.pageDimensions;
const MAX_RATIO = 0.75;
if (this.width) {
width = this.width * pageWidth;
height = this.height * pageHeight;
} else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) {
const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height);
width *= factor;
height *= factor;
}
this._uiManager.enableWaiting(false);
const canvas = this.#canvas = document.createElement("canvas");
canvas.setAttribute("role", "img");
this.addContainer(canvas);
this.width = width / pageWidth;
this.height = height / pageHeight;
this.setDims();
if (this._initialOptions?.isCentered) {
this.center();
} else {
this.fixAndSetPosition();
}
this._initialOptions = null;
if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) {
div.hidden = false;
}
this.#drawBitmap();
if (!this.#hasBeenAddedInUndoStack) {
this.parent.addUndoableEditor(this);
this.#hasBeenAddedInUndoStack = true;
}
this._reportTelemetry({
action: "inserted_image"
});
if (this.#bitmapFileName) {
this.div.setAttribute("aria-description", this.#bitmapFileName);
}
if (!this.annotationElementId) {
this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert");
}
}
copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) {
if (!maxDataDimension) {
maxDataDimension = 224;
}
const {
width: bitmapWidth,
height: bitmapHeight
} = this.#bitmap;
const outputScale = new OutputScale();
let bitmap = this.#bitmap;
let width = bitmapWidth, height = bitmapHeight;
let canvas = null;
if (maxPreviewDimension) {
if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) {
const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight);
width = Math.floor(bitmapWidth * ratio);
height = Math.floor(bitmapHeight * ratio);
}
canvas = document.createElement("canvas");
const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx);
const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy);
if (!this.#isSvg) {
bitmap = this.#scaleBitmap(scaledWidth, scaledHeight);
}
const ctx = canvas.getContext("2d");
ctx.filter = this._uiManager.hcmFilter;
let white = "white", black = "#cfcfd8";
if (this._uiManager.hcmFilter !== "none") {
black = "black";
} else if (ColorScheme.isDarkMode) {
white = "#8f8f9d";
black = "#42414d";
}
const boxDim = 15;
const boxDimWidth = boxDim * outputScale.sx;
const boxDimHeight = boxDim * outputScale.sy;
const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2);
const patternCtx = pattern.getContext("2d");
patternCtx.fillStyle = white;
patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2);
patternCtx.fillStyle = black;
patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight);
patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight);
ctx.fillStyle = ctx.createPattern(pattern, "repeat");
ctx.fillRect(0, 0, scaledWidth, scaledHeight);
ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
}
let imageData = null;
if (createImageData) {
let dataWidth, dataHeight;
if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) {
dataWidth = bitmap.width;
dataHeight = bitmap.height;
} else {
bitmap = this.#bitmap;
if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) {
const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight);
dataWidth = Math.floor(bitmapWidth * ratio);
dataHeight = Math.floor(bitmapHeight * ratio);
if (!this.#isSvg) {
bitmap = this.#scaleBitmap(dataWidth, dataHeight);
}
}
}
const offscreen = new OffscreenCanvas(dataWidth, dataHeight);
const offscreenCtx = offscreen.getContext("2d", {
willReadFrequently: true
});
offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight);
imageData = {
width: dataWidth,
height: dataHeight,
data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data
};
}
return {
canvas,
width,
height,
imageData
};
}
#scaleBitmap(width, height) {
const {
width: bitmapWidth,
height: bitmapHeight
} = this.#bitmap;
let newWidth = bitmapWidth;
let newHeight = bitmapHeight;
let bitmap = this.#bitmap;
while (newWidth > 2 * width || newHeight > 2 * height) {
const prevWidth = newWidth;
const prevHeight = newHeight;
if (newWidth > 2 * width) {
newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2);
}
if (newHeight > 2 * height) {
newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2);
}
const offscreen = new OffscreenCanvas(newWidth, newHeight);
const ctx = offscreen.getContext("2d");
ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight);
bitmap = offscreen.transferToImageBitmap();
}
return bitmap;
}
#drawBitmap() {
const [parentWidth, parentHeight] = this.parentDimensions;
const {
width,
height
} = this;
const outputScale = new OutputScale();
const scaledWidth = Math.ceil(width * parentWidth * outputScale.sx);
const scaledHeight = Math.ceil(height * parentHeight * outputScale.sy);
const canvas = this.#canvas;
if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) {
return;
}
canvas.width = scaledWidth;
canvas.height = scaledHeight;
const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight);
const ctx = canvas.getContext("2d");
ctx.filter = this._uiManager.hcmFilter;
ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight);
}
#serializeBitmap(toUrl) {
if (toUrl) {
if (this.#isSvg) {
const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId);
if (url) {
return url;
}
}
const canvas = document.createElement("canvas");
({
width: canvas.width,
height: canvas.height
} = this.#bitmap);
const ctx = canvas.getContext("2d");
ctx.drawImage(this.#bitmap, 0, 0);
return canvas.toDataURL();
}
if (this.#isSvg) {
const [pageWidth, pageHeight] = this.pageDimensions;
const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS);
const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS);
const offscreen = new OffscreenCanvas(width, height);
const ctx = offscreen.getContext("2d");
ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height);
return offscreen.transferToImageBitmap();
}
return structuredClone(this.#bitmap);
}
static async deserialize(data, parent, uiManager) {
let initialData = null;
let missingCanvas = false;
if (data instanceof StampAnnotationElement) {
const {
data: {
rect: rect2,
rotation,
id,
structParent,
popupRef,
richText,
contentsObj,
creationDate,
modificationDate
},
container,
parent: {
page: {
pageNumber
}
},
canvas
} = data;
let bitmapId2, bitmap2;
if (canvas) {
delete data.canvas;
({
id: bitmapId2,
bitmap: bitmap2
} = uiManager.imageManager.getFromCanvas(container.id, canvas));
canvas.remove();
} else {
missingCanvas = true;
data._hasNoCanvas = true;
}
const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || "";
initialData = data = {
annotationType: AnnotationEditorType.STAMP,
bitmapId: bitmapId2,
bitmap: bitmap2,
pageIndex: pageNumber - 1,
rect: rect2.slice(0),
rotation,
annotationElementId: id,
id,
deleted: false,
accessibilityData: {
decorative: false,
altText
},
isSvg: false,
structParent,
popupRef,
richText,
comment: contentsObj?.str || null,
creationDate,
modificationDate
};
}
const editor = await super.deserialize(data, parent, uiManager);
const {
rect,
bitmap,
bitmapUrl,
bitmapId,
isSvg,
accessibilityData
} = data;
if (missingCanvas) {
uiManager.addMissingCanvas(data.id, editor);
editor.#missingCanvas = true;
} else if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) {
editor.#bitmapId = bitmapId;
if (bitmap) {
editor.#bitmap = bitmap;
}
} else {
editor.#bitmapUrl = bitmapUrl;
}
editor.#isSvg = isSvg;
const [parentWidth, parentHeight] = editor.pageDimensions;
editor.width = (rect[2] - rect[0]) / parentWidth;
editor.height = (rect[3] - rect[1]) / parentHeight;
if (accessibilityData) {
editor.altTextData = accessibilityData;
}
editor._initialData = initialData;
if (data.comment) {
editor.setCommentData(data);
}
editor.#hasBeenAddedInUndoStack = !!initialData;
return editor;
}
serialize(isForCopying = false, context = null) {
if (this.isEmpty()) {
return null;
}
if (this.deleted) {
return this.serializeDeleted();
}
const serialized = Object.assign(super.serialize(isForCopying), {
bitmapId: this.#bitmapId,
isSvg: this.#isSvg
});
this.addComment(serialized);
if (isForCopying) {
serialized.bitmapUrl = this.#serializeBitmap(true);
serialized.accessibilityData = this.serializeAltText(true);
serialized.isCopy = true;
return serialized;
}
const {
decorative,
altText
} = this.serializeAltText(false);
if (!decorative && altText) {
serialized.accessibilityData = {
type: "Figure",
alt: altText
};
}
if (this.annotationElementId) {
const changes = this.#hasElementChanged(serialized);
if (changes.isSame) {
return null;
}
if (changes.isSameAltText) {
delete serialized.accessibilityData;
} else {
serialized.accessibilityData.structParent = this._initialData.structParent ?? -1;
}
serialized.id = this.annotationElementId;
delete serialized.bitmapId;
return serialized;
}
if (context === null) {
return serialized;
}
context.stamps ||= /* @__PURE__ */ new Map();
const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null;
if (!context.stamps.has(this.#bitmapId)) {
context.stamps.set(this.#bitmapId, {
area,
serialized
});
serialized.bitmap = this.#serializeBitmap(false);
} else if (this.#isSvg) {
const prevData = context.stamps.get(this.#bitmapId);
if (area > prevData.area) {
prevData.area = area;
prevData.serialized.bitmap.close();
prevData.serialized.bitmap = this.#serializeBitmap(false);
}
}
return serialized;
}
#hasElementChanged(serialized) {
const {
pageIndex,
accessibilityData: {
altText
}
} = this._initialData;
const isSamePageIndex = serialized.pageIndex === pageIndex;
const isSameAltText = (serialized.accessibilityData?.alt || "") === altText;
return {
isSame: !this.hasEditedComment && !this._hasBeenMoved && !this._hasBeenResized && isSamePageIndex && isSameAltText,
isSameAltText
};
}
renderAnnotationElement(annotation) {
if (this.deleted) {
annotation.hide();
return null;
}
annotation.updateEdited({
rect: this.getPDFRect(),
popup: this.comment
});
return null;
}
};
AnnotationEditorLayer = class _AnnotationEditorLayer {
#accessibilityManager;
#allowClick = false;
#annotationLayer = null;
#clickAC = null;
#editorFocusTimeoutId = null;
#editors = /* @__PURE__ */ new Map();
#hadPointerDown = false;
#isDisabling = false;
#isEnabling = false;
#drawingAC = null;
#focusedElement = null;
#textLayer = null;
#textSelectionAC = null;
#textLayerDblClickAC = null;
#lastPointerDownTimestamp = -1;
#uiManager;
static _initialized = false;
static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor, SignatureEditor].map((type) => [type._editorType, type]));
constructor({
uiManager,
pageIndex,
div,
structTreeLayer,
accessibilityManager,
annotationLayer,
drawLayer,
textLayer,
viewport,
l10n
}) {
const editorTypes = [..._AnnotationEditorLayer.#editorTypes.values()];
if (!_AnnotationEditorLayer._initialized) {
_AnnotationEditorLayer._initialized = true;
for (const editorType of editorTypes) {
editorType.initialize(l10n, uiManager);
}
}
uiManager.registerEditorTypes(editorTypes);
this.#uiManager = uiManager;
this.pageIndex = pageIndex;
this.div = div;
this.#accessibilityManager = accessibilityManager;
this.#annotationLayer = annotationLayer;
this.viewport = viewport;
this.#textLayer = textLayer;
this.drawLayer = drawLayer;
this._structTree = structTreeLayer;
this.#uiManager.addLayer(this);
}
get isEmpty() {
return this.#editors.size === 0;
}
get isInvisible() {
return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE;
}
updateToolbar(options) {
this.#uiManager.updateToolbar(options);
}
updateMode(mode = this.#uiManager.getMode()) {
this.#cleanup();
switch (mode) {
case AnnotationEditorType.NONE:
this.div.classList.toggle("nonEditing", true);
this.disableTextSelection();
this.togglePointerEvents(false);
this.toggleAnnotationLayerPointerEvents(true);
this.disableClick();
return;
case AnnotationEditorType.INK:
this.disableTextSelection();
this.togglePointerEvents(true);
this.enableClick();
break;
case AnnotationEditorType.HIGHLIGHT:
this.enableTextSelection();
this.togglePointerEvents(false);
this.disableClick();
break;
default:
this.disableTextSelection();
this.togglePointerEvents(true);
this.enableClick();
}
this.toggleAnnotationLayerPointerEvents(false);
const {
classList
} = this.div;
classList.toggle("nonEditing", false);
if (mode === AnnotationEditorType.POPUP) {
classList.toggle("commentEditing", true);
} else {
classList.toggle("commentEditing", false);
for (const editorType of _AnnotationEditorLayer.#editorTypes.values()) {
classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType);
}
}
this.div.hidden = false;
}
hasTextLayer(textLayer) {
return textLayer === this.#textLayer?.div;
}
setEditingState(isEditing) {
this.#uiManager.setEditingState(isEditing);
}
addCommands(params) {
this.#uiManager.addCommands(params);
}
cleanUndoStack(type) {
this.#uiManager.cleanUndoStack(type);
}
toggleDrawing(enabled = false) {
this.div.classList.toggle("drawing", !enabled);
}
togglePointerEvents(enabled = false) {
this.div.classList.toggle("disabled", !enabled);
}
toggleAnnotationLayerPointerEvents(enabled = false) {
this.#annotationLayer?.togglePointerEvents(enabled);
}
get #allEditorsIterator() {
return this.#editors.size !== 0 ? this.#editors.values() : this.#uiManager.getEditors(this.pageIndex);
}
async enable() {
this.#isEnabling = true;
this.div.tabIndex = 0;
this.togglePointerEvents(true);
this.div.classList.toggle("nonEditing", false);
this.#textLayerDblClickAC?.abort();
this.#textLayerDblClickAC = null;
const annotationElementIds = /* @__PURE__ */ new Set();
for (const editor of this.#allEditorsIterator) {
editor.enableEditing();
editor.show(true);
if (editor.annotationElementId) {
this.#uiManager.removeChangedExistingAnnotation(editor);
annotationElementIds.add(editor.annotationElementId);
}
}
const annotationLayer = this.#annotationLayer;
if (annotationLayer) {
for (const editable of annotationLayer.getEditableAnnotations()) {
editable.hide();
if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) {
continue;
}
if (annotationElementIds.has(editable.data.id)) {
continue;
}
const editor = await this.deserialize(editable);
if (!editor) {
continue;
}
this.addOrRebuild(editor);
editor.enableEditing();
}
}
this.#isEnabling = false;
this.#uiManager._eventBus.dispatch("editorsrendered", {
source: this,
pageNumber: this.pageIndex + 1
});
}
disable() {
this.#isDisabling = true;
this.div.tabIndex = -1;
this.togglePointerEvents(false);
this.div.classList.toggle("nonEditing", true);
if (this.#textLayer && !this.#textLayerDblClickAC) {
this.#textLayerDblClickAC = new AbortController();
const signal = this.#uiManager.combinedSignal(this.#textLayerDblClickAC);
this.#textLayer.div.addEventListener("pointerdown", (e9) => {
const DBL_CLICK_THRESHOLD = 500;
const {
clientX,
clientY,
timeStamp
} = e9;
const lastPointerDownTimestamp = this.#lastPointerDownTimestamp;
if (timeStamp - lastPointerDownTimestamp > DBL_CLICK_THRESHOLD) {
this.#lastPointerDownTimestamp = timeStamp;
return;
}
this.#lastPointerDownTimestamp = -1;
const {
classList: classList2
} = this.div;
classList2.toggle("getElements", true);
const elements2 = document.elementsFromPoint(clientX, clientY);
classList2.toggle("getElements", false);
if (!this.div.contains(elements2[0])) {
return;
}
let id;
const regex = new RegExp(`^${AnnotationEditorPrefix}[0-9]+$`);
for (const element of elements2) {
if (regex.test(element.id)) {
id = element.id;
break;
}
}
if (!id) {
return;
}
const editor = this.#editors.get(id);
if (editor?.annotationElementId === null) {
e9.stopPropagation();
e9.preventDefault();
editor.dblclick(e9);
}
}, {
signal,
capture: true
});
}
const annotationLayer = this.#annotationLayer;
const needFakeAnnotation = [];
if (annotationLayer) {
const changedAnnotations = /* @__PURE__ */ new Map();
const resetAnnotations = /* @__PURE__ */ new Map();
for (const editor of this.#allEditorsIterator) {
editor.disableEditing();
if (!editor.annotationElementId) {
needFakeAnnotation.push(editor);
continue;
}
if (editor.serialize() !== null) {
changedAnnotations.set(editor.annotationElementId, editor);
continue;
} else {
resetAnnotations.set(editor.annotationElementId, editor);
}
this.getEditableAnnotation(editor.annotationElementId)?.show();
editor.remove();
}
const editables = annotationLayer.getEditableAnnotations();
for (const editable of editables) {
const {
id
} = editable.data;
if (this.#uiManager.isDeletedAnnotationElement(id)) {
editable.updateEdited({
deleted: true
});
continue;
}
let editor = resetAnnotations.get(id);
if (editor) {
editor.resetAnnotationElement(editable);
editor.show(false);
editable.show();
continue;
}
editor = changedAnnotations.get(id);
if (editor) {
this.#uiManager.addChangedExistingAnnotation(editor);
if (editor.renderAnnotationElement(editable)) {
editor.show(false);
}
}
editable.show();
}
}
this.#cleanup();
if (this.isEmpty) {
this.div.hidden = true;
}
const {
classList
} = this.div;
for (const editorType of _AnnotationEditorLayer.#editorTypes.values()) {
classList.remove(`${editorType._type}Editing`);
}
this.disableTextSelection();
this.toggleAnnotationLayerPointerEvents(true);
annotationLayer?.updateFakeAnnotations(needFakeAnnotation);
this.#isDisabling = false;
}
getEditableAnnotation(id) {
return this.#annotationLayer?.getEditableAnnotation(id) || null;
}
setActiveEditor(editor) {
const currentActive = this.#uiManager.getActive();
if (currentActive === editor) {
return;
}
this.#uiManager.setActiveEditor(editor);
}
enableTextSelection() {
this.div.tabIndex = -1;
if (this.#textLayer?.div && !this.#textSelectionAC) {
this.#textSelectionAC = new AbortController();
const signal = this.#uiManager.combinedSignal(this.#textSelectionAC);
this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), {
signal
});
this.#textLayer.div.classList.add("highlighting");
}
}
disableTextSelection() {
this.div.tabIndex = 0;
if (this.#textLayer?.div && this.#textSelectionAC) {
this.#textSelectionAC.abort();
this.#textSelectionAC = null;
this.#textLayer.div.classList.remove("highlighting");
}
}
#textLayerPointerDown(event) {
this.#uiManager.unselectAll();
const {
target
} = event;
if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) {
const {
isMac
} = util_FeatureTest.platform;
if (event.button !== 0 || event.ctrlKey && isMac) {
return;
}
this.#uiManager.showAllEditors("highlight", true, true);
this.#textLayer.div.classList.add("free");
this.toggleDrawing();
HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", {
target: this.#textLayer.div,
x: event.x,
y: event.y
});
this.#textLayer.div.addEventListener("pointerup", () => {
this.#textLayer.div.classList.remove("free");
this.toggleDrawing(true);
}, {
once: true,
signal: this.#uiManager._signal
});
event.preventDefault();
}
}
enableClick() {
if (this.#clickAC) {
return;
}
this.#clickAC = new AbortController();
const signal = this.#uiManager.combinedSignal(this.#clickAC);
this.div.addEventListener("pointerdown", this.pointerdown.bind(this), {
signal
});
const pointerup = this.pointerup.bind(this);
this.div.addEventListener("pointerup", pointerup, {
signal
});
this.div.addEventListener("pointercancel", pointerup, {
signal
});
}
disableClick() {
this.#clickAC?.abort();
this.#clickAC = null;
}
attach(editor) {
this.#editors.set(editor.id, editor);
const {
annotationElementId
} = editor;
if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) {
this.#uiManager.removeDeletedAnnotationElement(editor);
}
}
detach(editor) {
this.#editors.delete(editor.id);
this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
if (!this.#isDisabling && editor.annotationElementId) {
this.#uiManager.addDeletedAnnotationElement(editor);
}
}
remove(editor) {
this.detach(editor);
this.#uiManager.removeEditor(editor);
editor.div.remove();
editor.isAttachedToDOM = false;
}
changeParent(editor) {
if (editor.parent === this) {
return;
}
if (editor.parent && editor.annotationElementId) {
this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId);
AnnotationEditor.deleteAnnotationElement(editor);
editor.annotationElementId = null;
}
this.attach(editor);
editor.parent?.detach(editor);
editor.setParent(this);
if (editor.div && editor.isAttachedToDOM) {
editor.div.remove();
this.div.append(editor.div);
}
}
add(editor) {
if (editor.parent === this && editor.isAttachedToDOM) {
return;
}
this.changeParent(editor);
this.#uiManager.addEditor(editor);
this.attach(editor);
if (!editor.isAttachedToDOM) {
const div = editor.render();
this.div.append(div);
editor.isAttachedToDOM = true;
}
editor.fixAndSetPosition();
editor.onceAdded(!this.#isEnabling);
this.#uiManager.addToAnnotationStorage(editor);
editor._reportTelemetry(editor.telemetryInitialData);
}
moveEditorInDOM(editor) {
if (!editor.isAttachedToDOM) {
return;
}
const {
activeElement
} = document;
if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) {
editor._focusEventsAllowed = false;
this.#editorFocusTimeoutId = setTimeout(() => {
this.#editorFocusTimeoutId = null;
if (!editor.div.contains(document.activeElement)) {
editor.div.addEventListener("focusin", () => {
editor._focusEventsAllowed = true;
}, {
once: true,
signal: this.#uiManager._signal
});
activeElement.focus();
} else {
editor._focusEventsAllowed = true;
}
}, 0);
}
editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
}
addOrRebuild(editor) {
if (editor.needsToBeRebuilt()) {
editor.parent ||= this;
editor.rebuild();
editor.show();
} else {
this.add(editor);
}
}
addUndoableEditor(editor) {
const cmd = () => editor._uiManager.rebuild(editor);
const undo = () => {
editor.remove();
};
this.addCommands({
cmd,
undo,
mustExec: false
});
}
getEditorByUID(uid2) {
for (const editor of this.#editors.values()) {
if (editor.uid === uid2) {
return editor;
}
}
return null;
}
getNextId() {
return this.#uiManager.getId();
}
get #currentEditorType() {
return _AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode());
}
combinedSignal(ac) {
return this.#uiManager.combinedSignal(ac);
}
#createNewEditor(params) {
const editorType = this.#currentEditorType;
return editorType ? new editorType.prototype.constructor(params) : null;
}
canCreateNewEmptyEditor() {
return this.#currentEditorType?.canCreateNewEmptyEditor();
}
async pasteEditor(options, params) {
this.updateToolbar(options);
await this.#uiManager.updateMode(options.mode);
const {
offsetX,
offsetY
} = this.#getCenterPoint();
const id = this.getNextId();
const editor = this.#createNewEditor({
parent: this,
id,
x: offsetX,
y: offsetY,
uiManager: this.#uiManager,
isCentered: true,
...params
});
if (editor) {
this.add(editor);
}
}
async deserialize(data) {
return await _AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager) || null;
}
createAndAddNewEditor(event, isCentered, data = {}) {
const id = this.getNextId();
const editor = this.#createNewEditor({
parent: this,
id,
x: event.offsetX,
y: event.offsetY,
uiManager: this.#uiManager,
isCentered,
...data
});
if (editor) {
this.add(editor);
}
return editor;
}
get boundingClientRect() {
return this.div.getBoundingClientRect();
}
#getCenterPoint() {
const {
x: x2,
y: y4,
width,
height
} = this.boundingClientRect;
const tlX = Math.max(0, x2);
const tlY = Math.max(0, y4);
const brX = Math.min(window.innerWidth, x2 + width);
const brY = Math.min(window.innerHeight, y4 + height);
const centerX = (tlX + brX) / 2 - x2;
const centerY = (tlY + brY) / 2 - y4;
const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX];
return {
offsetX,
offsetY
};
}
addNewEditor(data = {}) {
this.createAndAddNewEditor(this.#getCenterPoint(), true, data);
}
setSelected(editor) {
this.#uiManager.setSelected(editor);
}
toggleSelected(editor) {
this.#uiManager.toggleSelected(editor);
}
unselect(editor) {
this.#uiManager.unselect(editor);
}
pointerup(event) {
const {
isMac
} = util_FeatureTest.platform;
if (event.button !== 0 || event.ctrlKey && isMac) {
return;
}
if (event.target !== this.div) {
return;
}
if (!this.#hadPointerDown) {
return;
}
this.#hadPointerDown = false;
if (this.#currentEditorType?.isDrawer && this.#currentEditorType.supportMultipleDrawings) {
return;
}
if (!this.#allowClick) {
this.#allowClick = true;
return;
}
const currentMode = this.#uiManager.getMode();
if (currentMode === AnnotationEditorType.STAMP || currentMode === AnnotationEditorType.SIGNATURE) {
this.#uiManager.unselectAll();
return;
}
this.createAndAddNewEditor(event, false);
}
pointerdown(event) {
if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) {
this.enableTextSelection();
}
if (this.#hadPointerDown) {
this.#hadPointerDown = false;
return;
}
const {
isMac
} = util_FeatureTest.platform;
if (event.button !== 0 || event.ctrlKey && isMac) {
return;
}
if (event.target !== this.div) {
return;
}
this.#hadPointerDown = true;
if (this.#currentEditorType?.isDrawer) {
this.startDrawingSession(event);
return;
}
const editor = this.#uiManager.getActive();
this.#allowClick = !editor || editor.isEmpty();
}
startDrawingSession(event) {
this.div.focus({
preventScroll: true
});
if (this.#drawingAC) {
this.#currentEditorType.startDrawing(this, this.#uiManager, false, event);
return;
}
this.#uiManager.setCurrentDrawingSession(this);
this.#drawingAC = new AbortController();
const signal = this.#uiManager.combinedSignal(this.#drawingAC);
this.div.addEventListener("blur", ({
relatedTarget
}) => {
if (relatedTarget && !this.div.contains(relatedTarget)) {
this.#focusedElement = null;
this.commitOrRemove();
}
}, {
signal
});
this.#currentEditorType.startDrawing(this, this.#uiManager, false, event);
}
pause(on) {
if (on) {
const {
activeElement
} = document;
if (this.div.contains(activeElement)) {
this.#focusedElement = activeElement;
}
return;
}
if (this.#focusedElement) {
setTimeout(() => {
this.#focusedElement?.focus();
this.#focusedElement = null;
}, 0);
}
}
endDrawingSession(isAborted3 = false) {
if (!this.#drawingAC) {
return null;
}
this.#uiManager.setCurrentDrawingSession(null);
this.#drawingAC.abort();
this.#drawingAC = null;
this.#focusedElement = null;
return this.#currentEditorType.endDrawing(isAborted3);
}
findNewParent(editor, x2, y4) {
const layer = this.#uiManager.findParent(x2, y4);
if (layer === null || layer === this) {
return false;
}
layer.changeParent(editor);
return true;
}
commitOrRemove() {
if (this.#drawingAC) {
this.endDrawingSession();
return true;
}
return false;
}
onScaleChanging() {
if (!this.#drawingAC) {
return;
}
this.#currentEditorType.onScaleChangingWhenDrawing(this);
}
destroy() {
this.commitOrRemove();
if (this.#uiManager.getActive()?.parent === this) {
this.#uiManager.commitOrRemove();
this.#uiManager.setActiveEditor(null);
}
if (this.#editorFocusTimeoutId) {
clearTimeout(this.#editorFocusTimeoutId);
this.#editorFocusTimeoutId = null;
}
for (const editor of this.#editors.values()) {
this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
editor.setParent(null);
editor.isAttachedToDOM = false;
editor.div.remove();
}
this.div = null;
this.#editors.clear();
this.#uiManager.removeLayer(this);
}
#cleanup() {
for (const editor of this.#editors.values()) {
if (editor.isEmpty()) {
editor.remove();
}
}
}
render({
viewport
}) {
this.viewport = viewport;
setLayerDimensions(this.div, viewport);
for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
this.add(editor);
editor.rebuild();
}
this.updateMode();
}
update({
viewport
}) {
this.#uiManager.commitOrRemove();
this.#cleanup();
const oldRotation = this.viewport.rotation;
const rotation = viewport.rotation;
this.viewport = viewport;
setLayerDimensions(this.div, {
rotation
});
if (oldRotation !== rotation) {
for (const editor of this.#editors.values()) {
editor.rotate(rotation);
}
}
}
get pageDimensions() {
const {
pageWidth,
pageHeight
} = this.viewport.rawDims;
return [pageWidth, pageHeight];
}
get scale() {
return this.#uiManager.viewParameters.realScale;
}
};
DrawLayer = class _DrawLayer {
#parent = null;
#mapping = /* @__PURE__ */ new Map();
#toUpdate = /* @__PURE__ */ new Map();
static #id = 0;
constructor({
pageIndex
}) {
this.pageIndex = pageIndex;
}
setParent(parent) {
if (!this.#parent) {
this.#parent = parent;
return;
}
if (this.#parent !== parent) {
if (this.#mapping.size > 0) {
for (const root of this.#mapping.values()) {
root.remove();
parent.append(root);
}
}
this.#parent = parent;
}
}
static get _svgFactory() {
return shadow(this, "_svgFactory", new DOMSVGFactory());
}
static #setBox(element, [x2, y4, width, height]) {
const {
style
} = element;
style.top = `${100 * y4}%`;
style.left = `${100 * x2}%`;
style.width = `${100 * width}%`;
style.height = `${100 * height}%`;
}
#createSVG() {
const svg = _DrawLayer._svgFactory.create(1, 1, true);
this.#parent.append(svg);
svg.setAttribute("aria-hidden", true);
return svg;
}
#createClipPath(defs, pathId) {
const clipPath = _DrawLayer._svgFactory.createElement("clipPath");
defs.append(clipPath);
const clipPathId = `clip_${pathId}`;
clipPath.setAttribute("id", clipPathId);
clipPath.setAttribute("clipPathUnits", "objectBoundingBox");
const clipPathUse = _DrawLayer._svgFactory.createElement("use");
clipPath.append(clipPathUse);
clipPathUse.setAttribute("href", `#${pathId}`);
clipPathUse.classList.add("clip");
return clipPathId;
}
#updateProperties(element, properties) {
for (const [key, value] of Object.entries(properties)) {
if (value === null) {
element.removeAttribute(key);
} else {
element.setAttribute(key, value);
}
}
}
draw(properties, isPathUpdatable = false, hasClip = false) {
const id = _DrawLayer.#id++;
const root = this.#createSVG();
const defs = _DrawLayer._svgFactory.createElement("defs");
root.append(defs);
const path6 = _DrawLayer._svgFactory.createElement("path");
defs.append(path6);
const pathId = `path_p${this.pageIndex}_${id}`;
path6.setAttribute("id", pathId);
path6.setAttribute("vector-effect", "non-scaling-stroke");
if (isPathUpdatable) {
this.#toUpdate.set(id, path6);
}
const clipPathId = hasClip ? this.#createClipPath(defs, pathId) : null;
const use = _DrawLayer._svgFactory.createElement("use");
root.append(use);
use.setAttribute("href", `#${pathId}`);
this.updateProperties(root, properties);
this.#mapping.set(id, root);
return {
id,
clipPathId: `url(#${clipPathId})`
};
}
drawOutline(properties, mustRemoveSelfIntersections) {
const id = _DrawLayer.#id++;
const root = this.#createSVG();
const defs = _DrawLayer._svgFactory.createElement("defs");
root.append(defs);
const path6 = _DrawLayer._svgFactory.createElement("path");
defs.append(path6);
const pathId = `path_p${this.pageIndex}_${id}`;
path6.setAttribute("id", pathId);
path6.setAttribute("vector-effect", "non-scaling-stroke");
let maskId;
if (mustRemoveSelfIntersections) {
const mask = _DrawLayer._svgFactory.createElement("mask");
defs.append(mask);
maskId = `mask_p${this.pageIndex}_${id}`;
mask.setAttribute("id", maskId);
mask.setAttribute("maskUnits", "objectBoundingBox");
const rect = _DrawLayer._svgFactory.createElement("rect");
mask.append(rect);
rect.setAttribute("width", "1");
rect.setAttribute("height", "1");
rect.setAttribute("fill", "white");
const use = _DrawLayer._svgFactory.createElement("use");
mask.append(use);
use.setAttribute("href", `#${pathId}`);
use.setAttribute("stroke", "none");
use.setAttribute("fill", "black");
use.setAttribute("fill-rule", "nonzero");
use.classList.add("mask");
}
const use1 = _DrawLayer._svgFactory.createElement("use");
root.append(use1);
use1.setAttribute("href", `#${pathId}`);
if (maskId) {
use1.setAttribute("mask", `url(#${maskId})`);
}
const use2 = use1.cloneNode();
root.append(use2);
use1.classList.add("mainOutline");
use2.classList.add("secondaryOutline");
this.updateProperties(root, properties);
this.#mapping.set(id, root);
return id;
}
finalizeDraw(id, properties) {
this.#toUpdate.delete(id);
this.updateProperties(id, properties);
}
updateProperties(elementOrId, properties) {
if (!properties) {
return;
}
const {
root,
bbox,
rootClass,
path: path6
} = properties;
const element = typeof elementOrId === "number" ? this.#mapping.get(elementOrId) : elementOrId;
if (!element) {
return;
}
if (root) {
this.#updateProperties(element, root);
}
if (bbox) {
_DrawLayer.#setBox(element, bbox);
}
if (rootClass) {
const {
classList
} = element;
for (const [className, value] of Object.entries(rootClass)) {
classList.toggle(className, value);
}
}
if (path6) {
const defs = element.firstChild;
const pathElement = defs.firstChild;
this.#updateProperties(pathElement, path6);
}
}
updateParent(id, layer) {
if (layer === this) {
return;
}
const root = this.#mapping.get(id);
if (!root) {
return;
}
layer.#parent.append(root);
this.#mapping.delete(id);
layer.#mapping.set(id, root);
}
remove(id) {
this.#toUpdate.delete(id);
if (this.#parent === null) {
return;
}
this.#mapping.get(id).remove();
this.#mapping.delete(id);
}
destroy() {
this.#parent = null;
for (const root of this.#mapping.values()) {
root.remove();
}
this.#mapping.clear();
this.#toUpdate.clear();
}
};
{
globalThis._pdfjsTestingUtils = {
HighlightOutliner
};
}
globalThis.pdfjsLib = {
AbortException,
AnnotationEditorLayer,
AnnotationEditorParamsType,
AnnotationEditorType,
AnnotationEditorUIManager,
AnnotationLayer,
AnnotationMode,
AnnotationType,
applyOpacity,
build,
ColorPicker,
createValidAbsoluteUrl,
CSSConstants,
DOMSVGFactory,
DrawLayer,
FeatureTest: util_FeatureTest,
fetchData,
findContrastColor,
getDocument,
getFilenameFromUrl,
getPdfFilenameFromUrl,
getRGB,
getUuid,
getXfaPageViewport,
GlobalWorkerOptions,
ImageKind: util_ImageKind,
InvalidPDFException,
isDataScheme,
isPdfFile,
isValidExplicitDest,
MathClamp,
noContextMenu,
normalizeUnicode,
OPS,
OutputScale,
PasswordResponses,
PDFDataRangeTransport,
PDFDateString,
PDFWorker,
PermissionFlag,
PixelsPerInch,
RenderingCancelledException,
renderRichText,
ResponseException,
setLayerDimensions,
shadow,
SignatureExtractor,
stopEvent,
SupportedImageMimeTypes,
TextLayer,
TouchManager,
updateUrlHash,
Util,
VerbosityLevel,
version: version2,
XfaLayer
};
}
});
// ../pi-mono/node_modules/xlsx/xlsx.mjs
function reset_ansi() {
set_ansi(1252);
}
function reset_cp() {
set_cp(1200);
reset_ansi();
}
function char_codes(data) {
var o9 = [];
for (var i7 = 0, len = data.length; i7 < len; ++i7) o9[i7] = data.charCodeAt(i7);
return o9;
}
function utf16leread(data) {
var o9 = [];
for (var i7 = 0; i7 < data.length >> 1; ++i7) o9[i7] = String.fromCharCode(data.charCodeAt(2 * i7) + (data.charCodeAt(2 * i7 + 1) << 8));
return o9.join("");
}
function utf16lereadu(data) {
var o9 = [];
for (var i7 = 0; i7 < data.length >> 1; ++i7) o9[i7] = String.fromCharCode(data[2 * i7] + (data[2 * i7 + 1] << 8));
return o9.join("");
}
function utf16beread(data) {
var o9 = [];
for (var i7 = 0; i7 < data.length >> 1; ++i7) o9[i7] = String.fromCharCode(data.charCodeAt(2 * i7 + 1) + (data.charCodeAt(2 * i7) << 8));
return o9.join("");
}
function Base64_encode(input) {
var o9 = "";
var c1 = 0, c22 = 0, c32 = 0, e1 = 0, e22 = 0, e32 = 0, e42 = 0;
for (var i7 = 0; i7 < input.length; ) {
c1 = input.charCodeAt(i7++);
e1 = c1 >> 2;
c22 = input.charCodeAt(i7++);
e22 = (c1 & 3) << 4 | c22 >> 4;
c32 = input.charCodeAt(i7++);
e32 = (c22 & 15) << 2 | c32 >> 6;
e42 = c32 & 63;
if (isNaN(c22)) {
e32 = e42 = 64;
} else if (isNaN(c32)) {
e42 = 64;
}
o9 += Base64_map.charAt(e1) + Base64_map.charAt(e22) + Base64_map.charAt(e32) + Base64_map.charAt(e42);
}
return o9;
}
function Base64_decode(input) {
var o9 = "";
var c1 = 0, c22 = 0, c32 = 0, e1 = 0, e22 = 0, e32 = 0, e42 = 0;
if (input.slice(0, 5) == "data:") {
var i7 = input.slice(0, 1024).indexOf(";base64,");
if (i7 > -1)
input = input.slice(i7 + 8);
}
input = input.replace(/[^\w\+\/\=]/g, "");
for (var i7 = 0; i7 < input.length; ) {
e1 = Base64_map.indexOf(input.charAt(i7++));
e22 = Base64_map.indexOf(input.charAt(i7++));
c1 = e1 << 2 | e22 >> 4;
o9 += String.fromCharCode(c1);
e32 = Base64_map.indexOf(input.charAt(i7++));
c22 = (e22 & 15) << 4 | e32 >> 2;
if (e32 !== 64) {
o9 += String.fromCharCode(c22);
}
e42 = Base64_map.indexOf(input.charAt(i7++));
c32 = (e32 & 3) << 6 | e42;
if (e42 !== 64) {
o9 += String.fromCharCode(c32);
}
}
return o9;
}
function new_raw_buf(len) {
if (has_buf) return Buffer.alloc ? Buffer.alloc(len) : new Buffer(len);
return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
}
function new_unsafe_buf(len) {
if (has_buf) return Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : new Buffer(len);
return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
}
function a2s(data) {
if (Array.isArray(data)) return data.map(function(c6) {
return String.fromCharCode(c6);
}).join("");
var o9 = [];
for (var i7 = 0; i7 < data.length; ++i7) o9[i7] = String.fromCharCode(data[i7]);
return o9.join("");
}
function ab2a(data) {
if (typeof ArrayBuffer == "undefined") throw new Error("Unsupported");
if (data instanceof ArrayBuffer) return ab2a(new Uint8Array(data));
var o9 = new Array(data.length);
for (var i7 = 0; i7 < data.length; ++i7) o9[i7] = data[i7];
return o9;
}
function utf8decode(content) {
var out = [], widx = 0, L3 = content.length + 250;
var o9 = new_raw_buf(content.length + 255);
for (var ridx = 0; ridx < content.length; ++ridx) {
var c6 = content.charCodeAt(ridx);
if (c6 < 128) o9[widx++] = c6;
else if (c6 < 2048) {
o9[widx++] = 192 | c6 >> 6 & 31;
o9[widx++] = 128 | c6 & 63;
} else if (c6 >= 55296 && c6 < 57344) {
c6 = (c6 & 1023) + 64;
var d4 = content.charCodeAt(++ridx) & 1023;
o9[widx++] = 240 | c6 >> 8 & 7;
o9[widx++] = 128 | c6 >> 2 & 63;
o9[widx++] = 128 | d4 >> 6 & 15 | (c6 & 3) << 4;
o9[widx++] = 128 | d4 & 63;
} else {
o9[widx++] = 224 | c6 >> 12 & 15;
o9[widx++] = 128 | c6 >> 6 & 63;
o9[widx++] = 128 | c6 & 63;
}
if (widx > L3) {
out.push(o9.slice(0, widx));
widx = 0;
o9 = new_raw_buf(65535);
L3 = 65530;
}
}
out.push(o9.slice(0, widx));
return bconcat(out);
}
function _strrev(x2) {
var o9 = "", i7 = x2.length - 1;
while (i7 >= 0) o9 += x2.charAt(i7--);
return o9;
}
function pad0(v4, d4) {
var t6 = "" + v4;
return t6.length >= d4 ? t6 : fill("0", d4 - t6.length) + t6;
}
function pad_(v4, d4) {
var t6 = "" + v4;
return t6.length >= d4 ? t6 : fill(" ", d4 - t6.length) + t6;
}
function rpad_(v4, d4) {
var t6 = "" + v4;
return t6.length >= d4 ? t6 : t6 + fill(" ", d4 - t6.length);
}
function pad0r1(v4, d4) {
var t6 = "" + Math.round(v4);
return t6.length >= d4 ? t6 : fill("0", d4 - t6.length) + t6;
}
function pad0r2(v4, d4) {
var t6 = "" + v4;
return t6.length >= d4 ? t6 : fill("0", d4 - t6.length) + t6;
}
function pad0r(v4, d4) {
if (v4 > p2_32 || v4 < -p2_32) return pad0r1(v4, d4);
var i7 = Math.round(v4);
return pad0r2(i7, d4);
}
function SSF_isgeneral(s6, i7) {
i7 = i7 || 0;
return s6.length >= 7 + i7 && (s6.charCodeAt(i7) | 32) === 103 && (s6.charCodeAt(i7 + 1) | 32) === 101 && (s6.charCodeAt(i7 + 2) | 32) === 110 && (s6.charCodeAt(i7 + 3) | 32) === 101 && (s6.charCodeAt(i7 + 4) | 32) === 114 && (s6.charCodeAt(i7 + 5) | 32) === 97 && (s6.charCodeAt(i7 + 6) | 32) === 108;
}
function SSF_init_table(t6) {
if (!t6) t6 = {};
t6[0] = "General";
t6[1] = "0";
t6[2] = "0.00";
t6[3] = "#,##0";
t6[4] = "#,##0.00";
t6[9] = "0%";
t6[10] = "0.00%";
t6[11] = "0.00E+00";
t6[12] = "# ?/?";
t6[13] = "# ??/??";
t6[14] = "m/d/yy";
t6[15] = "d-mmm-yy";
t6[16] = "d-mmm";
t6[17] = "mmm-yy";
t6[18] = "h:mm AM/PM";
t6[19] = "h:mm:ss AM/PM";
t6[20] = "h:mm";
t6[21] = "h:mm:ss";
t6[22] = "m/d/yy h:mm";
t6[37] = "#,##0 ;(#,##0)";
t6[38] = "#,##0 ;[Red](#,##0)";
t6[39] = "#,##0.00;(#,##0.00)";
t6[40] = "#,##0.00;[Red](#,##0.00)";
t6[45] = "mm:ss";
t6[46] = "[h]:mm:ss";
t6[47] = "mmss.0";
t6[48] = "##0.0E+0";
t6[49] = "@";
t6[56] = '"\u4E0A\u5348/\u4E0B\u5348 "hh"\u6642"mm"\u5206"ss"\u79D2 "';
return t6;
}
function SSF_frac(x2, D4, mixed) {
var sgn = x2 < 0 ? -1 : 1;
var B3 = x2 * sgn;
var P_2 = 0, P_1 = 1, P3 = 0;
var Q_2 = 1, Q_1 = 0, Q2 = 0;
var A2 = Math.floor(B3);
while (Q_1 < D4) {
A2 = Math.floor(B3);
P3 = A2 * P_1 + P_2;
Q2 = A2 * Q_1 + Q_2;
if (B3 - A2 < 5e-8) break;
B3 = 1 / (B3 - A2);
P_2 = P_1;
P_1 = P3;
Q_2 = Q_1;
Q_1 = Q2;
}
if (Q2 > D4) {
if (Q_1 > D4) {
Q2 = Q_2;
P3 = P_2;
} else {
Q2 = Q_1;
P3 = P_1;
}
}
if (!mixed) return [0, sgn * P3, Q2];
var q2 = Math.floor(sgn * P3 / Q2);
return [q2, sgn * P3 - q2 * Q2, Q2];
}
function SSF_normalize_xl_unsafe(v4) {
var s6 = v4.toPrecision(16);
if (s6.indexOf("e") > -1) {
var m4 = s6.slice(0, s6.indexOf("e"));
m4 = m4.indexOf(".") > -1 ? m4.slice(0, m4.slice(0, 2) == "0." ? 17 : 16) : m4.slice(0, 15) + fill("0", m4.length - 15);
return m4 + s6.slice(s6.indexOf("e"));
}
var n7 = s6.indexOf(".") > -1 ? s6.slice(0, s6.slice(0, 2) == "0." ? 17 : 16) : s6.slice(0, 15) + fill("0", s6.length - 15);
return Number(n7);
}
function SSF_parse_date_code(v4, opts, b22) {
if (v4 > 2958465 || v4 < 0) return null;
v4 = SSF_normalize_xl_unsafe(v4);
var date = v4 | 0, time = Math.floor(86400 * (v4 - date)), dow = 0;
var dout = [];
var out = { D: date, T: time, u: 86400 * (v4 - date) - time, y: 0, m: 0, d: 0, H: 0, M: 0, S: 0, q: 0 };
if (Math.abs(out.u) < 1e-6) out.u = 0;
if (opts && opts.date1904) date += 1462;
if (out.u > 0.9999) {
out.u = 0;
if (++time == 86400) {
out.T = time = 0;
++date;
++out.D;
}
}
if (date === 60) {
dout = b22 ? [1317, 10, 29] : [1900, 2, 29];
dow = 3;
} else if (date === 0) {
dout = b22 ? [1317, 8, 29] : [1900, 1, 0];
dow = 6;
} else {
if (date > 60) --date;
var d4 = new Date(1900, 0, 1);
d4.setDate(d4.getDate() + date - 1);
dout = [d4.getFullYear(), d4.getMonth() + 1, d4.getDate()];
dow = d4.getDay();
if (date < 60) dow = (dow + 6) % 7;
if (b22) dow = SSF_fix_hijri(d4, dout);
}
out.y = dout[0];
out.m = dout[1];
out.d = dout[2];
out.S = time % 60;
time = Math.floor(time / 60);
out.M = time % 60;
time = Math.floor(time / 60);
out.H = time;
out.q = dow;
return out;
}
function SSF_strip_decimal(o9) {
return o9.indexOf(".") == -1 ? o9 : o9.replace(/(?:\.0*|(\.\d*[1-9])0+)$/, "$1");
}
function SSF_normalize_exp(o9) {
if (o9.indexOf("E") == -1) return o9;
return o9.replace(/(?:\.0*|(\.\d*[1-9])0+)[Ee]/, "$1E").replace(/(E[+-])(\d)$/, "$10$2");
}
function SSF_small_exp(v4) {
var w3 = v4 < 0 ? 12 : 11;
var o9 = SSF_strip_decimal(v4.toFixed(12));
if (o9.length <= w3) return o9;
o9 = v4.toPrecision(10);
if (o9.length <= w3) return o9;
return v4.toExponential(5);
}
function SSF_large_exp(v4) {
var o9 = SSF_strip_decimal(v4.toFixed(11));
return o9.length > (v4 < 0 ? 12 : 11) || o9 === "0" || o9 === "-0" ? v4.toPrecision(6) : o9;
}
function SSF_general_num(v4) {
if (!isFinite(v4)) return isNaN(v4) ? "#NUM!" : "#DIV/0!";
var V3 = Math.floor(Math.log(Math.abs(v4)) * Math.LOG10E), o9;
if (V3 >= -4 && V3 <= -1) o9 = v4.toPrecision(10 + V3);
else if (Math.abs(V3) <= 9) o9 = SSF_small_exp(v4);
else if (V3 === 10) o9 = v4.toFixed(10).substr(0, 12);
else o9 = SSF_large_exp(v4);
return SSF_strip_decimal(SSF_normalize_exp(o9.toUpperCase()));
}
function SSF_general(v4, opts) {
switch (typeof v4) {
case "string":
return v4;
case "boolean":
return v4 ? "TRUE" : "FALSE";
case "number":
return (v4 | 0) === v4 ? v4.toString(10) : SSF_general_num(v4);
case "undefined":
return "";
case "object":
if (v4 == null) return "";
if (v4 instanceof Date) return SSF_format(14, datenum(v4, opts && opts.date1904), opts);
}
throw new Error("unsupported value in General format: " + v4);
}
function SSF_fix_hijri(date, o9) {
o9[0] -= 581;
var dow = date.getDay();
if (date < 60) dow = (dow + 6) % 7;
return dow;
}
function SSF_write_date(type, fmt, val2, ss0) {
var o9 = "", ss = 0, tt = 0, y4 = val2.y, out, outl = 0;
switch (type) {
case 98:
y4 = val2.y + 543;
/* falls through */
case 121:
switch (fmt.length) {
case 1:
case 2:
out = y4 % 100;
outl = 2;
break;
default:
out = y4 % 1e4;
outl = 4;
break;
}
break;
case 109:
switch (fmt.length) {
case 1:
case 2:
out = val2.m;
outl = fmt.length;
break;
case 3:
return months[val2.m - 1][1];
case 5:
return months[val2.m - 1][0];
default:
return months[val2.m - 1][2];
}
break;
case 100:
switch (fmt.length) {
case 1:
case 2:
out = val2.d;
outl = fmt.length;
break;
case 3:
return days[val2.q][0];
default:
return days[val2.q][1];
}
break;
case 104:
switch (fmt.length) {
case 1:
case 2:
out = 1 + (val2.H + 11) % 12;
outl = fmt.length;
break;
default:
throw "bad hour format: " + fmt;
}
break;
case 72:
switch (fmt.length) {
case 1:
case 2:
out = val2.H;
outl = fmt.length;
break;
default:
throw "bad hour format: " + fmt;
}
break;
case 77:
switch (fmt.length) {
case 1:
case 2:
out = val2.M;
outl = fmt.length;
break;
default:
throw "bad minute format: " + fmt;
}
break;
case 115:
if (fmt != "s" && fmt != "ss" && fmt != ".0" && fmt != ".00" && fmt != ".000") throw "bad second format: " + fmt;
if (val2.u === 0 && (fmt == "s" || fmt == "ss")) return pad0(val2.S, fmt.length);
if (ss0 >= 2) tt = ss0 === 3 ? 1e3 : 100;
else tt = ss0 === 1 ? 10 : 1;
ss = Math.round(tt * (val2.S + val2.u));
if (ss >= 60 * tt) ss = 0;
if (fmt === "s") return ss === 0 ? "0" : "" + ss / tt;
o9 = pad0(ss, 2 + ss0);
if (fmt === "ss") return o9.substr(0, 2);
return "." + o9.substr(2, fmt.length - 1);
case 90:
switch (fmt) {
case "[h]":
case "[hh]":
out = val2.D * 24 + val2.H;
break;
case "[m]":
case "[mm]":
out = (val2.D * 24 + val2.H) * 60 + val2.M;
break;
case "[s]":
case "[ss]":
out = ((val2.D * 24 + val2.H) * 60 + val2.M) * 60 + (ss0 == 0 ? Math.round(val2.S + val2.u) : val2.S);
break;
default:
throw "bad abstime format: " + fmt;
}
outl = fmt.length === 3 ? 1 : 2;
break;
case 101:
out = y4;
outl = 1;
break;
}
var outstr = outl > 0 ? pad0(out, outl) : "";
return outstr;
}
function commaify(s6) {
var w3 = 3;
if (s6.length <= w3) return s6;
var j3 = s6.length % w3, o9 = s6.substr(0, j3);
for (; j3 != s6.length; j3 += w3) o9 += (o9.length > 0 ? "," : "") + s6.substr(j3, w3);
return o9;
}
function write_num_pct(type, fmt, val2) {
var sfmt = fmt.replace(pct1, ""), mul = fmt.length - sfmt.length;
return write_num(type, sfmt, val2 * Math.pow(10, 2 * mul)) + fill("%", mul);
}
function write_num_cm(type, fmt, val2) {
var idx = fmt.length - 1;
while (fmt.charCodeAt(idx - 1) === 44) --idx;
return write_num(type, fmt.substr(0, idx), val2 / Math.pow(10, 3 * (fmt.length - idx)));
}
function write_num_exp(fmt, val2) {
var o9;
var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
if (fmt.match(/^#+0.0E\+0$/)) {
if (val2 == 0) return "0.0E+0";
else if (val2 < 0) return "-" + write_num_exp(fmt, -val2);
var period = fmt.indexOf(".");
if (period === -1) period = fmt.indexOf("E");
var ee = Math.floor(Math.log(val2) * Math.LOG10E) % period;
if (ee < 0) ee += period;
o9 = (val2 / Math.pow(10, ee)).toPrecision(idx + 1 + (period + ee) % period);
if (o9.indexOf("e") === -1) {
var fakee = Math.floor(Math.log(val2) * Math.LOG10E);
if (o9.indexOf(".") === -1) o9 = o9.charAt(0) + "." + o9.substr(1) + "E+" + (fakee - o9.length + ee);
else o9 += "E+" + (fakee - ee);
while (o9.substr(0, 2) === "0.") {
o9 = o9.charAt(0) + o9.substr(2, period) + "." + o9.substr(2 + period);
o9 = o9.replace(/^0+([1-9])/, "$1").replace(/^0+\./, "0.");
}
o9 = o9.replace(/\+-/, "-");
}
o9 = o9.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/, function($$, $1, $22, $32) {
return $1 + $22 + $32.substr(0, (period + ee) % period) + "." + $32.substr(ee) + "E";
});
} else o9 = val2.toExponential(idx);
if (fmt.match(/E\+00$/) && o9.match(/e[+-]\d$/)) o9 = o9.substr(0, o9.length - 1) + "0" + o9.charAt(o9.length - 1);
if (fmt.match(/E\-/) && o9.match(/e\+/)) o9 = o9.replace(/e\+/, "e");
return o9.replace("e", "E");
}
function write_num_f1(r8, aval, sign2) {
var den = parseInt(r8[4], 10), rr = Math.round(aval * den), base = Math.floor(rr / den);
var myn = rr - base * den, myd = den;
return sign2 + (base === 0 ? "" : "" + base) + " " + (myn === 0 ? fill(" ", r8[1].length + 1 + r8[4].length) : pad_(myn, r8[1].length) + r8[2] + "/" + r8[3] + pad0(myd, r8[4].length));
}
function write_num_f2(r8, aval, sign2) {
return sign2 + (aval === 0 ? "" : "" + aval) + fill(" ", r8[1].length + 2 + r8[4].length);
}
function hashq(str2) {
var o9 = "", cc;
for (var i7 = 0; i7 != str2.length; ++i7) switch (cc = str2.charCodeAt(i7)) {
case 35:
break;
case 63:
o9 += " ";
break;
case 48:
o9 += "0";
break;
default:
o9 += String.fromCharCode(cc);
}
return o9;
}
function rnd(val2, d4) {
var dd = Math.pow(10, d4);
return "" + Math.round(val2 * dd) / dd;
}
function dec(val2, d4) {
var _frac = val2 - Math.floor(val2), dd = Math.pow(10, d4);
if (d4 < ("" + Math.round(_frac * dd)).length) return 0;
return Math.round(_frac * dd);
}
function carry(val2, d4) {
if (d4 < ("" + Math.round((val2 - Math.floor(val2)) * Math.pow(10, d4))).length) {
return 1;
}
return 0;
}
function flr(val2) {
if (val2 < 2147483647 && val2 > -2147483648) return "" + (val2 >= 0 ? val2 | 0 : val2 - 1 | 0);
return "" + Math.floor(val2);
}
function write_num_flt(type, fmt, val2) {
if (type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
var ffmt = fmt.replace(/\( */, "").replace(/ \)/, "").replace(/\)/, "");
if (val2 >= 0) return write_num_flt("n", ffmt, val2);
return "(" + write_num_flt("n", ffmt, -val2) + ")";
}
if (fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val2);
if (fmt.indexOf("%") !== -1) return write_num_pct(type, fmt, val2);
if (fmt.indexOf("E") !== -1) return write_num_exp(fmt, val2);
if (fmt.charCodeAt(0) === 36) return "$" + write_num_flt(type, fmt.substr(fmt.charAt(1) == " " ? 2 : 1), val2);
var o9;
var r8, ri, ff, aval = Math.abs(val2), sign2 = val2 < 0 ? "-" : "";
if (fmt.match(/^00+$/)) return sign2 + pad0r(aval, fmt.length);
if (fmt.match(/^[#?]+$/)) {
o9 = pad0r(val2, 0);
if (o9 === "0") o9 = "";
return o9.length > fmt.length ? o9 : hashq(fmt.substr(0, fmt.length - o9.length)) + o9;
}
if (r8 = fmt.match(frac1)) return write_num_f1(r8, aval, sign2);
if (fmt.match(/^#+0+$/)) return sign2 + pad0r(aval, fmt.length - fmt.indexOf("0"));
if (r8 = fmt.match(dec1)) {
o9 = rnd(val2, r8[1].length).replace(/^([^\.]+)$/, "$1." + hashq(r8[1])).replace(/\.$/, "." + hashq(r8[1])).replace(/\.(\d*)$/, function($$, $1) {
return "." + $1 + fill("0", hashq(
/*::(*/
r8[1]
).length - $1.length);
});
return fmt.indexOf("0.") !== -1 ? o9 : o9.replace(/^0\./, ".");
}
fmt = fmt.replace(/^#+([0.])/, "$1");
if (r8 = fmt.match(/^(0*)\.(#*)$/)) {
return sign2 + rnd(aval, r8[2].length).replace(/\.(\d*[1-9])0*$/, ".$1").replace(/^(-?\d*)$/, "$1.").replace(/^0\./, r8[1].length ? "0." : ".");
}
if (r8 = fmt.match(/^#{1,3},##0(\.?)$/)) return sign2 + commaify(pad0r(aval, 0));
if (r8 = fmt.match(/^#,##0\.([#0]*0)$/)) {
return val2 < 0 ? "-" + write_num_flt(type, fmt, -val2) : commaify("" + (Math.floor(val2) + carry(val2, r8[1].length))) + "." + pad0(dec(val2, r8[1].length), r8[1].length);
}
if (r8 = fmt.match(/^#,#*,#0/)) return write_num_flt(type, fmt.replace(/^#,#*,/, ""), val2);
if (r8 = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) {
o9 = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g, ""), val2));
ri = 0;
return _strrev(_strrev(fmt.replace(/\\/g, "")).replace(/[0#]/g, function(x3) {
return ri < o9.length ? o9.charAt(ri++) : x3 === "0" ? "0" : "";
}));
}
if (fmt.match(phone)) {
o9 = write_num_flt(type, "##########", val2);
return "(" + o9.substr(0, 3) + ") " + o9.substr(3, 3) + "-" + o9.substr(6);
}
var oa = "";
if (r8 = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) {
ri = Math.min(
/*::String(*/
r8[4].length,
7
);
ff = SSF_frac(aval, Math.pow(10, ri) - 1, false);
o9 = "" + sign2;
oa = write_num(
"n",
/*::String(*/
r8[1],
ff[1]
);
if (oa.charAt(oa.length - 1) == " ") oa = oa.substr(0, oa.length - 1) + "0";
o9 += oa + /*::String(*/
r8[2] + "/" + /*::String(*/
r8[3];
oa = rpad_(ff[2], ri);
if (oa.length < r8[4].length) oa = hashq(r8[4].substr(r8[4].length - oa.length)) + oa;
o9 += oa;
return o9;
}
if (r8 = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) {
ri = Math.min(Math.max(r8[1].length, r8[4].length), 7);
ff = SSF_frac(aval, Math.pow(10, ri) - 1, true);
return sign2 + (ff[0] || (ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1], ri) + r8[2] + "/" + r8[3] + rpad_(ff[2], ri) : fill(" ", 2 * ri + 1 + r8[2].length + r8[3].length));
}
if (r8 = fmt.match(/^[#0?]+$/)) {
o9 = pad0r(val2, 0);
if (fmt.length <= o9.length) return o9;
return hashq(fmt.substr(0, fmt.length - o9.length)) + o9;
}
if (r8 = fmt.match(/^([#0?]+)\.([#0]+)$/)) {
o9 = "" + val2.toFixed(Math.min(r8[2].length, 10)).replace(/([^0])0+$/, "$1");
ri = o9.indexOf(".");
var lres = fmt.indexOf(".") - ri, rres = fmt.length - o9.length - lres;
return hashq(fmt.substr(0, lres) + o9 + fmt.substr(fmt.length - rres));
}
if (r8 = fmt.match(/^00,000\.([#0]*0)$/)) {
ri = dec(val2, r8[1].length);
return val2 < 0 ? "-" + write_num_flt(type, fmt, -val2) : commaify(flr(val2)).replace(/^\d,\d{3}$/, "0$&").replace(/^\d*$/, function($$) {
return "00," + ($$.length < 3 ? pad0(0, 3 - $$.length) : "") + $$;
}) + "." + pad0(ri, r8[1].length);
}
switch (fmt) {
case "###,##0.00":
return write_num_flt(type, "#,##0.00", val2);
case "###,###":
case "##,###":
case "#,###":
var x2 = commaify(pad0r(aval, 0));
return x2 !== "0" ? sign2 + x2 : "";
case "###,###.00":
return write_num_flt(type, "###,##0.00", val2).replace(/^0\./, ".");
case "#,###.00":
return write_num_flt(type, "#,##0.00", val2).replace(/^0\./, ".");
default:
}
throw new Error("unsupported format |" + fmt + "|");
}
function write_num_cm2(type, fmt, val2) {
var idx = fmt.length - 1;
while (fmt.charCodeAt(idx - 1) === 44) --idx;
return write_num(type, fmt.substr(0, idx), val2 / Math.pow(10, 3 * (fmt.length - idx)));
}
function write_num_pct2(type, fmt, val2) {
var sfmt = fmt.replace(pct1, ""), mul = fmt.length - sfmt.length;
return write_num(type, sfmt, val2 * Math.pow(10, 2 * mul)) + fill("%", mul);
}
function write_num_exp2(fmt, val2) {
var o9;
var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
if (fmt.match(/^#+0.0E\+0$/)) {
if (val2 == 0) return "0.0E+0";
else if (val2 < 0) return "-" + write_num_exp2(fmt, -val2);
var period = fmt.indexOf(".");
if (period === -1) period = fmt.indexOf("E");
var ee = Math.floor(Math.log(val2) * Math.LOG10E) % period;
if (ee < 0) ee += period;
o9 = (val2 / Math.pow(10, ee)).toPrecision(idx + 1 + (period + ee) % period);
if (!o9.match(/[Ee]/)) {
var fakee = Math.floor(Math.log(val2) * Math.LOG10E);
if (o9.indexOf(".") === -1) o9 = o9.charAt(0) + "." + o9.substr(1) + "E+" + (fakee - o9.length + ee);
else o9 += "E+" + (fakee - ee);
o9 = o9.replace(/\+-/, "-");
}
o9 = o9.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/, function($$, $1, $22, $32) {
return $1 + $22 + $32.substr(0, (period + ee) % period) + "." + $32.substr(ee) + "E";
});
} else o9 = val2.toExponential(idx);
if (fmt.match(/E\+00$/) && o9.match(/e[+-]\d$/)) o9 = o9.substr(0, o9.length - 1) + "0" + o9.charAt(o9.length - 1);
if (fmt.match(/E\-/) && o9.match(/e\+/)) o9 = o9.replace(/e\+/, "e");
return o9.replace("e", "E");
}
function write_num_int(type, fmt, val2) {
if (type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
var ffmt = fmt.replace(/\( */, "").replace(/ \)/, "").replace(/\)/, "");
if (val2 >= 0) return write_num_int("n", ffmt, val2);
return "(" + write_num_int("n", ffmt, -val2) + ")";
}
if (fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val2);
if (fmt.indexOf("%") !== -1) return write_num_pct2(type, fmt, val2);
if (fmt.indexOf("E") !== -1) return write_num_exp2(fmt, val2);
if (fmt.charCodeAt(0) === 36) return "$" + write_num_int(type, fmt.substr(fmt.charAt(1) == " " ? 2 : 1), val2);
var o9;
var r8, ri, ff, aval = Math.abs(val2), sign2 = val2 < 0 ? "-" : "";
if (fmt.match(/^00+$/)) return sign2 + pad0(aval, fmt.length);
if (fmt.match(/^[#?]+$/)) {
o9 = "" + val2;
if (val2 === 0) o9 = "";
return o9.length > fmt.length ? o9 : hashq(fmt.substr(0, fmt.length - o9.length)) + o9;
}
if (r8 = fmt.match(frac1)) return write_num_f2(r8, aval, sign2);
if (fmt.match(/^#+0+$/)) return sign2 + pad0(aval, fmt.length - fmt.indexOf("0"));
if (r8 = fmt.match(dec1)) {
o9 = ("" + val2).replace(/^([^\.]+)$/, "$1." + hashq(r8[1])).replace(/\.$/, "." + hashq(r8[1]));
o9 = o9.replace(/\.(\d*)$/, function($$, $1) {
return "." + $1 + fill("0", hashq(r8[1]).length - $1.length);
});
return fmt.indexOf("0.") !== -1 ? o9 : o9.replace(/^0\./, ".");
}
fmt = fmt.replace(/^#+([0.])/, "$1");
if (r8 = fmt.match(/^(0*)\.(#*)$/)) {
return sign2 + ("" + aval).replace(/\.(\d*[1-9])0*$/, ".$1").replace(/^(-?\d*)$/, "$1.").replace(/^0\./, r8[1].length ? "0." : ".");
}
if (r8 = fmt.match(/^#{1,3},##0(\.?)$/)) return sign2 + commaify("" + aval);
if (r8 = fmt.match(/^#,##0\.([#0]*0)$/)) {
return val2 < 0 ? "-" + write_num_int(type, fmt, -val2) : commaify("" + val2) + "." + fill("0", r8[1].length);
}
if (r8 = fmt.match(/^#,#*,#0/)) return write_num_int(type, fmt.replace(/^#,#*,/, ""), val2);
if (r8 = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) {
o9 = _strrev(write_num_int(type, fmt.replace(/[\\-]/g, ""), val2));
ri = 0;
return _strrev(_strrev(fmt.replace(/\\/g, "")).replace(/[0#]/g, function(x3) {
return ri < o9.length ? o9.charAt(ri++) : x3 === "0" ? "0" : "";
}));
}
if (fmt.match(phone)) {
o9 = write_num_int(type, "##########", val2);
return "(" + o9.substr(0, 3) + ") " + o9.substr(3, 3) + "-" + o9.substr(6);
}
var oa = "";
if (r8 = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) {
ri = Math.min(
/*::String(*/
r8[4].length,
7
);
ff = SSF_frac(aval, Math.pow(10, ri) - 1, false);
o9 = "" + sign2;
oa = write_num(
"n",
/*::String(*/
r8[1],
ff[1]
);
if (oa.charAt(oa.length - 1) == " ") oa = oa.substr(0, oa.length - 1) + "0";
o9 += oa + /*::String(*/
r8[2] + "/" + /*::String(*/
r8[3];
oa = rpad_(ff[2], ri);
if (oa.length < r8[4].length) oa = hashq(r8[4].substr(r8[4].length - oa.length)) + oa;
o9 += oa;
return o9;
}
if (r8 = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) {
ri = Math.min(Math.max(r8[1].length, r8[4].length), 7);
ff = SSF_frac(aval, Math.pow(10, ri) - 1, true);
return sign2 + (ff[0] || (ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1], ri) + r8[2] + "/" + r8[3] + rpad_(ff[2], ri) : fill(" ", 2 * ri + 1 + r8[2].length + r8[3].length));
}
if (r8 = fmt.match(/^[#0?]+$/)) {
o9 = "" + val2;
if (fmt.length <= o9.length) return o9;
return hashq(fmt.substr(0, fmt.length - o9.length)) + o9;
}
if (r8 = fmt.match(/^([#0]+)\.([#0]+)$/)) {
o9 = "" + val2.toFixed(Math.min(r8[2].length, 10)).replace(/([^0])0+$/, "$1");
ri = o9.indexOf(".");
var lres = fmt.indexOf(".") - ri, rres = fmt.length - o9.length - lres;
return hashq(fmt.substr(0, lres) + o9 + fmt.substr(fmt.length - rres));
}
if (r8 = fmt.match(/^00,000\.([#0]*0)$/)) {
return val2 < 0 ? "-" + write_num_int(type, fmt, -val2) : commaify("" + val2).replace(/^\d,\d{3}$/, "0$&").replace(/^\d*$/, function($$) {
return "00," + ($$.length < 3 ? pad0(0, 3 - $$.length) : "") + $$;
}) + "." + pad0(0, r8[1].length);
}
switch (fmt) {
case "###,###":
case "##,###":
case "#,###":
var x2 = commaify("" + aval);
return x2 !== "0" ? sign2 + x2 : "";
default:
if (fmt.match(/\.[0#?]*$/)) return write_num_int(type, fmt.slice(0, fmt.lastIndexOf(".")), val2) + hashq(fmt.slice(fmt.lastIndexOf(".")));
}
throw new Error("unsupported format |" + fmt + "|");
}
function write_num(type, fmt, val2) {
return (val2 | 0) === val2 ? write_num_int(type, fmt, val2) : write_num_flt(type, fmt, val2);
}
function SSF_split_fmt(fmt) {
var out = [];
var in_str = false;
for (var i7 = 0, j3 = 0; i7 < fmt.length; ++i7) switch (
/*cc=*/
fmt.charCodeAt(i7)
) {
case 34:
in_str = !in_str;
break;
case 95:
case 42:
case 92:
++i7;
break;
case 59:
out[out.length] = fmt.substr(j3, i7 - j3);
j3 = i7 + 1;
}
out[out.length] = fmt.substr(j3);
if (in_str === true) throw new Error("Format |" + fmt + "| unterminated string ");
return out;
}
function fmt_is_date(fmt) {
var i7 = 0, c6 = "", o9 = "";
while (i7 < fmt.length) {
switch (c6 = fmt.charAt(i7)) {
case "G":
if (SSF_isgeneral(fmt, i7)) i7 += 6;
i7++;
break;
case '"':
for (
;
/*cc=*/
fmt.charCodeAt(++i7) !== 34 && i7 < fmt.length;
) {
}
++i7;
break;
case "\\":
i7 += 2;
break;
case "_":
i7 += 2;
break;
case "@":
++i7;
break;
case "B":
case "b":
if (fmt.charAt(i7 + 1) === "1" || fmt.charAt(i7 + 1) === "2") return true;
/* falls through */
case "M":
case "D":
case "Y":
case "H":
case "S":
case "E":
/* falls through */
case "m":
case "d":
case "y":
case "h":
case "s":
case "e":
case "g":
return true;
case "A":
case "a":
case "\u4E0A":
if (fmt.substr(i7, 3).toUpperCase() === "A/P") return true;
if (fmt.substr(i7, 5).toUpperCase() === "AM/PM") return true;
if (fmt.substr(i7, 5).toUpperCase() === "\u4E0A\u5348/\u4E0B\u5348") return true;
++i7;
break;
case "[":
o9 = c6;
while (fmt.charAt(i7++) !== "]" && i7 < fmt.length) o9 += fmt.charAt(i7);
if (o9.match(SSF_abstime)) return true;
break;
case ".":
/* falls through */
case "0":
case "#":
while (i7 < fmt.length && ("0#?.,E+-%".indexOf(c6 = fmt.charAt(++i7)) > -1 || c6 == "\\" && fmt.charAt(i7 + 1) == "-" && "0#".indexOf(fmt.charAt(i7 + 2)) > -1)) {
}
break;
case "?":
while (fmt.charAt(++i7) === c6) {
}
break;
case "*":
++i7;
if (fmt.charAt(i7) == " " || fmt.charAt(i7) == "*") ++i7;
break;
case "(":
case ")":
++i7;
break;
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
while (i7 < fmt.length && "0123456789".indexOf(fmt.charAt(++i7)) > -1) {
}
break;
case " ":
++i7;
break;
default:
++i7;
break;
}
}
return false;
}
function eval_fmt(fmt, v4, opts, flen) {
var out = [], o9 = "", i7 = 0, c6 = "", lst = "t", dt, j3, cc;
var hr = "H";
while (i7 < fmt.length) {
switch (c6 = fmt.charAt(i7)) {
case "G":
if (!SSF_isgeneral(fmt, i7)) throw new Error("unrecognized character " + c6 + " in " + fmt);
out[out.length] = { t: "G", v: "General" };
i7 += 7;
break;
case '"':
for (o9 = ""; (cc = fmt.charCodeAt(++i7)) !== 34 && i7 < fmt.length; ) o9 += String.fromCharCode(cc);
out[out.length] = { t: "t", v: o9 };
++i7;
break;
case "\\":
var w3 = fmt.charAt(++i7), t6 = w3 === "(" || w3 === ")" ? w3 : "t";
out[out.length] = { t: t6, v: w3 };
++i7;
break;
case "_":
out[out.length] = { t: "t", v: " " };
i7 += 2;
break;
case "@":
out[out.length] = { t: "T", v: v4 };
++i7;
break;
case "B":
case "b":
if (fmt.charAt(i7 + 1) === "1" || fmt.charAt(i7 + 1) === "2") {
if (dt == null) {
dt = SSF_parse_date_code(v4, opts, fmt.charAt(i7 + 1) === "2");
if (dt == null) return "";
}
out[out.length] = { t: "X", v: fmt.substr(i7, 2) };
lst = c6;
i7 += 2;
break;
}
/* falls through */
case "M":
case "D":
case "Y":
case "H":
case "S":
case "E":
c6 = c6.toLowerCase();
/* falls through */
case "m":
case "d":
case "y":
case "h":
case "s":
case "e":
case "g":
if (v4 < 0) return "";
if (dt == null) {
dt = SSF_parse_date_code(v4, opts);
if (dt == null) return "";
}
o9 = c6;
while (++i7 < fmt.length && fmt.charAt(i7).toLowerCase() === c6) o9 += c6;
if (c6 === "m" && lst.toLowerCase() === "h") c6 = "M";
if (c6 === "h") c6 = hr;
out[out.length] = { t: c6, v: o9 };
lst = c6;
break;
case "A":
case "a":
case "\u4E0A":
var q2 = { t: c6, v: c6 };
if (dt == null) dt = SSF_parse_date_code(v4, opts);
if (fmt.substr(i7, 3).toUpperCase() === "A/P") {
if (dt != null) q2.v = dt.H >= 12 ? fmt.charAt(i7 + 2) : c6;
q2.t = "T";
hr = "h";
i7 += 3;
} else if (fmt.substr(i7, 5).toUpperCase() === "AM/PM") {
if (dt != null) q2.v = dt.H >= 12 ? "PM" : "AM";
q2.t = "T";
i7 += 5;
hr = "h";
} else if (fmt.substr(i7, 5).toUpperCase() === "\u4E0A\u5348/\u4E0B\u5348") {
if (dt != null) q2.v = dt.H >= 12 ? "\u4E0B\u5348" : "\u4E0A\u5348";
q2.t = "T";
i7 += 5;
hr = "h";
} else {
q2.t = "t";
++i7;
}
if (dt == null && q2.t === "T") return "";
out[out.length] = q2;
lst = c6;
break;
case "[":
o9 = c6;
while (fmt.charAt(i7++) !== "]" && i7 < fmt.length) o9 += fmt.charAt(i7);
if (o9.slice(-1) !== "]") throw 'unterminated "[" block: |' + o9 + "|";
if (o9.match(SSF_abstime)) {
if (dt == null) {
dt = SSF_parse_date_code(v4, opts);
if (dt == null) return "";
}
out[out.length] = { t: "Z", v: o9.toLowerCase() };
lst = o9.charAt(1);
} else if (o9.indexOf("$") > -1) {
o9 = (o9.match(/\$([^-\[\]]*)/) || [])[1] || "$";
if (!fmt_is_date(fmt)) out[out.length] = { t: "t", v: o9 };
}
break;
/* Numbers */
case ".":
if (dt != null) {
o9 = c6;
while (++i7 < fmt.length && (c6 = fmt.charAt(i7)) === "0") o9 += c6;
out[out.length] = { t: "s", v: o9 };
break;
}
/* falls through */
case "0":
case "#":
o9 = c6;
while (++i7 < fmt.length && "0#?.,E+-%".indexOf(c6 = fmt.charAt(i7)) > -1) o9 += c6;
out[out.length] = { t: "n", v: o9 };
break;
case "?":
o9 = c6;
while (fmt.charAt(++i7) === c6) o9 += c6;
out[out.length] = { t: c6, v: o9 };
lst = c6;
break;
case "*":
++i7;
if (fmt.charAt(i7) == " " || fmt.charAt(i7) == "*") ++i7;
break;
// **
case "(":
case ")":
out[out.length] = { t: flen === 1 ? "t" : c6, v: c6 };
++i7;
break;
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
o9 = c6;
while (i7 < fmt.length && "0123456789".indexOf(fmt.charAt(++i7)) > -1) o9 += fmt.charAt(i7);
out[out.length] = { t: "D", v: o9 };
break;
case " ":
out[out.length] = { t: c6, v: c6 };
++i7;
break;
case "$":
out[out.length] = { t: "t", v: "$" };
++i7;
break;
default:
if (",$-+/():!^&'~{}<>=\u20ACacfijklopqrtuvwxzP".indexOf(c6) === -1) throw new Error("unrecognized character " + c6 + " in " + fmt);
out[out.length] = { t: "t", v: c6 };
++i7;
break;
}
}
var bt = 0, ss0 = 0, ssm;
for (i7 = out.length - 1, lst = "t"; i7 >= 0; --i7) {
switch (out[i7].t) {
case "h":
case "H":
out[i7].t = hr;
lst = "h";
if (bt < 1) bt = 1;
break;
case "s":
if (ssm = out[i7].v.match(/\.0+$/)) {
ss0 = Math.max(ss0, ssm[0].length - 1);
bt = 4;
}
if (bt < 3) bt = 3;
/* falls through */
case "d":
case "y":
case "e":
lst = out[i7].t;
break;
case "M":
lst = out[i7].t;
if (bt < 2) bt = 2;
break;
case "m":
if (lst === "s") {
out[i7].t = "M";
if (bt < 2) bt = 2;
}
break;
case "X":
break;
case "Z":
if (bt < 1 && out[i7].v.match(/[Hh]/)) bt = 1;
if (bt < 2 && out[i7].v.match(/[Mm]/)) bt = 2;
if (bt < 3 && out[i7].v.match(/[Ss]/)) bt = 3;
}
}
var _dt;
switch (bt) {
case 0:
break;
case 1:
case 2:
case 3:
if (dt.u >= 0.5) {
dt.u = 0;
++dt.S;
}
if (dt.S >= 60) {
dt.S = 0;
++dt.M;
}
if (dt.M >= 60) {
dt.M = 0;
++dt.H;
}
if (dt.H >= 24) {
dt.H = 0;
++dt.D;
_dt = SSF_parse_date_code(dt.D);
_dt.u = dt.u;
_dt.S = dt.S;
_dt.M = dt.M;
_dt.H = dt.H;
dt = _dt;
}
break;
case 4:
switch (ss0) {
case 1:
dt.u = Math.round(dt.u * 10) / 10;
break;
case 2:
dt.u = Math.round(dt.u * 100) / 100;
break;
case 3:
dt.u = Math.round(dt.u * 1e3) / 1e3;
break;
}
if (dt.u >= 1) {
dt.u = 0;
++dt.S;
}
if (dt.S >= 60) {
dt.S = 0;
++dt.M;
}
if (dt.M >= 60) {
dt.M = 0;
++dt.H;
}
if (dt.H >= 24) {
dt.H = 0;
++dt.D;
_dt = SSF_parse_date_code(dt.D);
_dt.u = dt.u;
_dt.S = dt.S;
_dt.M = dt.M;
_dt.H = dt.H;
dt = _dt;
}
break;
}
var nstr = "", jj;
for (i7 = 0; i7 < out.length; ++i7) {
switch (out[i7].t) {
case "t":
case "T":
case " ":
case "D":
break;
case "X":
out[i7].v = "";
out[i7].t = ";";
break;
case "d":
case "m":
case "y":
case "h":
case "H":
case "M":
case "s":
case "e":
case "b":
case "Z":
out[i7].v = SSF_write_date(out[i7].t.charCodeAt(0), out[i7].v, dt, ss0);
out[i7].t = "t";
break;
case "n":
case "?":
jj = i7 + 1;
while (out[jj] != null && ((c6 = out[jj].t) === "?" || c6 === "D" || (c6 === " " || c6 === "t") && out[jj + 1] != null && (out[jj + 1].t === "?" || out[jj + 1].t === "t" && out[jj + 1].v === "/") || out[i7].t === "(" && (c6 === " " || c6 === "n" || c6 === ")") || c6 === "t" && (out[jj].v === "/" || out[jj].v === " " && out[jj + 1] != null && out[jj + 1].t == "?"))) {
out[i7].v += out[jj].v;
out[jj] = { v: "", t: ";" };
++jj;
}
nstr += out[i7].v;
i7 = jj - 1;
break;
case "G":
out[i7].t = "t";
out[i7].v = SSF_general(v4, opts);
break;
}
}
var vv = "", myv, ostr;
if (nstr.length > 0) {
if (nstr.charCodeAt(0) == 40) {
myv = v4 < 0 && nstr.charCodeAt(0) === 45 ? -v4 : v4;
ostr = write_num("n", nstr, myv);
} else {
myv = v4 < 0 && flen > 1 ? -v4 : v4;
ostr = write_num("n", nstr, myv);
if (myv < 0 && out[0] && out[0].t == "t") {
ostr = ostr.substr(1);
out[0].v = "-" + out[0].v;
}
}
jj = ostr.length - 1;
var decpt = out.length;
for (i7 = 0; i7 < out.length; ++i7) if (out[i7] != null && out[i7].t != "t" && out[i7].v.indexOf(".") > -1) {
decpt = i7;
break;
}
var lasti = out.length;
if (decpt === out.length && ostr.indexOf("E") === -1) {
for (i7 = out.length - 1; i7 >= 0; --i7) {
if (out[i7] == null || "n?".indexOf(out[i7].t) === -1) continue;
if (jj >= out[i7].v.length - 1) {
jj -= out[i7].v.length;
out[i7].v = ostr.substr(jj + 1, out[i7].v.length);
} else if (jj < 0) out[i7].v = "";
else {
out[i7].v = ostr.substr(0, jj + 1);
jj = -1;
}
out[i7].t = "t";
lasti = i7;
}
if (jj >= 0 && lasti < out.length) out[lasti].v = ostr.substr(0, jj + 1) + out[lasti].v;
} else if (decpt !== out.length && ostr.indexOf("E") === -1) {
jj = ostr.indexOf(".") - 1;
for (i7 = decpt; i7 >= 0; --i7) {
if (out[i7] == null || "n?".indexOf(out[i7].t) === -1) continue;
j3 = out[i7].v.indexOf(".") > -1 && i7 === decpt ? out[i7].v.indexOf(".") - 1 : out[i7].v.length - 1;
vv = out[i7].v.substr(j3 + 1);
for (; j3 >= 0; --j3) {
if (jj >= 0 && (out[i7].v.charAt(j3) === "0" || out[i7].v.charAt(j3) === "#")) vv = ostr.charAt(jj--) + vv;
}
out[i7].v = vv;
out[i7].t = "t";
lasti = i7;
}
if (jj >= 0 && lasti < out.length) out[lasti].v = ostr.substr(0, jj + 1) + out[lasti].v;
jj = ostr.indexOf(".") + 1;
for (i7 = decpt; i7 < out.length; ++i7) {
if (out[i7] == null || "n?(".indexOf(out[i7].t) === -1 && i7 !== decpt) continue;
j3 = out[i7].v.indexOf(".") > -1 && i7 === decpt ? out[i7].v.indexOf(".") + 1 : 0;
vv = out[i7].v.substr(0, j3);
for (; j3 < out[i7].v.length; ++j3) {
if (jj < ostr.length) vv += ostr.charAt(jj++);
}
out[i7].v = vv;
out[i7].t = "t";
lasti = i7;
}
}
}
for (i7 = 0; i7 < out.length; ++i7) if (out[i7] != null && "n?".indexOf(out[i7].t) > -1) {
myv = flen > 1 && v4 < 0 && i7 > 0 && out[i7 - 1].v === "-" ? -v4 : v4;
out[i7].v = write_num(out[i7].t, out[i7].v, myv);
out[i7].t = "t";
}
var retval = "";
for (i7 = 0; i7 !== out.length; ++i7) if (out[i7] != null) retval += out[i7].v;
return retval;
}
function chkcond(v4, rr) {
if (rr == null) return false;
var thresh = parseFloat(rr[2]);
switch (rr[1]) {
case "=":
if (v4 == thresh) return true;
break;
case ">":
if (v4 > thresh) return true;
break;
case "<":
if (v4 < thresh) return true;
break;
case "<>":
if (v4 != thresh) return true;
break;
case ">=":
if (v4 >= thresh) return true;
break;
case "<=":
if (v4 <= thresh) return true;
break;
}
return false;
}
function choose_fmt(f4, v4) {
var fmt = SSF_split_fmt(f4);
var l5 = fmt.length, lat = fmt[l5 - 1].indexOf("@");
if (l5 < 4 && lat > -1) --l5;
if (fmt.length > 4) throw new Error("cannot find right format for |" + fmt.join("|") + "|");
if (typeof v4 !== "number") return [4, fmt.length === 4 || lat > -1 ? fmt[fmt.length - 1] : "@"];
if (typeof v4 === "number" && !isFinite(v4)) v4 = 0;
switch (fmt.length) {
case 1:
fmt = lat > -1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"];
break;
case 2:
fmt = lat > -1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"];
break;
case 3:
fmt = lat > -1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"];
break;
case 4:
break;
}
var ff = v4 > 0 ? fmt[0] : v4 < 0 ? fmt[1] : fmt[2];
if (fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l5, ff];
if (fmt[0].match(/\[[=<>]/) != null || fmt[1].match(/\[[=<>]/) != null) {
var m1 = fmt[0].match(cfregex2);
var m22 = fmt[1].match(cfregex2);
return chkcond(v4, m1) ? [l5, fmt[0]] : chkcond(v4, m22) ? [l5, fmt[1]] : [l5, fmt[m1 != null && m22 != null ? 2 : 1]];
}
return [l5, ff];
}
function SSF_format(fmt, v4, o9) {
if (o9 == null) o9 = {};
var sfmt = "";
switch (typeof fmt) {
case "string":
if (fmt == "m/d/yy" && o9.dateNF) sfmt = o9.dateNF;
else sfmt = fmt;
break;
case "number":
if (fmt == 14 && o9.dateNF) sfmt = o9.dateNF;
else sfmt = (o9.table != null ? o9.table : table_fmt)[fmt];
if (sfmt == null) sfmt = o9.table && o9.table[SSF_default_map[fmt]] || table_fmt[SSF_default_map[fmt]];
if (sfmt == null) sfmt = SSF_default_str[fmt] || "General";
break;
}
if (SSF_isgeneral(sfmt, 0)) return SSF_general(v4, o9);
if (v4 instanceof Date) v4 = datenum(v4, o9.date1904);
var f4 = choose_fmt(sfmt, v4);
if (SSF_isgeneral(f4[1])) return SSF_general(v4, o9);
if (v4 === true) v4 = "TRUE";
else if (v4 === false) v4 = "FALSE";
else if (v4 === "" || v4 == null) return "";
else if (isNaN(v4) && f4[1].indexOf("0") > -1) return "#NUM!";
else if (!isFinite(v4) && f4[1].indexOf("0") > -1) return "#DIV/0!";
return eval_fmt(f4[1], v4, o9, f4[0]);
}
function SSF_load(fmt, idx) {
if (typeof idx != "number") {
idx = +idx || -1;
for (var i7 = 0; i7 < 392; ++i7) {
if (table_fmt[i7] == void 0) {
if (idx < 0) idx = i7;
continue;
}
if (table_fmt[i7] == fmt) {
idx = i7;
break;
}
}
if (idx < 0) idx = 391;
}
table_fmt[idx] = fmt;
return idx;
}
function make_ssf() {
table_fmt = SSF_init_table();
}
function dateNF_regex(dateNF) {
var fmt = typeof dateNF == "number" ? table_fmt[dateNF] : dateNF;
fmt = fmt.replace(dateNFregex, "(\\d+)");
dateNFregex.lastIndex = 0;
return new RegExp("^" + fmt + "$");
}
function dateNF_fix(str2, dateNF, match2) {
var Y = -1, m4 = -1, d4 = -1, H2 = -1, M4 = -1, S5 = -1;
(dateNF.match(dateNFregex) || []).forEach(function(n7, i7) {
var v4 = parseInt(match2[i7 + 1], 10);
switch (n7.toLowerCase().charAt(0)) {
case "y":
Y = v4;
break;
case "d":
d4 = v4;
break;
case "h":
H2 = v4;
break;
case "s":
S5 = v4;
break;
case "m":
if (H2 >= 0) M4 = v4;
else m4 = v4;
break;
}
});
dateNFregex.lastIndex = 0;
if (S5 >= 0 && M4 == -1 && m4 >= 0) {
M4 = m4;
m4 = -1;
}
var datestr = ("" + (Y >= 0 ? Y : (/* @__PURE__ */ new Date()).getFullYear())).slice(-4) + "-" + ("00" + (m4 >= 1 ? m4 : 1)).slice(-2) + "-" + ("00" + (d4 >= 1 ? d4 : 1)).slice(-2);
if (datestr.length == 7) datestr = "0" + datestr;
if (datestr.length == 8) datestr = "20" + datestr;
var timestr = ("00" + (H2 >= 0 ? H2 : 0)).slice(-2) + ":" + ("00" + (M4 >= 0 ? M4 : 0)).slice(-2) + ":" + ("00" + (S5 >= 0 ? S5 : 0)).slice(-2);
if (H2 == -1 && M4 == -1 && S5 == -1) return datestr;
if (Y == -1 && m4 == -1 && d4 == -1) return timestr;
return datestr + "T" + timestr;
}
function SSF__load(fmt, idx) {
return SSF_load(bad_formats[fmt] || fmt, idx);
}
function read_binary(path6) {
if (typeof _fs !== "undefined") return _fs.readFileSync(path6);
if (typeof Deno !== "undefined") return Deno.readFileSync(path6);
if (typeof $ !== "undefined" && typeof File !== "undefined" && typeof Folder !== "undefined") try {
var infile = File(path6);
infile.open("r");
infile.encoding = "binary";
var data = infile.read();
infile.close();
return data;
} catch (e9) {
if (!e9.message || e9.message.indexOf("onstruct") == -1) throw e9;
}
throw new Error("Cannot access file " + path6);
}
function keys(o9) {
var ks = Object.keys(o9), o22 = [];
for (var i7 = 0; i7 < ks.length; ++i7) if (Object.prototype.hasOwnProperty.call(o9, ks[i7])) o22.push(ks[i7]);
return o22;
}
function evert(obj) {
var o9 = [], K2 = keys(obj);
for (var i7 = 0; i7 !== K2.length; ++i7) o9[obj[K2[i7]]] = K2[i7];
return o9;
}
function datenum(v4, date1904) {
var epoch = /* @__PURE__ */ v4.getTime();
var res = (epoch - dnthresh) / (24 * 60 * 60 * 1e3);
if (date1904) {
res -= 1462;
return res < -1402 ? res - 1 : res;
}
return res < 60 ? res - 1 : res;
}
function numdate(v4) {
if (v4 >= 60 && v4 < 61) return v4;
var out = /* @__PURE__ */ new Date();
out.setTime((v4 > 60 ? v4 : v4 + 1) * 24 * 60 * 60 * 1e3 + dnthresh);
return out;
}
function parse_isodur(s6) {
var sec = 0, mt = 0, time = false;
var m4 = s6.match(/P([0-9\.]+Y)?([0-9\.]+M)?([0-9\.]+D)?T([0-9\.]+H)?([0-9\.]+M)?([0-9\.]+S)?/);
if (!m4) throw new Error("|" + s6 + "| is not an ISO8601 Duration");
for (var i7 = 1; i7 != m4.length; ++i7) {
if (!m4[i7]) continue;
mt = 1;
if (i7 > 3) time = true;
switch (m4[i7].slice(m4[i7].length - 1)) {
case "Y":
throw new Error("Unsupported ISO Duration Field: " + m4[i7].slice(m4[i7].length - 1));
case "D":
mt *= 24;
/* falls through */
case "H":
mt *= 60;
/* falls through */
case "M":
if (!time) throw new Error("Unsupported ISO Duration Field: M");
else mt *= 60;
/* falls through */
case "S":
break;
}
sec += mt * parseInt(m4[i7], 10);
}
return sec;
}
function parseDate(str2, date1904) {
if (str2 instanceof Date) return str2;
var m4 = str2.match(pdre1);
if (m4) return new Date((date1904 ? dnthresh2 : dnthresh1) + ((parseInt(m4[1], 10) * 60 + parseInt(m4[2], 10)) * 60 + (m4[3] ? parseInt(m4[3].slice(1), 10) : 0)) * 1e3 + (m4[4] ? parseInt((m4[4] + "000").slice(1, 4), 10) : 0));
m4 = str2.match(pdre2);
if (m4) return new Date(Date.UTC(+m4[1], +m4[2] - 1, +m4[3], 0, 0, 0, 0));
m4 = str2.match(pdre3);
if (m4) return new Date(Date.UTC(+m4[1], +m4[2] - 1, +m4[3], +m4[4], +m4[5], m4[6] && parseInt(m4[6].slice(1), 10) || 0, m4[7] && parseInt((m4[7] + "0000").slice(1, 4), 10) || 0));
var d4 = new Date(str2);
return d4;
}
function cc2str(arr, debomit) {
if (has_buf && Buffer.isBuffer(arr)) {
if (debomit && buf_utf16le) {
if (arr[0] == 255 && arr[1] == 254) return utf8write(arr.slice(2).toString("utf16le"));
if (arr[1] == 254 && arr[2] == 255) return utf8write(utf16beread(arr.slice(2).toString("binary")));
}
return arr.toString("binary");
}
if (typeof TextDecoder !== "undefined") try {
if (debomit) {
if (arr[0] == 255 && arr[1] == 254) return utf8write(new TextDecoder("utf-16le").decode(arr.slice(2)));
if (arr[0] == 254 && arr[1] == 255) return utf8write(new TextDecoder("utf-16be").decode(arr.slice(2)));
}
var rev = {
"\u20AC": "\x80",
"\u201A": "\x82",
"\u0192": "\x83",
"\u201E": "\x84",
"\u2026": "\x85",
"\u2020": "\x86",
"\u2021": "\x87",
"\u02C6": "\x88",
"\u2030": "\x89",
"\u0160": "\x8A",
"\u2039": "\x8B",
"\u0152": "\x8C",
"\u017D": "\x8E",
"\u2018": "\x91",
"\u2019": "\x92",
"\u201C": "\x93",
"\u201D": "\x94",
"\u2022": "\x95",
"\u2013": "\x96",
"\u2014": "\x97",
"\u02DC": "\x98",
"\u2122": "\x99",
"\u0161": "\x9A",
"\u203A": "\x9B",
"\u0153": "\x9C",
"\u017E": "\x9E",
"\u0178": "\x9F"
};
if (Array.isArray(arr)) arr = new Uint8Array(arr);
return new TextDecoder("latin1").decode(arr).replace(/[€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ]/g, function(c6) {
return rev[c6] || c6;
});
} catch (e9) {
}
var o9 = [], i7 = 0;
try {
for (i7 = 0; i7 < arr.length - 65536; i7 += 65536) o9.push(String.fromCharCode.apply(0, arr.slice(i7, i7 + 65536)));
o9.push(String.fromCharCode.apply(0, arr.slice(i7)));
} catch (e9) {
try {
for (; i7 < arr.length - 16384; i7 += 16384) o9.push(String.fromCharCode.apply(0, arr.slice(i7, i7 + 16384)));
o9.push(String.fromCharCode.apply(0, arr.slice(i7)));
} catch (e10) {
for (; i7 != arr.length; ++i7) o9.push(String.fromCharCode(arr[i7]));
}
}
return o9.join("");
}
function dup(o9) {
if (typeof JSON != "undefined" && !Array.isArray(o9)) return JSON.parse(JSON.stringify(o9));
if (typeof o9 != "object" || o9 == null) return o9;
if (o9 instanceof Date) return new Date(o9.getTime());
var out = {};
for (var k2 in o9) if (Object.prototype.hasOwnProperty.call(o9, k2)) out[k2] = dup(o9[k2]);
return out;
}
function fill(c6, l5) {
var o9 = "";
while (o9.length < l5) o9 += c6;
return o9;
}
function fuzzynum(s6) {
var v4 = Number(s6);
if (!isNaN(v4)) return isFinite(v4) ? v4 : NaN;
if (!/\d/.test(s6)) return v4;
var wt = 1;
var ss = s6.replace(/([\d]),([\d])/g, "$1$2").replace(/[$]/g, "").replace(/[%]/g, function() {
wt *= 100;
return "";
});
if (!isNaN(v4 = Number(ss))) return v4 / wt;
ss = ss.replace(/[(]([^()]*)[)]/, function($$, $1) {
wt = -wt;
return $1;
});
if (!isNaN(v4 = Number(ss))) return v4 / wt;
return v4;
}
function fuzzytime1(M4) {
if (!M4[2]) return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), 0, 0, 0));
if (M4[3]) {
if (M4[4]) return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), +M4[2], +M4[4], parseFloat(M4[3]) * 1e3));
else return new Date(Date.UTC(1899, 11, 31, M4[7] == "p" ? 12 : 0, +M4[1], +M4[2], parseFloat(M4[3]) * 1e3));
} else if (M4[5]) return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), +M4[2], +M4[5], M4[6] ? parseFloat(M4[6]) * 1e3 : 0));
else return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), +M4[2], 0, 0));
}
function fuzzytime2(M4) {
if (!M4[2]) return new Date(Date.UTC(1899, 11, 31, +M4[1], 0, 0, 0));
if (M4[3]) {
if (M4[4]) return new Date(Date.UTC(1899, 11, 31, +M4[1], +M4[2], +M4[4], parseFloat(M4[3]) * 1e3));
else return new Date(Date.UTC(1899, 11, 31, 0, +M4[1], +M4[2], parseFloat(M4[3]) * 1e3));
} else if (M4[5]) return new Date(Date.UTC(1899, 11, 31, +M4[1], +M4[2], +M4[5], M4[6] ? parseFloat(M4[6]) * 1e3 : 0));
else return new Date(Date.UTC(1899, 11, 31, +M4[1], +M4[2], 0, 0));
}
function fuzzydate(s6) {
if (FDISO.test(s6)) return s6.indexOf("Z") == -1 ? local_to_utc(new Date(s6)) : new Date(s6);
var lower = s6.toLowerCase();
var lnos = lower.replace(/\s+/g, " ").trim();
var M4 = lnos.match(FDRE1);
if (M4) return fuzzytime1(M4);
M4 = lnos.match(FDRE2);
if (M4) return fuzzytime2(M4);
M4 = lnos.match(pdre3);
if (M4) return new Date(Date.UTC(+M4[1], +M4[2] - 1, +M4[3], +M4[4], +M4[5], M4[6] && parseInt(M4[6].slice(1), 10) || 0, M4[7] && parseInt((M4[7] + "0000").slice(1, 4), 10) || 0));
var o9 = new Date(utc_append_works && s6.indexOf("UTC") == -1 ? s6 + " UTC" : s6), n7 = /* @__PURE__ */ new Date(NaN);
var y4 = o9.getYear(), m4 = o9.getMonth(), d4 = o9.getDate();
if (isNaN(d4)) return n7;
if (lower.match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/)) {
lower = lower.replace(/[^a-z]/g, "").replace(/([^a-z]|^)[ap]m?([^a-z]|$)/, "");
if (lower.length > 3 && lower_months.indexOf(lower) == -1) return n7;
} else if (lower.replace(/[ap]m?/, "").match(/[a-z]/)) return n7;
if (y4 < 0 || y4 > 8099 || s6.match(/[^-0-9:,\/\\\ ]/)) return n7;
return o9;
}
function utc_to_local(utc) {
return new Date(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate(), utc.getUTCHours(), utc.getUTCMinutes(), utc.getUTCSeconds(), utc.getUTCMilliseconds());
}
function local_to_utc(local) {
return new Date(Date.UTC(local.getFullYear(), local.getMonth(), local.getDate(), local.getHours(), local.getMinutes(), local.getSeconds(), local.getMilliseconds()));
}
function remove_doctype(str2) {
var preamble = str2.slice(0, 1024);
var si = preamble.indexOf(" -1) {
var ei = str2.indexOf(e9, si + s6.length);
if (ei == -1) break;
out.push(str2.slice(si, ei + e9.length));
si = str2.indexOf(s6, ei + e9.length);
}
return out.length > 0 ? out : null;
}
function str_remove_ng(str2, s6, e9) {
var out = [], last = 0;
var si = str2.indexOf(s6);
if (si == -1) return str2;
while (si > -1) {
out.push(str2.slice(last, si));
var ei = str2.indexOf(e9, si + s6.length);
if (ei == -1) break;
if ((si = str2.indexOf(s6, last = ei + e9.length)) == -1) out.push(str2.slice(last));
}
return out.join("");
}
function str_match_xml(str2, tag) {
var si = str2.indexOf("<" + tag), w3 = tag.length + 1, L3 = str2.length;
while (si >= 0 && si <= L3 - w3 && !xml_boundary[str2.charAt(si + w3)]) si = str2.indexOf("<" + tag, si + 1);
if (si === -1) return null;
var sf = str2.indexOf(">", si + tag.length);
if (sf === -1) return null;
var et = "" + tag + ">";
var ei = str2.indexOf(et, sf);
if (ei == -1) return null;
return [str2.slice(si, ei + et.length), str2.slice(sf + 1, ei)];
}
function getdatastr(data) {
if (!data) return null;
if (data.content && data.type) return cc2str(data.content, true);
if (data.data) return debom(data.data);
if (data.asNodeBuffer && has_buf) return debom(data.asNodeBuffer().toString("binary"));
if (data.asBinary) return debom(data.asBinary());
if (data._data && data._data.getContent) return debom(cc2str(Array.prototype.slice.call(data._data.getContent(), 0)));
return null;
}
function getdatabin(data) {
if (!data) return null;
if (data.data) return char_codes(data.data);
if (data.asNodeBuffer && has_buf) return data.asNodeBuffer();
if (data._data && data._data.getContent) {
var o9 = data._data.getContent();
if (typeof o9 == "string") return char_codes(o9);
return Array.prototype.slice.call(o9);
}
if (data.content && data.type) return data.content;
return null;
}
function getdata(data) {
return data && data.name.slice(-4) === ".bin" ? getdatabin(data) : getdatastr(data);
}
function safegetzipfile(zip, file) {
var k2 = zip.FullPaths || keys(zip.files);
var f4 = file.toLowerCase().replace(/[\/]/g, "\\"), g3 = f4.replace(/\\/g, "/");
for (var i7 = 0; i7 < k2.length; ++i7) {
var n7 = k2[i7].replace(/^Root Entry[\/]/, "").toLowerCase();
if (f4 == n7 || g3 == n7) return zip.files ? zip.files[k2[i7]] : zip.FileIndex[i7];
}
return null;
}
function getzipfile(zip, file) {
var o9 = safegetzipfile(zip, file);
if (o9 == null) throw new Error("Cannot find file " + file + " in zip");
return o9;
}
function getzipdata(zip, file, safe) {
if (!safe) return getdata(getzipfile(zip, file));
if (!file) return null;
try {
return getzipdata(zip, file);
} catch (e9) {
return null;
}
}
function getzipstr(zip, file, safe) {
if (!safe) return getdatastr(getzipfile(zip, file));
if (!file) return null;
try {
return getzipstr(zip, file);
} catch (e9) {
return null;
}
}
function getzipbin(zip, file, safe) {
if (!safe) return getdatabin(getzipfile(zip, file));
if (!file) return null;
try {
return getzipbin(zip, file);
} catch (e9) {
return null;
}
}
function zipentries(zip) {
var k2 = zip.FullPaths || keys(zip.files), o9 = [];
for (var i7 = 0; i7 < k2.length; ++i7) if (k2[i7].slice(-1) != "/") o9.push(k2[i7].replace(/^Root Entry[\/]/, ""));
return o9.sort();
}
function zip_add_file(zip, path6, content) {
if (zip.FullPaths) {
if (Array.isArray(content) && typeof content[0] == "string") {
content = content.join("");
}
if (typeof content == "string") {
var res;
if (has_buf) res = Buffer_from(content);
else res = utf8decode(content);
return CFB.utils.cfb_add(zip, path6, res);
}
CFB.utils.cfb_add(zip, path6, content);
} else zip.file(path6, content);
}
function zip_read(d4, o9) {
switch (o9.type) {
case "base64":
return CFB.read(d4, { type: "base64" });
case "binary":
return CFB.read(d4, { type: "binary" });
case "buffer":
case "array":
return CFB.read(d4, { type: "buffer" });
}
throw new Error("Unrecognized type " + o9.type);
}
function resolve_path(path6, base) {
if (path6.charAt(0) == "/") return path6.slice(1);
var result = base.split("/");
if (base.slice(-1) != "/") result.pop();
var target = path6.split("/");
while (target.length !== 0) {
var step = target.shift();
if (step === "..") result.pop();
else if (step !== ".") result.push(step);
}
return result.join("/");
}
function parsexmltag(tag, skip_root, skip_LC) {
var z3 = {};
var eq2 = 0, c6 = 0;
for (; eq2 !== tag.length; ++eq2) if ((c6 = tag.charCodeAt(eq2)) === 32 || c6 === 10 || c6 === 13) break;
if (!skip_root) z3[0] = tag.slice(0, eq2);
if (eq2 === tag.length) return z3;
var m4 = tag.match(attregexg), j3 = 0, v4 = "", i7 = 0, q2 = "", cc = "", quot = 1;
if (m4) for (i7 = 0; i7 != m4.length; ++i7) {
cc = m4[i7].slice(1);
for (c6 = 0; c6 != cc.length; ++c6) if (cc.charCodeAt(c6) === 61) break;
q2 = cc.slice(0, c6).trim();
while (cc.charCodeAt(c6 + 1) == 32) ++c6;
quot = (eq2 = cc.charCodeAt(c6 + 1)) == 34 || eq2 == 39 ? 1 : 0;
v4 = cc.slice(c6 + 1 + quot, cc.length - quot);
for (j3 = 0; j3 != q2.length; ++j3) if (q2.charCodeAt(j3) === 58) break;
if (j3 === q2.length) {
if (q2.indexOf("_") > 0) q2 = q2.slice(0, q2.indexOf("_"));
z3[q2] = v4;
if (!skip_LC) z3[q2.toLowerCase()] = v4;
} else {
var k2 = (j3 === 5 && q2.slice(0, 5) === "xmlns" ? "xmlns" : "") + q2.slice(j3 + 1);
if (z3[k2] && q2.slice(j3 - 3, j3) == "ext") continue;
z3[k2] = v4;
if (!skip_LC) z3[k2.toLowerCase()] = v4;
}
}
return z3;
}
function parsexmltagraw(tag, skip_root, skip_LC) {
var z3 = {};
var eq2 = 0, c6 = 0;
for (; eq2 !== tag.length; ++eq2) if ((c6 = tag.charCodeAt(eq2)) === 32 || c6 === 10 || c6 === 13) break;
if (!skip_root) z3[0] = tag.slice(0, eq2);
if (eq2 === tag.length) return z3;
var m4 = tag.match(attregexg), j3 = 0, v4 = "", i7 = 0, q2 = "", cc = "", quot = 1;
if (m4) for (i7 = 0; i7 != m4.length; ++i7) {
cc = m4[i7].slice(1);
for (c6 = 0; c6 != cc.length; ++c6) if (cc.charCodeAt(c6) === 61) break;
q2 = cc.slice(0, c6).trim();
while (cc.charCodeAt(c6 + 1) == 32) ++c6;
quot = (eq2 = cc.charCodeAt(c6 + 1)) == 34 || eq2 == 39 ? 1 : 0;
v4 = cc.slice(c6 + 1 + quot, cc.length - quot);
if (q2.indexOf("_") > 0) q2 = q2.slice(0, q2.indexOf("_"));
z3[q2] = v4;
if (!skip_LC) z3[q2.toLowerCase()] = v4;
}
return z3;
}
function strip_ns(x2) {
return x2.replace(nsregex2, "<$1");
}
function escapehtml(text3) {
var s6 = text3 + "";
return s6.replace(decregex, function(y4) {
return rencoding[y4];
}).replace(/\n/g, "
").replace(htmlcharegex, function(s7) {
return "" + ("000" + s7.charCodeAt(0).toString(16)).slice(-4) + ";";
});
}
function parsexmlbool(value) {
switch (value) {
case 1:
case true:
case "1":
case "true":
return true;
case 0:
case false:
case "0":
case "false":
return false;
}
return false;
}
function utf8reada(orig) {
var out = "", i7 = 0, c6 = 0, d4 = 0, e9 = 0, f4 = 0, w3 = 0;
while (i7 < orig.length) {
c6 = orig.charCodeAt(i7++);
if (c6 < 128) {
out += String.fromCharCode(c6);
continue;
}
d4 = orig.charCodeAt(i7++);
if (c6 > 191 && c6 < 224) {
f4 = (c6 & 31) << 6;
f4 |= d4 & 63;
out += String.fromCharCode(f4);
continue;
}
e9 = orig.charCodeAt(i7++);
if (c6 < 240) {
out += String.fromCharCode((c6 & 15) << 12 | (d4 & 63) << 6 | e9 & 63);
continue;
}
f4 = orig.charCodeAt(i7++);
w3 = ((c6 & 7) << 18 | (d4 & 63) << 12 | (e9 & 63) << 6 | f4 & 63) - 65536;
out += String.fromCharCode(55296 + (w3 >>> 10 & 1023));
out += String.fromCharCode(56320 + (w3 & 1023));
}
return out;
}
function utf8readb(data) {
var out = new_raw_buf(2 * data.length), w3, i7, j3 = 1, k2 = 0, ww = 0, c6;
for (i7 = 0; i7 < data.length; i7 += j3) {
j3 = 1;
if ((c6 = data.charCodeAt(i7)) < 128) w3 = c6;
else if (c6 < 224) {
w3 = (c6 & 31) * 64 + (data.charCodeAt(i7 + 1) & 63);
j3 = 2;
} else if (c6 < 240) {
w3 = (c6 & 15) * 4096 + (data.charCodeAt(i7 + 1) & 63) * 64 + (data.charCodeAt(i7 + 2) & 63);
j3 = 3;
} else {
j3 = 4;
w3 = (c6 & 7) * 262144 + (data.charCodeAt(i7 + 1) & 63) * 4096 + (data.charCodeAt(i7 + 2) & 63) * 64 + (data.charCodeAt(i7 + 3) & 63);
w3 -= 65536;
ww = 55296 + (w3 >>> 10 & 1023);
w3 = 56320 + (w3 & 1023);
}
if (ww !== 0) {
out[k2++] = ww & 255;
out[k2++] = ww >>> 8;
ww = 0;
}
out[k2++] = w3 % 256;
out[k2++] = w3 >>> 8;
}
return out.slice(0, k2).toString("ucs2");
}
function utf8readc(data) {
return Buffer_from(data, "binary").toString("utf8");
}
function parseVector(data, opts) {
var h7 = parsexmltag(data);
var matches = str_match_xml_ns_g(data, h7.baseType) || [];
var res = [];
if (matches.length != h7.size) {
if (opts.WTF) throw new Error("unexpected vector length " + matches.length + " != " + h7.size);
return res;
}
matches.forEach(function(x2) {
var v4 = x2.replace(vtvregex, "").match(vtmregex);
if (v4) res.push({ v: utf8read(v4[2]), t: v4[1] });
});
return res;
}
function wxt_helper(h7) {
return keys(h7).map(function(k2) {
return " " + k2 + '="' + h7[k2] + '"';
}).join("");
}
function writextag(f4, g3, h7) {
return "<" + f4 + (h7 != null ? wxt_helper(h7) : "") + (g3 != null ? (g3.match(wtregex) ? ' xml:space="preserve"' : "") + ">" + g3 + "" + f4 : "/") + ">";
}
function xlml_normalize(d4) {
if (has_buf && /*::typeof Buffer !== "undefined" && d != null && d instanceof Buffer &&*/
Buffer.isBuffer(d4)) return d4.toString("utf8");
if (typeof d4 === "string") return d4;
if (typeof Uint8Array !== "undefined" && d4 instanceof Uint8Array) return utf8read(a2s(ab2a(d4)));
throw new Error("Bad input format: expected Buffer or string");
}
function read_double_le(b4, idx) {
var s6 = 1 - 2 * (b4[idx + 7] >>> 7);
var e9 = ((b4[idx + 7] & 127) << 4) + (b4[idx + 6] >>> 4 & 15);
var m4 = b4[idx + 6] & 15;
for (var i7 = 5; i7 >= 0; --i7) m4 = m4 * 256 + b4[idx + i7];
if (e9 == 2047) return m4 == 0 ? s6 * Infinity : NaN;
if (e9 == 0) e9 = -1022;
else {
e9 -= 1023;
m4 += Math.pow(2, 52);
}
return s6 * Math.pow(2, e9 - 52) * m4;
}
function write_double_le(b4, v4, idx) {
var bs = (v4 < 0 || 1 / v4 == -Infinity ? 1 : 0) << 7, e9 = 0, m4 = 0;
var av = bs ? -v4 : v4;
if (!isFinite(av)) {
e9 = 2047;
m4 = isNaN(v4) ? 26985 : 0;
} else if (av == 0) e9 = m4 = 0;
else {
e9 = Math.floor(Math.log(av) / Math.LN2);
m4 = av * Math.pow(2, 52 - e9);
if (e9 <= -1023 && (!isFinite(m4) || m4 < Math.pow(2, 52))) {
e9 = -1022;
} else {
m4 -= Math.pow(2, 52);
e9 += 1023;
}
}
for (var i7 = 0; i7 <= 5; ++i7, m4 /= 256) b4[idx + i7] = m4 & 255;
b4[idx + 6] = (e9 & 15) << 4 | m4 & 15;
b4[idx + 7] = e9 >> 4 | bs;
}
function cpdoit() {
__utf16le = function(b4, s6, e9) {
return $cptable.utils.decode(1200, b4.slice(s6, e9)).replace(chr0, "");
};
__utf8 = function(b4, s6, e9) {
return $cptable.utils.decode(65001, b4.slice(s6, e9));
};
__lpstr = function(b4, i7) {
var len = __readUInt32LE(b4, i7);
return len > 0 ? $cptable.utils.decode(current_ansi, b4.slice(i7 + 4, i7 + 4 + len - 1)) : "";
};
__cpstr = function(b4, i7) {
var len = __readUInt32LE(b4, i7);
return len > 0 ? $cptable.utils.decode(current_codepage, b4.slice(i7 + 4, i7 + 4 + len - 1)) : "";
};
__lpwstr = function(b4, i7) {
var len = 2 * __readUInt32LE(b4, i7);
return len > 0 ? $cptable.utils.decode(1200, b4.slice(i7 + 4, i7 + 4 + len - 1)) : "";
};
__lpp4 = function(b4, i7) {
var len = __readUInt32LE(b4, i7);
return len > 0 ? $cptable.utils.decode(1200, b4.slice(i7 + 4, i7 + 4 + len)) : "";
};
__8lpp4 = function(b4, i7) {
var len = __readUInt32LE(b4, i7);
return len > 0 ? $cptable.utils.decode(65001, b4.slice(i7 + 4, i7 + 4 + len)) : "";
};
}
function ReadShift(size, t6) {
var o9 = "", oI, oR, oo = [], w3, vv, i7, loc;
switch (t6) {
case "dbcs":
loc = this.l;
if (has_buf && Buffer.isBuffer(this) && buf_utf16le) o9 = this.slice(this.l, this.l + 2 * size).toString("utf16le");
else for (i7 = 0; i7 < size; ++i7) {
o9 += String.fromCharCode(__readUInt16LE(this, loc));
loc += 2;
}
size *= 2;
break;
case "utf8":
o9 = __utf8(this, this.l, this.l + size);
break;
case "utf16le":
size *= 2;
o9 = __utf16le(this, this.l, this.l + size);
break;
case "wstr":
if (typeof $cptable !== "undefined") o9 = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l + 2 * size));
else return ReadShift.call(this, size, "dbcs");
size = 2 * size;
break;
/* [MS-OLEDS] 2.1.4 LengthPrefixedAnsiString */
case "lpstr-ansi":
o9 = __lpstr(this, this.l);
size = 4 + __readUInt32LE(this, this.l);
break;
case "lpstr-cp":
o9 = __cpstr(this, this.l);
size = 4 + __readUInt32LE(this, this.l);
break;
/* [MS-OLEDS] 2.1.5 LengthPrefixedUnicodeString */
case "lpwstr":
o9 = __lpwstr(this, this.l);
size = 4 + 2 * __readUInt32LE(this, this.l);
break;
/* [MS-OFFCRYPTO] 2.1.2 Length-Prefixed Padded Unicode String (UNICODE-LP-P4) */
case "lpp4":
size = 4 + __readUInt32LE(this, this.l);
o9 = __lpp4(this, this.l);
if (size & 2) size += 2;
break;
/* [MS-OFFCRYPTO] 2.1.3 Length-Prefixed UTF-8 String (UTF-8-LP-P4) */
case "8lpp4":
size = 4 + __readUInt32LE(this, this.l);
o9 = __8lpp4(this, this.l);
if (size & 3) size += 4 - (size & 3);
break;
case "cstr":
size = 0;
o9 = "";
while ((w3 = __readUInt8(this, this.l + size++)) !== 0) oo.push(_getchar(w3));
o9 = oo.join("");
break;
case "_wstr":
size = 0;
o9 = "";
while ((w3 = __readUInt16LE(this, this.l + size)) !== 0) {
oo.push(_getchar(w3));
size += 2;
}
size += 2;
o9 = oo.join("");
break;
/* sbcs and dbcs support continue records in the SST way TODO codepages */
case "dbcs-cont":
o9 = "";
loc = this.l;
for (i7 = 0; i7 < size; ++i7) {
if (this.lens && this.lens.indexOf(loc) !== -1) {
w3 = __readUInt8(this, loc);
this.l = loc + 1;
vv = ReadShift.call(this, size - i7, w3 ? "dbcs-cont" : "sbcs-cont");
return oo.join("") + vv;
}
oo.push(_getchar(__readUInt16LE(this, loc)));
loc += 2;
}
o9 = oo.join("");
size *= 2;
break;
case "cpstr":
if (typeof $cptable !== "undefined") {
o9 = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l + size));
break;
}
/* falls through */
case "sbcs-cont":
o9 = "";
loc = this.l;
for (i7 = 0; i7 != size; ++i7) {
if (this.lens && this.lens.indexOf(loc) !== -1) {
w3 = __readUInt8(this, loc);
this.l = loc + 1;
vv = ReadShift.call(this, size - i7, w3 ? "dbcs-cont" : "sbcs-cont");
return oo.join("") + vv;
}
oo.push(_getchar(__readUInt8(this, loc)));
loc += 1;
}
o9 = oo.join("");
break;
default:
switch (size) {
case 1:
oI = __readUInt8(this, this.l);
this.l++;
return oI;
case 2:
oI = (t6 === "i" ? __readInt16LE : __readUInt16LE)(this, this.l);
this.l += 2;
return oI;
case 4:
case -4:
if (t6 === "i" || (this[this.l + 3] & 128) === 0) {
oI = (size > 0 ? __readInt32LE : __readInt32BE)(this, this.l);
this.l += 4;
return oI;
} else {
oR = __readUInt32LE(this, this.l);
this.l += 4;
}
return oR;
case 8:
case -8:
if (t6 === "f") {
if (size == 8) oR = __double(this, this.l);
else oR = __double([this[this.l + 7], this[this.l + 6], this[this.l + 5], this[this.l + 4], this[this.l + 3], this[this.l + 2], this[this.l + 1], this[this.l + 0]], 0);
this.l += 8;
return oR;
} else size = 8;
/* falls through */
case 16:
o9 = __hexlify(this, this.l, size);
break;
}
}
this.l += size;
return o9;
}
function WriteShift(t6, val2, f4) {
var size = 0, i7 = 0;
if (f4 === "dbcs") {
for (i7 = 0; i7 != val2.length; ++i7) __writeUInt16LE(this, val2.charCodeAt(i7), this.l + 2 * i7);
size = 2 * val2.length;
} else if (f4 === "sbcs" || f4 == "cpstr") {
if (typeof $cptable !== "undefined" && current_ansi == 874) {
for (i7 = 0; i7 != val2.length; ++i7) {
var cpp = $cptable.utils.encode(current_ansi, val2.charAt(i7));
this[this.l + i7] = cpp[0];
}
size = val2.length;
} else if (typeof $cptable !== "undefined" && f4 == "cpstr") {
cpp = $cptable.utils.encode(current_codepage, val2);
if (cpp.length == val2.length) {
for (i7 = 0; i7 < val2.length; ++i7) if (cpp[i7] == 0 && val2.charCodeAt(i7) != 0) cpp[i7] = 95;
}
if (cpp.length == 2 * val2.length) {
for (i7 = 0; i7 < val2.length; ++i7) if (cpp[2 * i7] == 0 && cpp[2 * i7 + 1] == 0 && val2.charCodeAt(i7) != 0) cpp[2 * i7] = 95;
}
for (i7 = 0; i7 < cpp.length; ++i7) this[this.l + i7] = cpp[i7];
size = cpp.length;
} else {
val2 = val2.replace(/[^\x00-\x7F]/g, "_");
for (i7 = 0; i7 != val2.length; ++i7) this[this.l + i7] = val2.charCodeAt(i7) & 255;
size = val2.length;
}
} else if (f4 === "hex") {
for (; i7 < t6; ++i7) {
this[this.l++] = parseInt(val2.slice(2 * i7, 2 * i7 + 2), 16) || 0;
}
return this;
} else if (f4 === "utf16le") {
var end = Math.min(this.l + t6, this.length);
for (i7 = 0; i7 < Math.min(val2.length, t6); ++i7) {
var cc = val2.charCodeAt(i7);
this[this.l++] = cc & 255;
this[this.l++] = cc >> 8;
}
while (this.l < end) this[this.l++] = 0;
return this;
} else switch (t6) {
case 1:
size = 1;
this[this.l] = val2 & 255;
break;
case 2:
size = 2;
this[this.l] = val2 & 255;
val2 >>>= 8;
this[this.l + 1] = val2 & 255;
break;
case 3:
size = 3;
this[this.l] = val2 & 255;
val2 >>>= 8;
this[this.l + 1] = val2 & 255;
val2 >>>= 8;
this[this.l + 2] = val2 & 255;
break;
case 4:
size = 4;
__writeUInt32LE(this, val2, this.l);
break;
case 8:
size = 8;
if (f4 === "f") {
write_double_le(this, val2, this.l);
break;
}
/* falls through */
case 16:
break;
case -4:
size = 4;
__writeInt32LE(this, val2, this.l);
break;
}
this.l += size;
return this;
}
function CheckField(hexstr, fld) {
var m4 = __hexlify(this, this.l, hexstr.length >> 1);
if (m4 !== hexstr) throw new Error(fld + "Expected " + hexstr + " saw " + m4);
this.l += hexstr.length >> 1;
}
function prep_blob(blob, pos) {
blob.l = pos;
blob.read_shift = /*::(*/
ReadShift;
blob.chk = CheckField;
blob.write_shift = WriteShift;
}
function parsenoop(blob, length) {
blob.l += length;
}
function new_buf(sz) {
var o9 = new_raw_buf(sz);
prep_blob(o9, 0);
return o9;
}
function recordhopper(data, cb, opts) {
if (!data) return;
var tmpbyte, cntbyte, length;
prep_blob(data, data.l || 0);
var L3 = data.length, RT = 0, tgt = 0;
while (data.l < L3) {
RT = data.read_shift(1);
if (RT & 128) RT = (RT & 127) + ((data.read_shift(1) & 127) << 7);
var R3 = XLSBRecordEnum[RT] || XLSBRecordEnum[65535];
tmpbyte = data.read_shift(1);
length = tmpbyte & 127;
for (cntbyte = 1; cntbyte < 4 && tmpbyte & 128; ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 127) << 7 * cntbyte;
tgt = data.l + length;
var d4 = R3.f && R3.f(data, length, opts);
data.l = tgt;
if (cb(d4, R3, RT)) return;
}
}
function buf_array() {
var bufs = [], blksz = has_buf ? 16384 : 2048;
var has_buf_copy = has_buf && typeof new_buf(blksz).copy == "function";
var newblk = function ba_newblk(sz) {
var o9 = new_buf(sz);
prep_blob(o9, 0);
return o9;
};
var curbuf = newblk(blksz);
var endbuf = function ba_endbuf() {
if (!curbuf) return;
if (curbuf.l) {
if (curbuf.length > curbuf.l) {
curbuf = curbuf.slice(0, curbuf.l);
curbuf.l = curbuf.length;
}
if (curbuf.length > 0) bufs.push(curbuf);
}
curbuf = null;
};
var next = function ba_next(sz) {
if (curbuf && sz < curbuf.length - curbuf.l) return curbuf;
endbuf();
return curbuf = newblk(Math.max(sz + 1, blksz));
};
var end = function ba_end() {
endbuf();
return bconcat(bufs);
};
var end2 = function() {
endbuf();
return bufs;
};
var push = function ba_push(buf) {
endbuf();
curbuf = buf;
if (curbuf.l == null) curbuf.l = curbuf.length;
next(blksz);
};
return { next, push, end, _bufs: bufs, end2 };
}
function shift_cell_xls(cell, tgt, opts) {
var out = dup(cell);
if (tgt.s) {
if (out.cRel) out.c += tgt.s.c;
if (out.rRel) out.r += tgt.s.r;
} else {
if (out.cRel) out.c += tgt.c;
if (out.rRel) out.r += tgt.r;
}
if (!opts || opts.biff < 12) {
while (out.c >= 256) out.c -= 256;
while (out.r >= 65536) out.r -= 65536;
}
return out;
}
function shift_range_xls(cell, range2, opts) {
var out = dup(cell);
out.s = shift_cell_xls(out.s, range2.s, opts);
out.e = shift_cell_xls(out.e, range2.s, opts);
return out;
}
function encode_cell_xls(c6, biff) {
if (c6.cRel && c6.c < 0) {
c6 = dup(c6);
while (c6.c < 0) c6.c += biff > 8 ? 16384 : 256;
}
if (c6.rRel && c6.r < 0) {
c6 = dup(c6);
while (c6.r < 0) c6.r += biff > 8 ? 1048576 : biff > 5 ? 65536 : 16384;
}
var s6 = encode_cell(c6);
if (!c6.cRel && c6.cRel != null) s6 = fix_col(s6);
if (!c6.rRel && c6.rRel != null) s6 = fix_row(s6);
return s6;
}
function encode_range_xls(r8, opts) {
if (r8.s.r == 0 && !r8.s.rRel) {
if (r8.e.r == (opts.biff >= 12 ? 1048575 : opts.biff >= 8 ? 65536 : 16384) && !r8.e.rRel) {
return (r8.s.cRel ? "" : "$") + encode_col(r8.s.c) + ":" + (r8.e.cRel ? "" : "$") + encode_col(r8.e.c);
}
}
if (r8.s.c == 0 && !r8.s.cRel) {
if (r8.e.c == (opts.biff >= 12 ? 16383 : 255) && !r8.e.cRel) {
return (r8.s.rRel ? "" : "$") + encode_row(r8.s.r) + ":" + (r8.e.rRel ? "" : "$") + encode_row(r8.e.r);
}
}
return encode_cell_xls(r8.s, opts.biff) + ":" + encode_cell_xls(r8.e, opts.biff);
}
function decode_row(rowstr) {
return parseInt(unfix_row(rowstr), 10) - 1;
}
function encode_row(row) {
return "" + (row + 1);
}
function fix_row(cstr) {
return cstr.replace(/([A-Z]|^)(\d+)$/, "$1$$$2");
}
function unfix_row(cstr) {
return cstr.replace(/\$(\d+)$/, "$1");
}
function decode_col(colstr) {
var c6 = unfix_col(colstr), d4 = 0, i7 = 0;
for (; i7 !== c6.length; ++i7) d4 = 26 * d4 + c6.charCodeAt(i7) - 64;
return d4 - 1;
}
function encode_col(col) {
if (col < 0) throw new Error("invalid column " + col);
var s6 = "";
for (++col; col; col = Math.floor((col - 1) / 26)) s6 = String.fromCharCode((col - 1) % 26 + 65) + s6;
return s6;
}
function fix_col(cstr) {
return cstr.replace(/^([A-Z])/, "$$$1");
}
function unfix_col(cstr) {
return cstr.replace(/^\$([A-Z])/, "$1");
}
function split_cell(cstr) {
return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/, "$1,$2").split(",");
}
function decode_cell(cstr) {
var R3 = 0, C3 = 0;
for (var i7 = 0; i7 < cstr.length; ++i7) {
var cc = cstr.charCodeAt(i7);
if (cc >= 48 && cc <= 57) R3 = 10 * R3 + (cc - 48);
else if (cc >= 65 && cc <= 90) C3 = 26 * C3 + (cc - 64);
}
return { c: C3 - 1, r: R3 - 1 };
}
function encode_cell(cell) {
var col = cell.c + 1;
var s6 = "";
for (; col; col = (col - 1) / 26 | 0) s6 = String.fromCharCode((col - 1) % 26 + 65) + s6;
return s6 + (cell.r + 1);
}
function decode_range(range2) {
var idx = range2.indexOf(":");
if (idx == -1) return { s: decode_cell(range2), e: decode_cell(range2) };
return { s: decode_cell(range2.slice(0, idx)), e: decode_cell(range2.slice(idx + 1)) };
}
function encode_range(cs, ce2) {
if (typeof ce2 === "undefined" || typeof ce2 === "number") {
return encode_range(cs.s, cs.e);
}
if (typeof cs !== "string") cs = encode_cell(cs);
if (typeof ce2 !== "string") ce2 = encode_cell(ce2);
return cs == ce2 ? cs : cs + ":" + ce2;
}
function formula_quote_sheet_name(sname, opts) {
if (!sname && !(opts && opts.biff <= 5 && opts.biff >= 2)) throw new Error("empty sheet name");
if (/[^\w\u4E00-\u9FFF\u3040-\u30FF]/.test(sname)) return "'" + sname.replace(/'/g, "''") + "'";
return sname;
}
function safe_decode_range(range2) {
var o9 = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } };
var idx = 0, i7 = 0, cc = 0;
var len = range2.length;
for (idx = 0; i7 < len; ++i7) {
if ((cc = range2.charCodeAt(i7) - 64) < 1 || cc > 26) break;
idx = 26 * idx + cc;
}
o9.s.c = --idx;
for (idx = 0; i7 < len; ++i7) {
if ((cc = range2.charCodeAt(i7) - 48) < 0 || cc > 9) break;
idx = 10 * idx + cc;
}
o9.s.r = --idx;
if (i7 === len || cc != 10) {
o9.e.c = o9.s.c;
o9.e.r = o9.s.r;
return o9;
}
++i7;
for (idx = 0; i7 != len; ++i7) {
if ((cc = range2.charCodeAt(i7) - 64) < 1 || cc > 26) break;
idx = 26 * idx + cc;
}
o9.e.c = --idx;
for (idx = 0; i7 != len; ++i7) {
if ((cc = range2.charCodeAt(i7) - 48) < 0 || cc > 9) break;
idx = 10 * idx + cc;
}
o9.e.r = --idx;
return o9;
}
function safe_format_cell(cell, v4) {
var q2 = cell.t == "d" && v4 instanceof Date;
if (cell.z != null) try {
return cell.w = SSF_format(cell.z, q2 ? datenum(v4) : v4);
} catch (e9) {
}
try {
return cell.w = SSF_format((cell.XF || {}).numFmtId || (q2 ? 14 : 0), q2 ? datenum(v4) : v4);
} catch (e9) {
return "" + v4;
}
}
function format_cell(cell, v4, o9) {
if (cell == null || cell.t == null || cell.t == "z") return "";
if (cell.w !== void 0) return cell.w;
if (cell.t == "d" && !cell.z && o9 && o9.dateNF) cell.z = o9.dateNF;
if (cell.t == "e") return BErr[cell.v] || cell.v;
if (v4 == void 0) return safe_format_cell(cell, cell.v);
return safe_format_cell(cell, v4);
}
function sheet_to_workbook(sheet, opts) {
var n7 = opts && opts.sheet ? opts.sheet : "Sheet1";
var sheets = {};
sheets[n7] = sheet;
return { SheetNames: [n7], Sheets: sheets };
}
function sheet_new(opts) {
var out = {};
var o9 = opts || {};
if (o9.dense) out["!data"] = [];
return out;
}
function sheet_add_aoa(_ws, data, opts) {
var o9 = opts || {};
var dense = _ws ? _ws["!data"] != null : o9.dense;
if (DENSE != null && dense == null) dense = DENSE;
var ws = _ws || (dense ? { "!data": [] } : {});
if (dense && !ws["!data"]) ws["!data"] = [];
var _R = 0, _C = 0;
if (ws && o9.origin != null) {
if (typeof o9.origin == "number") _R = o9.origin;
else {
var _origin2 = typeof o9.origin == "string" ? decode_cell(o9.origin) : o9.origin;
_R = _origin2.r;
_C = _origin2.c;
}
}
var range2 = { s: { c: 1e7, r: 1e7 }, e: { c: 0, r: 0 } };
if (ws["!ref"]) {
var _range = safe_decode_range(ws["!ref"]);
range2.s.c = _range.s.c;
range2.s.r = _range.s.r;
range2.e.c = Math.max(range2.e.c, _range.e.c);
range2.e.r = Math.max(range2.e.r, _range.e.r);
if (_R == -1) range2.e.r = _R = ws["!ref"] ? _range.e.r + 1 : 0;
} else {
range2.s.c = range2.e.c = range2.s.r = range2.e.r = 0;
}
var row = [], seen = false;
for (var R3 = 0; R3 != data.length; ++R3) {
if (!data[R3]) continue;
if (!Array.isArray(data[R3])) throw new Error("aoa_to_sheet expects an array of arrays");
var __R = _R + R3;
if (dense) {
if (!ws["!data"][__R]) ws["!data"][__R] = [];
row = ws["!data"][__R];
}
var data_R = data[R3];
for (var C3 = 0; C3 != data_R.length; ++C3) {
if (typeof data_R[C3] === "undefined") continue;
var cell = { v: data_R[C3], t: "" };
var __C = _C + C3;
if (range2.s.r > __R) range2.s.r = __R;
if (range2.s.c > __C) range2.s.c = __C;
if (range2.e.r < __R) range2.e.r = __R;
if (range2.e.c < __C) range2.e.c = __C;
seen = true;
if (data_R[C3] && typeof data_R[C3] === "object" && !Array.isArray(data_R[C3]) && !(data_R[C3] instanceof Date)) cell = data_R[C3];
else {
if (Array.isArray(cell.v)) {
cell.f = data_R[C3][1];
cell.v = cell.v[0];
}
if (cell.v === null) {
if (cell.f) cell.t = "n";
else if (o9.nullError) {
cell.t = "e";
cell.v = 0;
} else if (!o9.sheetStubs) continue;
else cell.t = "z";
} else if (typeof cell.v === "number") {
if (isFinite(cell.v)) cell.t = "n";
else if (isNaN(cell.v)) {
cell.t = "e";
cell.v = 15;
} else {
cell.t = "e";
cell.v = 7;
}
} else if (typeof cell.v === "boolean") cell.t = "b";
else if (cell.v instanceof Date) {
cell.z = o9.dateNF || table_fmt[14];
if (!o9.UTC) cell.v = local_to_utc(cell.v);
if (o9.cellDates) {
cell.t = "d";
cell.w = SSF_format(cell.z, datenum(cell.v, o9.date1904));
} else {
cell.t = "n";
cell.v = datenum(cell.v, o9.date1904);
cell.w = SSF_format(cell.z, cell.v);
}
} else cell.t = "s";
}
if (dense) {
if (row[__C] && row[__C].z) cell.z = row[__C].z;
row[__C] = cell;
} else {
var cell_ref = encode_col(__C) + (__R + 1);
if (ws[cell_ref] && ws[cell_ref].z) cell.z = ws[cell_ref].z;
ws[cell_ref] = cell;
}
}
}
if (seen && range2.s.c < 104e5) ws["!ref"] = encode_range(range2);
return ws;
}
function aoa_to_sheet(data, opts) {
return sheet_add_aoa(null, data, opts);
}
function parse_Int32LE(data) {
return data.read_shift(4, "i");
}
function parse_XLWideString(data) {
var cchCharacters = data.read_shift(4);
return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, "dbcs");
}
function parse_StrRun(data) {
return { ich: data.read_shift(2), ifnt: data.read_shift(2) };
}
function parse_RichStr(data, length) {
var start = data.l;
var flags = data.read_shift(1);
var str2 = parse_XLWideString(data);
var rgsStrRun = [];
var z3 = { t: str2, h: str2 };
if ((flags & 1) !== 0) {
var dwSizeStrRun = data.read_shift(4);
for (var i7 = 0; i7 != dwSizeStrRun; ++i7) rgsStrRun.push(parse_StrRun(data));
z3.r = rgsStrRun;
} else z3.r = [{ ich: 0, ifnt: 0 }];
data.l = start + length;
return z3;
}
function parse_XLSBCell(data) {
var col = data.read_shift(4);
var iStyleRef = data.read_shift(2);
iStyleRef += data.read_shift(1) << 16;
data.l++;
return { c: col, iStyleRef };
}
function parse_XLSBShortCell(data) {
var iStyleRef = data.read_shift(2);
iStyleRef += data.read_shift(1) << 16;
data.l++;
return { c: -1, iStyleRef };
}
function parse_XLNullableWideString(data) {
var cchCharacters = data.read_shift(4);
return cchCharacters === 0 || cchCharacters === 4294967295 ? "" : data.read_shift(cchCharacters, "dbcs");
}
function parse_RkNumber(data) {
var b4 = data.slice(data.l, data.l + 4);
var fX100 = b4[0] & 1, fInt = b4[0] & 2;
data.l += 4;
var RK = fInt === 0 ? __double([0, 0, 0, 0, b4[0] & 252, b4[1], b4[2], b4[3]], 0) : __readInt32LE(b4, 0) >> 2;
return fX100 ? RK / 100 : RK;
}
function parse_RfX(data) {
var cell = { s: {}, e: {} };
cell.s.r = data.read_shift(4);
cell.e.r = data.read_shift(4);
cell.s.c = data.read_shift(4);
cell.e.c = data.read_shift(4);
return cell;
}
function parse_Xnum(data) {
if (data.length - data.l < 8) throw "XLS Xnum Buffer underflow";
return data.read_shift(8, "f");
}
function parse_BrtColor(data) {
var out = {};
var d4 = data.read_shift(1);
var xColorType = d4 >>> 1;
var index2 = data.read_shift(1);
var nTS = data.read_shift(2, "i");
var bR = data.read_shift(1);
var bG = data.read_shift(1);
var bB = data.read_shift(1);
data.l++;
switch (xColorType) {
case 0:
out.auto = 1;
break;
case 1:
out.index = index2;
var icv = XLSIcv[index2];
if (icv) out.rgb = rgb2Hex(icv);
break;
case 2:
out.rgb = rgb2Hex([bR, bG, bB]);
break;
case 3:
out.theme = index2;
break;
}
if (nTS != 0) out.tint = nTS > 0 ? nTS / 32767 : nTS / 32768;
return out;
}
function parse_FontFlags(data) {
var d4 = data.read_shift(1);
data.l++;
var out = {
fBold: d4 & 1,
fItalic: d4 & 2,
fUnderline: d4 & 4,
fStrikeout: d4 & 8,
fOutline: d4 & 16,
fShadow: d4 & 32,
fCondense: d4 & 64,
fExtend: d4 & 128
};
return out;
}
function parse_ClipboardFormatOrString(o9, w3) {
var ClipFmt = { 2: "BITMAP", 3: "METAFILEPICT", 8: "DIB", 14: "ENHMETAFILE" };
var m4 = o9.read_shift(4);
switch (m4) {
case 0:
return "";
case 4294967295:
case 4294967294:
return ClipFmt[o9.read_shift(4)] || "";
}
if (m4 > 400) throw new Error("Unsupported Clipboard: " + m4.toString(16));
o9.l -= 4;
return o9.read_shift(0, w3 == 1 ? "lpstr" : "lpwstr");
}
function parse_ClipboardFormatOrAnsiString(o9) {
return parse_ClipboardFormatOrString(o9, 1);
}
function parse_ClipboardFormatOrUnicodeString(o9) {
return parse_ClipboardFormatOrString(o9, 2);
}
function rgbify(arr) {
return arr.map(function(x2) {
return [x2 >> 16 & 255, x2 >> 8 & 255, x2 & 255];
});
}
function new_ct() {
return {
workbooks: [],
sheets: [],
charts: [],
dialogs: [],
macros: [],
rels: [],
strs: [],
comments: [],
threadedcomments: [],
links: [],
coreprops: [],
extprops: [],
custprops: [],
themes: [],
styles: [],
calcchains: [],
vba: [],
drawings: [],
metadata: [],
people: [],
TODO: [],
xmlns: ""
};
}
function parse_ct(data) {
var ct = new_ct();
if (!data || !data.match) return ct;
var ctext = {};
(data.match(tagregex) || []).forEach(function(x2) {
var y4 = parsexmltag(x2);
switch (y4[0].replace(nsregex, "<")) {
case " 0 ? ct.calcchains[0] : "";
ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
ct.defaults = ctext;
delete ct.calcchains;
return ct;
}
function get_rels_path(file) {
var n7 = file.lastIndexOf("/");
return file.slice(0, n7 + 1) + "_rels/" + file.slice(n7 + 1) + ".rels";
}
function parse_rels(data, currentFilePath) {
var rels = { "!id": {} };
if (!data) return rels;
if (currentFilePath.charAt(0) !== "/") {
currentFilePath = "/" + currentFilePath;
}
var hash = {};
(data.match(tagregex) || []).forEach(function(x2) {
var y4 = parsexmltag(x2);
if (y4[0] === " 0) p4[f4[1]] = unescapexml(cur[1]);
if (f4[2] === "date" && p4[f4[1]]) p4[f4[1]] = parseDate(p4[f4[1]]);
}
return p4;
}
function load_props_pairs(HP, TOP, props, opts) {
var v4 = [];
if (typeof HP == "string") v4 = parseVector(HP, opts);
else for (var j3 = 0; j3 < HP.length; ++j3) v4 = v4.concat(HP[j3].map(function(hp) {
return { v: hp };
}));
var parts = typeof TOP == "string" ? parseVector(TOP, opts).map(function(x2) {
return x2.v;
}) : TOP;
var idx = 0, len = 0;
if (parts.length > 0) for (var i7 = 0; i7 !== v4.length; i7 += 2) {
len = +v4[i7 + 1].v;
switch (v4[i7].v) {
case "Worksheets":
case "\u5DE5\u4F5C\u8868":
case "\u041B\u0438\u0441\u0442\u044B":
case "\u0623\u0648\u0631\u0627\u0642 \u0627\u0644\u0639\u0645\u0644":
case "\u30EF\u30FC\u30AF\u30B7\u30FC\u30C8":
case "\u05D2\u05DC\u05D9\u05D5\u05E0\u05D5\u05EA \u05E2\u05D1\u05D5\u05D3\u05D4":
case "Arbeitsbl\xE4tter":
case "\xC7al\u0131\u015Fma Sayfalar\u0131":
case "Feuilles de calcul":
case "Fogli di lavoro":
case "Folhas de c\xE1lculo":
case "Planilhas":
case "Regneark":
case "Hojas de c\xE1lculo":
case "Werkbladen":
props.Worksheets = len;
props.SheetNames = parts.slice(idx, idx + len);
break;
case "Named Ranges":
case "Rangos con nombre":
case "\u540D\u524D\u4ED8\u304D\u4E00\u89A7":
case "Benannte Bereiche":
case "Navngivne omr\xE5der":
props.NamedRanges = len;
props.DefinedNames = parts.slice(idx, idx + len);
break;
case "Charts":
case "Diagramme":
props.Chartsheets = len;
props.ChartNames = parts.slice(idx, idx + len);
break;
}
idx += len;
}
}
function parse_ext_props(data, p4, opts) {
var q2 = {};
if (!p4) p4 = {};
data = utf8read(data);
EXT_PROPS.forEach(function(f4) {
var xml2 = (str_match_xml_ns(data, f4[0]) || [])[1];
switch (f4[2]) {
case "string":
if (xml2) p4[f4[1]] = unescapexml(xml2);
break;
case "bool":
p4[f4[1]] = xml2 === "true";
break;
case "raw":
var cur = str_match_xml(data, f4[0]);
if (cur && cur.length > 0) q2[f4[1]] = cur[1];
break;
}
});
if (q2.HeadingPairs && q2.TitlesOfParts) load_props_pairs(q2.HeadingPairs, q2.TitlesOfParts, p4, opts);
return p4;
}
function parse_cust_props(data, opts) {
var p4 = {}, name = "";
var m4 = data.match(custregex);
if (m4) for (var i7 = 0; i7 != m4.length; ++i7) {
var x2 = m4[i7], y4 = parsexmltag(x2);
switch (strip_ns(y4[0])) {
case "":
name = null;
break;
default:
if (x2.indexOf("");
var type = toks[0].slice(4), text3 = toks[1];
switch (type) {
case "lpstr":
case "bstr":
case "lpwstr":
p4[name] = unescapexml(text3);
break;
case "bool":
p4[name] = parsexmlbool(text3);
break;
case "i1":
case "i2":
case "i4":
case "i8":
case "int":
case "uint":
p4[name] = parseInt(text3, 10);
break;
case "r4":
case "r8":
case "decimal":
p4[name] = parseFloat(text3);
break;
case "filetime":
case "date":
p4[name] = parseDate(text3);
break;
case "cy":
case "error":
p4[name] = unescapexml(text3);
break;
default:
if (type.slice(-1) == "/") break;
if (opts.WTF && typeof console !== "undefined") console.warn("Unexpected", x2, type, toks);
}
} else if (x2.slice(0, 2) === "") {
} else if (opts.WTF) throw new Error(x2);
}
}
return p4;
}
function xlml_set_prop(Props, tag, val2) {
if (!evert_XLMLDPM) evert_XLMLDPM = evert(XLMLDocPropsMap);
tag = evert_XLMLDPM[tag] || tag;
Props[tag] = val2;
}
function parse_FILETIME(blob) {
var dwLowDateTime = blob.read_shift(4), dwHighDateTime = blob.read_shift(4);
return new Date((dwHighDateTime / 1e7 * Math.pow(2, 32) + dwLowDateTime / 1e7 - 11644473600) * 1e3).toISOString().replace(/\.000/, "");
}
function parse_lpstr(blob, type, pad2) {
var start = blob.l;
var str2 = blob.read_shift(0, "lpstr-cp");
if (pad2) while (blob.l - start & 3) ++blob.l;
return str2;
}
function parse_lpwstr(blob, type, pad2) {
var str2 = blob.read_shift(0, "lpwstr");
if (pad2) blob.l += 4 - (str2.length + 1 & 3) & 3;
return str2;
}
function parse_VtStringBase(blob, stringType3, pad2) {
if (stringType3 === 31) return parse_lpwstr(blob);
return parse_lpstr(blob, stringType3, pad2);
}
function parse_VtString(blob, t6, pad2) {
return parse_VtStringBase(blob, t6, pad2 === false ? 0 : 4);
}
function parse_VtUnalignedString(blob, t6) {
if (!t6) throw new Error("VtUnalignedString must have positive length");
return parse_VtStringBase(blob, t6, 0);
}
function parse_VtVecLpwstrValue(blob) {
var length = blob.read_shift(4);
var ret = [];
for (var i7 = 0; i7 != length; ++i7) {
var start = blob.l;
ret[i7] = blob.read_shift(0, "lpwstr").replace(chr0, "");
if (blob.l - start & 2) blob.l += 2;
}
return ret;
}
function parse_VtVecUnalignedLpstrValue(blob) {
var length = blob.read_shift(4);
var ret = [];
for (var i7 = 0; i7 != length; ++i7) ret[i7] = blob.read_shift(0, "lpstr-cp").replace(chr0, "");
return ret;
}
function parse_VtHeadingPair(blob) {
var start = blob.l;
var headingString = parse_TypedPropertyValue(blob, VT_USTR);
if (blob[blob.l] == 0 && blob[blob.l + 1] == 0 && blob.l - start & 2) blob.l += 2;
var headerParts = parse_TypedPropertyValue(blob, VT_I4);
return [headingString, headerParts];
}
function parse_VtVecHeadingPairValue(blob) {
var cElements = blob.read_shift(4);
var out = [];
for (var i7 = 0; i7 < cElements / 2; ++i7) out.push(parse_VtHeadingPair(blob));
return out;
}
function parse_dictionary(blob, CodePage) {
var cnt = blob.read_shift(4);
var dict = {};
for (var j3 = 0; j3 != cnt; ++j3) {
var pid = blob.read_shift(4);
var len = blob.read_shift(4);
dict[pid] = blob.read_shift(len, CodePage === 1200 ? "utf16le" : "utf8").replace(chr0, "").replace(chr1, "!");
if (CodePage === 1200 && len % 2) blob.l += 2;
}
if (blob.l & 3) blob.l = blob.l >> 2 + 1 << 2;
return dict;
}
function parse_BLOB(blob) {
var size = blob.read_shift(4);
var bytes = blob.slice(blob.l, blob.l + size);
blob.l += size;
if ((size & 3) > 0) blob.l += 4 - (size & 3) & 3;
return bytes;
}
function parse_ClipboardData(blob) {
var o9 = {};
o9.Size = blob.read_shift(4);
blob.l += o9.Size + 3 - (o9.Size - 1) % 4;
return o9;
}
function parse_TypedPropertyValue(blob, type, _opts) {
var t6 = blob.read_shift(2), ret, opts = _opts || {};
blob.l += 2;
if (type !== VT_VARIANT) {
if (t6 !== type && VT_CUSTOM.indexOf(type) === -1 && !((type & 65534) == 4126 && (t6 & 65534) == 4126)) throw new Error("Expected type " + type + " saw " + t6);
}
switch (type === VT_VARIANT ? t6 : type) {
case 2:
ret = blob.read_shift(2, "i");
if (!opts.raw) blob.l += 2;
return ret;
case 3:
ret = blob.read_shift(4, "i");
return ret;
case 11:
return blob.read_shift(4) !== 0;
case 19:
ret = blob.read_shift(4);
return ret;
case 30:
blob.l += 4;
val = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1");
break;
case 31:
blob.l += 4;
val = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1");
break;
case 64:
return parse_FILETIME(blob);
case 65:
return parse_BLOB(blob);
case 71:
return parse_ClipboardData(blob);
case 80:
return parse_VtString(blob, t6, !opts.raw).replace(chr0, "");
case 81:
return parse_VtUnalignedString(
blob,
t6
/*, 4*/
).replace(chr0, "");
case 4108:
return parse_VtVecHeadingPairValue(blob);
case 4126:
case 4127:
return t6 == 4127 ? parse_VtVecLpwstrValue(blob) : parse_VtVecUnalignedLpstrValue(blob);
default:
throw new Error("TypedPropertyValue unrecognized type " + type + " " + t6);
}
}
function parse_PropertySet(blob, PIDSI) {
var start_addr = blob.l;
var size = blob.read_shift(4);
var NumProps = blob.read_shift(4);
var Props = [], i7 = 0;
var CodePage = 0;
var Dictionary = -1, DictObj = {};
for (i7 = 0; i7 != NumProps; ++i7) {
var PropID = blob.read_shift(4);
var Offset = blob.read_shift(4);
Props[i7] = [PropID, Offset + start_addr];
}
Props.sort(function(x2, y4) {
return x2[1] - y4[1];
});
var PropH = {};
for (i7 = 0; i7 != NumProps; ++i7) {
if (blob.l !== Props[i7][1]) {
var fail = true;
if (i7 > 0 && PIDSI) switch (PIDSI[Props[i7 - 1][0]].t) {
case 2:
if (blob.l + 2 === Props[i7][1]) {
blob.l += 2;
fail = false;
}
break;
case 80:
if (blob.l <= Props[i7][1]) {
blob.l = Props[i7][1];
fail = false;
}
break;
case 4108:
if (blob.l <= Props[i7][1]) {
blob.l = Props[i7][1];
fail = false;
}
break;
}
if ((!PIDSI || i7 == 0) && blob.l <= Props[i7][1]) {
fail = false;
blob.l = Props[i7][1];
}
if (fail) throw new Error("Read Error: Expected address " + Props[i7][1] + " at " + blob.l + " :" + i7);
}
if (PIDSI) {
if (Props[i7][0] == 0 && Props.length > i7 + 1 && Props[i7][1] == Props[i7 + 1][1]) continue;
var piddsi = PIDSI[Props[i7][0]];
PropH[piddsi.n] = parse_TypedPropertyValue(blob, piddsi.t, { raw: true });
if (piddsi.p === "version") PropH[piddsi.n] = String(PropH[piddsi.n] >> 16) + "." + ("0000" + String(PropH[piddsi.n] & 65535)).slice(-4);
if (piddsi.n == "CodePage") switch (PropH[piddsi.n]) {
case 0:
PropH[piddsi.n] = 1252;
/* falls through */
case 874:
case 932:
case 936:
case 949:
case 950:
case 1250:
case 1251:
case 1253:
case 1254:
case 1255:
case 1256:
case 1257:
case 1258:
case 1e4:
case 1200:
case 1201:
case 1252:
case 65e3:
case -536:
case 65001:
case -535:
set_cp(CodePage = PropH[piddsi.n] >>> 0 & 65535);
break;
default:
throw new Error("Unsupported CodePage: " + PropH[piddsi.n]);
}
} else {
if (Props[i7][0] === 1) {
CodePage = PropH.CodePage = parse_TypedPropertyValue(blob, VT_I2);
set_cp(CodePage);
if (Dictionary !== -1) {
var oldpos = blob.l;
blob.l = Props[Dictionary][1];
DictObj = parse_dictionary(blob, CodePage);
blob.l = oldpos;
}
} else if (Props[i7][0] === 0) {
if (CodePage === 0) {
Dictionary = i7;
blob.l = Props[i7 + 1][1];
continue;
}
DictObj = parse_dictionary(blob, CodePage);
} else {
var name = DictObj[Props[i7][0]];
var val2;
switch (blob[blob.l]) {
case 65:
blob.l += 4;
val2 = parse_BLOB(blob);
break;
case 30:
blob.l += 4;
val2 = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1");
break;
case 31:
blob.l += 4;
val2 = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1");
break;
case 3:
blob.l += 4;
val2 = blob.read_shift(4, "i");
break;
case 19:
blob.l += 4;
val2 = blob.read_shift(4);
break;
case 5:
blob.l += 4;
val2 = blob.read_shift(8, "f");
break;
case 11:
blob.l += 4;
val2 = parsebool(blob, 4);
break;
case 64:
blob.l += 4;
val2 = parseDate(parse_FILETIME(blob));
break;
default:
throw new Error("unparsed value: " + blob[blob.l]);
}
PropH[name] = val2;
}
}
}
blob.l = start_addr + size;
return PropH;
}
function parse_PropertySetStream(file, PIDSI, clsid) {
var blob = file.content;
if (!blob) return {};
prep_blob(blob, 0);
var NumSets, FMTID0, FMTID1, Offset0, Offset1 = 0;
blob.chk("feff", "Byte Order: ");
blob.read_shift(2);
var SystemIdentifier = blob.read_shift(4);
var CLSID = blob.read_shift(16);
if (CLSID !== CFB.utils.consts.HEADER_CLSID && CLSID !== clsid) throw new Error("Bad PropertySet CLSID " + CLSID);
NumSets = blob.read_shift(4);
if (NumSets !== 1 && NumSets !== 2) throw new Error("Unrecognized #Sets: " + NumSets);
FMTID0 = blob.read_shift(16);
Offset0 = blob.read_shift(4);
if (NumSets === 1 && Offset0 !== blob.l) throw new Error("Length mismatch: " + Offset0 + " !== " + blob.l);
else if (NumSets === 2) {
FMTID1 = blob.read_shift(16);
Offset1 = blob.read_shift(4);
}
var PSet0 = parse_PropertySet(blob, PIDSI);
var rval = { SystemIdentifier };
for (var y4 in PSet0) rval[y4] = PSet0[y4];
rval.FMTID = FMTID0;
if (NumSets === 1) return rval;
if (Offset1 - blob.l == 2) blob.l += 2;
if (blob.l !== Offset1) throw new Error("Length mismatch 2: " + blob.l + " !== " + Offset1);
var PSet1;
try {
PSet1 = parse_PropertySet(blob, null);
} catch (e9) {
}
for (y4 in PSet1) rval[y4] = PSet1[y4];
rval.FMTID = [FMTID0, FMTID1];
return rval;
}
function parsenoop2(blob, length) {
blob.read_shift(length);
return null;
}
function parslurp(blob, length, cb) {
var arr = [], target = blob.l + length;
while (blob.l < target) arr.push(cb(blob, target - blob.l));
if (target !== blob.l) throw new Error("Slurp error");
return arr;
}
function parsebool(blob, length) {
return blob.read_shift(length) === 1;
}
function parseuint16(blob) {
return blob.read_shift(2, "u");
}
function parseuint16a(blob, length) {
return parslurp(blob, length, parseuint16);
}
function parse_Bes(blob) {
var v4 = blob.read_shift(1), t6 = blob.read_shift(1);
return t6 === 1 ? v4 : v4 === 1;
}
function parse_ShortXLUnicodeString(blob, length, opts) {
var cch = blob.read_shift(opts && opts.biff >= 12 ? 2 : 1);
var encoding = "sbcs-cont";
var cp = current_codepage;
if (opts && opts.biff >= 8) current_codepage = 1200;
if (!opts || opts.biff == 8) {
var fHighByte = blob.read_shift(1);
if (fHighByte) {
encoding = "dbcs-cont";
}
} else if (opts.biff == 12) {
encoding = "wstr";
}
if (opts.biff >= 2 && opts.biff <= 5) encoding = "cpstr";
var o9 = cch ? blob.read_shift(cch, encoding) : "";
current_codepage = cp;
return o9;
}
function parse_XLUnicodeRichExtendedString(blob) {
var cp = current_codepage;
current_codepage = 1200;
var cch = blob.read_shift(2), flags = blob.read_shift(1);
var fExtSt = flags & 4, fRichSt = flags & 8;
var width = 1 + (flags & 1);
var cRun = 0, cbExtRst;
var z3 = {};
if (fRichSt) cRun = blob.read_shift(2);
if (fExtSt) cbExtRst = blob.read_shift(4);
var encoding = width == 2 ? "dbcs-cont" : "sbcs-cont";
var msg = cch === 0 ? "" : blob.read_shift(cch, encoding);
if (fRichSt) blob.l += 4 * cRun;
if (fExtSt) blob.l += cbExtRst;
z3.t = msg;
if (!fRichSt) {
z3.raw = "" + z3.t + " ";
z3.r = z3.t;
}
current_codepage = cp;
return z3;
}
function parse_XLUnicodeStringNoCch(blob, cch, opts) {
var retval;
if (opts) {
if (opts.biff >= 2 && opts.biff <= 5) return blob.read_shift(cch, "cpstr");
if (opts.biff >= 12) return blob.read_shift(cch, "dbcs-cont");
}
var fHighByte = blob.read_shift(1);
if (fHighByte === 0) {
retval = blob.read_shift(cch, "sbcs-cont");
} else {
retval = blob.read_shift(cch, "dbcs-cont");
}
return retval;
}
function parse_XLUnicodeString(blob, length, opts) {
var cch = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
if (cch === 0) {
blob.l++;
return "";
}
return parse_XLUnicodeStringNoCch(blob, cch, opts);
}
function parse_XLUnicodeString2(blob, length, opts) {
if (opts.biff > 5) return parse_XLUnicodeString(blob, length, opts);
var cch = blob.read_shift(1);
if (cch === 0) {
blob.l++;
return "";
}
return blob.read_shift(cch, opts.biff <= 4 || !blob.lens ? "cpstr" : "sbcs-cont");
}
function parse_ControlInfo(blob) {
var flags = blob.read_shift(1);
blob.l++;
var accel = blob.read_shift(2);
blob.l += 2;
return [flags, accel];
}
function parse_URLMoniker(blob) {
var len = blob.read_shift(4), start = blob.l;
var extra = false;
if (len > 24) {
blob.l += len - 24;
if (blob.read_shift(16) === "795881f43b1d7f48af2c825dc4852763") extra = true;
blob.l = start;
}
var url = blob.read_shift((extra ? len - 24 : len) >> 1, "utf16le").replace(chr0, "");
if (extra) blob.l += 24;
return url;
}
function parse_FileMoniker(blob) {
var cAnti = blob.read_shift(2);
var preamble = "";
while (cAnti-- > 0) preamble += "../";
var ansiPath = blob.read_shift(0, "lpstr-ansi");
blob.l += 2;
if (blob.read_shift(2) != 57005) throw new Error("Bad FileMoniker");
var sz = blob.read_shift(4);
if (sz === 0) return preamble + ansiPath.replace(/\\/g, "/");
var bytes = blob.read_shift(4);
if (blob.read_shift(2) != 3) throw new Error("Bad FileMoniker");
var unicodePath = blob.read_shift(bytes >> 1, "utf16le").replace(chr0, "");
return preamble + unicodePath;
}
function parse_HyperlinkMoniker(blob, length) {
var clsid = blob.read_shift(16);
length -= 16;
switch (clsid) {
case "e0c9ea79f9bace118c8200aa004ba90b":
return parse_URLMoniker(blob, length);
case "0303000000000000c000000000000046":
return parse_FileMoniker(blob, length);
default:
throw new Error("Unsupported Moniker " + clsid);
}
}
function parse_HyperlinkString(blob) {
var len = blob.read_shift(4);
var o9 = len > 0 ? blob.read_shift(len, "utf16le").replace(chr0, "") : "";
return o9;
}
function parse_Hyperlink(blob, length) {
var end = blob.l + length;
var sVer = blob.read_shift(4);
if (sVer !== 2) throw new Error("Unrecognized streamVersion: " + sVer);
var flags = blob.read_shift(2);
blob.l += 2;
var displayName, targetFrameName, moniker, oleMoniker, Loc = "", guid, fileTime;
if (flags & 16) displayName = parse_HyperlinkString(blob, end - blob.l);
if (flags & 128) targetFrameName = parse_HyperlinkString(blob, end - blob.l);
if ((flags & 257) === 257) moniker = parse_HyperlinkString(blob, end - blob.l);
if ((flags & 257) === 1) oleMoniker = parse_HyperlinkMoniker(blob, end - blob.l);
if (flags & 8) Loc = parse_HyperlinkString(blob, end - blob.l);
if (flags & 32) guid = blob.read_shift(16);
if (flags & 64) fileTime = parse_FILETIME(
blob
/*, 8*/
);
blob.l = end;
var target = targetFrameName || moniker || oleMoniker || "";
if (target && Loc) target += "#" + Loc;
if (!target) target = "#" + Loc;
if (flags & 2 && target.charAt(0) == "/" && target.charAt(1) != "/") target = "file://" + target;
var out = { Target: target };
if (guid) out.guid = guid;
if (fileTime) out.time = fileTime;
if (displayName) out.Tooltip = displayName;
return out;
}
function parse_LongRGBA(blob) {
var r8 = blob.read_shift(1), g3 = blob.read_shift(1), b4 = blob.read_shift(1), a3 = blob.read_shift(1);
return [r8, g3, b4, a3];
}
function parse_LongRGB(blob, length) {
var x2 = parse_LongRGBA(blob, length);
x2[3] = 0;
return x2;
}
function parse_XLSCell(blob, length, opts) {
var rw = blob.read_shift(2);
var col = blob.read_shift(2);
var ret = { r: rw, c: col, ixfe: 0 };
if (opts && opts.biff == 2 || length == 7) {
var flags = blob.read_shift(1);
ret.ixfe = flags & 63;
blob.l += 2;
} else ret.ixfe = blob.read_shift(2);
return ret;
}
function parse_frtHeader(blob) {
var rt = blob.read_shift(2);
var flags = blob.read_shift(2);
blob.l += 8;
return { type: rt, flags };
}
function parse_OptXLUnicodeString(blob, length, opts) {
return length === 0 ? "" : parse_XLUnicodeString2(blob, length, opts);
}
function parse_XTI(blob, length, opts) {
var w3 = opts.biff > 8 ? 4 : 2;
var iSupBook = blob.read_shift(w3), itabFirst = blob.read_shift(w3, "i"), itabLast = blob.read_shift(w3, "i");
return [iSupBook, itabFirst, itabLast];
}
function parse_RkRec(blob) {
var ixfe = blob.read_shift(2);
var RK = parse_RkNumber(blob);
return [ixfe, RK];
}
function parse_AddinUdf(blob, length, opts) {
blob.l += 4;
length -= 4;
var l5 = blob.l + length;
var udfName = parse_ShortXLUnicodeString(blob, length, opts);
var cb = blob.read_shift(2);
l5 -= blob.l;
if (cb !== l5) throw new Error("Malformed AddinUdf: padding = " + l5 + " != " + cb);
blob.l += cb;
return udfName;
}
function parse_Ref8U(blob) {
var rwFirst = blob.read_shift(2);
var rwLast = blob.read_shift(2);
var colFirst = blob.read_shift(2);
var colLast = blob.read_shift(2);
return { s: { c: colFirst, r: rwFirst }, e: { c: colLast, r: rwLast } };
}
function parse_RefU(blob) {
var rwFirst = blob.read_shift(2);
var rwLast = blob.read_shift(2);
var colFirst = blob.read_shift(1);
var colLast = blob.read_shift(1);
return { s: { c: colFirst, r: rwFirst }, e: { c: colLast, r: rwLast } };
}
function parse_FtCmo(blob) {
blob.l += 4;
var ot = blob.read_shift(2);
var id = blob.read_shift(2);
var flags = blob.read_shift(2);
blob.l += 12;
return [id, ot, flags];
}
function parse_FtNts(blob) {
var out = {};
blob.l += 4;
blob.l += 16;
out.fSharedNote = blob.read_shift(2);
blob.l += 4;
return out;
}
function parse_FtCf(blob) {
var out = {};
blob.l += 4;
blob.cf = blob.read_shift(2);
return out;
}
function parse_FtSkip(blob) {
blob.l += 2;
blob.l += blob.read_shift(2);
}
function parse_FtArray(blob, length) {
var tgt = blob.l + length;
var fts = [];
while (blob.l < tgt) {
var ft = blob.read_shift(2);
blob.l -= 2;
try {
fts[ft] = FtTab[ft](blob, tgt - blob.l);
} catch (e9) {
blob.l = tgt;
return fts;
}
}
if (blob.l != tgt) blob.l = tgt;
return fts;
}
function parse_BOF(blob, length) {
var o9 = { BIFFVer: 0, dt: 0 };
o9.BIFFVer = blob.read_shift(2);
length -= 2;
if (length >= 2) {
o9.dt = blob.read_shift(2);
blob.l -= 2;
}
switch (o9.BIFFVer) {
case 1536:
/* BIFF8 */
case 1280:
/* BIFF5 */
case 1024:
/* BIFF4 */
case 768:
/* BIFF3 */
case 512:
/* BIFF2 */
case 2:
case 7:
break;
default:
if (length > 6) throw new Error("Unexpected BIFF Ver " + o9.BIFFVer);
}
blob.read_shift(length);
return o9;
}
function parse_InterfaceHdr(blob, length) {
if (length === 0) return 1200;
if (blob.read_shift(2) !== 1200) {
}
return 1200;
}
function parse_WriteAccess(blob, length, opts) {
if (opts.enc) {
blob.l += length;
return "";
}
var l5 = blob.l;
var UserName = parse_XLUnicodeString2(blob, 0, opts);
blob.read_shift(length + l5 - blob.l);
return UserName;
}
function parse_WsBool(blob, length, opts) {
var flags = opts && opts.biff == 8 || length == 2 ? blob.read_shift(2) : (blob.l += length, 0);
return { fDialog: flags & 16, fBelow: flags & 64, fRight: flags & 128 };
}
function parse_BoundSheet8(blob, length, opts) {
var name = "";
if (opts.biff == 4) {
name = parse_ShortXLUnicodeString(blob, 0, opts);
if (name.length === 0) name = "Sheet1";
return { name };
}
var pos = blob.read_shift(4);
var hidden = blob.read_shift(1) & 3;
var dt = blob.read_shift(1);
switch (dt) {
case 0:
dt = "Worksheet";
break;
case 1:
dt = "Macrosheet";
break;
case 2:
dt = "Chartsheet";
break;
case 6:
dt = "VBAModule";
break;
}
name = parse_ShortXLUnicodeString(blob, 0, opts);
if (name.length === 0) name = "Sheet1";
return { pos, hs: hidden, dt, name };
}
function parse_SST(blob, length) {
var end = blob.l + length;
var cnt = blob.read_shift(4);
var ucnt = blob.read_shift(4);
var strs2 = [];
for (var i7 = 0; i7 != ucnt && blob.l < end; ++i7) {
strs2.push(parse_XLUnicodeRichExtendedString(blob));
}
strs2.Count = cnt;
strs2.Unique = ucnt;
return strs2;
}
function parse_ExtSST(blob, length) {
var extsst = {};
extsst.dsst = blob.read_shift(2);
blob.l += length - 2;
return extsst;
}
function parse_Row(blob) {
var z3 = {};
z3.r = blob.read_shift(2);
z3.c = blob.read_shift(2);
z3.cnt = blob.read_shift(2) - z3.c;
var miyRw = blob.read_shift(2);
blob.l += 4;
var flags = blob.read_shift(1);
blob.l += 3;
if (flags & 7) z3.level = flags & 7;
if (flags & 32) z3.hidden = true;
if (flags & 64) z3.hpt = miyRw / 20;
return z3;
}
function parse_ForceFullCalculation(blob) {
var header = parse_frtHeader(blob);
if (header.type != 2211) throw new Error("Invalid Future Record " + header.type);
var fullcalc = blob.read_shift(4);
return fullcalc !== 0;
}
function parse_RecalcId(blob) {
blob.read_shift(2);
return blob.read_shift(4);
}
function parse_DefaultRowHeight(blob, length, opts) {
var f4 = 0;
if (!(opts && opts.biff == 2)) {
f4 = blob.read_shift(2);
}
var miyRw = blob.read_shift(2);
if (opts && opts.biff == 2) {
f4 = 1 - (miyRw >> 15);
miyRw &= 32767;
}
var fl = { Unsynced: f4 & 1, DyZero: (f4 & 2) >> 1, ExAsc: (f4 & 4) >> 2, ExDsc: (f4 & 8) >> 3 };
return [fl, miyRw];
}
function parse_Window1(blob) {
var xWn = blob.read_shift(2), yWn = blob.read_shift(2), dxWn = blob.read_shift(2), dyWn = blob.read_shift(2);
var flags = blob.read_shift(2), iTabCur = blob.read_shift(2), iTabFirst = blob.read_shift(2);
var ctabSel = blob.read_shift(2), wTabRatio = blob.read_shift(2);
return {
Pos: [xWn, yWn],
Dim: [dxWn, dyWn],
Flags: flags,
CurTab: iTabCur,
FirstTab: iTabFirst,
Selected: ctabSel,
TabRatio: wTabRatio
};
}
function parse_Window2(blob, length, opts) {
if (opts && opts.biff >= 2 && opts.biff < 5) return {};
var f4 = blob.read_shift(2);
return { RTL: f4 & 64 };
}
function parse_Pane() {
}
function parse_Font(blob, length, opts) {
var o9 = {
dyHeight: blob.read_shift(2),
fl: blob.read_shift(2)
};
switch (opts && opts.biff || 8) {
case 2:
break;
case 3:
case 4:
blob.l += 2;
break;
default:
blob.l += 10;
break;
}
o9.name = parse_ShortXLUnicodeString(blob, 0, opts);
return o9;
}
function parse_LabelSst(blob, length, opts) {
var cell = parse_XLSCell(blob, length, opts);
cell.isst = blob.read_shift(4);
return cell;
}
function parse_Label(blob, length, opts) {
if (opts.biffguess && opts.biff == 2) opts.biff = 5;
var target = blob.l + length;
var cell = parse_XLSCell(blob, length, opts);
var str2 = parse_XLUnicodeString(blob, target - blob.l, opts);
cell.val = str2;
return cell;
}
function parse_Format(blob, length, opts) {
var numFmtId = blob.read_shift(2);
var fmtstr = parse_XLUnicodeString2(blob, 0, opts);
return [numFmtId, fmtstr];
}
function parse_Dimensions(blob, length, opts) {
var end = blob.l + length;
var w3 = opts.biff == 8 || !opts.biff ? 4 : 2;
var r8 = blob.read_shift(w3), R3 = blob.read_shift(w3);
var c6 = blob.read_shift(2), C3 = blob.read_shift(2);
blob.l = end;
return { s: { r: r8, c: c6 }, e: { r: R3, c: C3 } };
}
function parse_RK(blob) {
var rw = blob.read_shift(2), col = blob.read_shift(2);
var rkrec = parse_RkRec(blob);
return { r: rw, c: col, ixfe: rkrec[0], rknum: rkrec[1] };
}
function parse_MulRk(blob, length) {
var target = blob.l + length - 2;
var rw = blob.read_shift(2), col = blob.read_shift(2);
var rkrecs = [];
while (blob.l < target) rkrecs.push(parse_RkRec(blob));
if (blob.l !== target) throw new Error("MulRK read error");
var lastcol = blob.read_shift(2);
if (rkrecs.length != lastcol - col + 1) throw new Error("MulRK length mismatch");
return { r: rw, c: col, C: lastcol, rkrec: rkrecs };
}
function parse_MulBlank(blob, length) {
var target = blob.l + length - 2;
var rw = blob.read_shift(2), col = blob.read_shift(2);
var ixfes = [];
while (blob.l < target) ixfes.push(blob.read_shift(2));
if (blob.l !== target) throw new Error("MulBlank read error");
var lastcol = blob.read_shift(2);
if (ixfes.length != lastcol - col + 1) throw new Error("MulBlank length mismatch");
return { r: rw, c: col, C: lastcol, ixfe: ixfes };
}
function parse_CellStyleXF(blob, length, style, opts) {
var o9 = {};
var a3 = blob.read_shift(4), b4 = blob.read_shift(4);
var c6 = blob.read_shift(4), d4 = blob.read_shift(2);
o9.patternType = XLSFillPattern[c6 >> 26];
if (!opts.cellStyles) return o9;
o9.alc = a3 & 7;
o9.fWrap = a3 >> 3 & 1;
o9.alcV = a3 >> 4 & 7;
o9.fJustLast = a3 >> 7 & 1;
o9.trot = a3 >> 8 & 255;
o9.cIndent = a3 >> 16 & 15;
o9.fShrinkToFit = a3 >> 20 & 1;
o9.iReadOrder = a3 >> 22 & 2;
o9.fAtrNum = a3 >> 26 & 1;
o9.fAtrFnt = a3 >> 27 & 1;
o9.fAtrAlc = a3 >> 28 & 1;
o9.fAtrBdr = a3 >> 29 & 1;
o9.fAtrPat = a3 >> 30 & 1;
o9.fAtrProt = a3 >> 31 & 1;
o9.dgLeft = b4 & 15;
o9.dgRight = b4 >> 4 & 15;
o9.dgTop = b4 >> 8 & 15;
o9.dgBottom = b4 >> 12 & 15;
o9.icvLeft = b4 >> 16 & 127;
o9.icvRight = b4 >> 23 & 127;
o9.grbitDiag = b4 >> 30 & 3;
o9.icvTop = c6 & 127;
o9.icvBottom = c6 >> 7 & 127;
o9.icvDiag = c6 >> 14 & 127;
o9.dgDiag = c6 >> 21 & 15;
o9.icvFore = d4 & 127;
o9.icvBack = d4 >> 7 & 127;
o9.fsxButton = d4 >> 14 & 1;
return o9;
}
function parse_XF(blob, length, opts) {
var o9 = {};
o9.ifnt = blob.read_shift(2);
o9.numFmtId = blob.read_shift(2);
o9.flags = blob.read_shift(2);
o9.fStyle = o9.flags >> 2 & 1;
length -= 6;
o9.data = parse_CellStyleXF(blob, length, o9.fStyle, opts);
return o9;
}
function parse_BIFF2XF(blob) {
var o9 = {};
o9.ifnt = blob.read_shift(1);
blob.l++;
o9.flags = blob.read_shift(1);
o9.numFmtId = o9.flags & 63;
o9.flags >>= 6;
o9.fStyle = 0;
o9.data = {};
return o9;
}
function parse_BIFF3XF(blob) {
var o9 = {};
o9.ifnt = blob.read_shift(1);
o9.numFmtId = blob.read_shift(1);
o9.flags = blob.read_shift(2);
o9.fStyle = o9.flags >> 2 & 1;
o9.data = {};
return o9;
}
function parse_BIFF4XF(blob) {
var o9 = {};
o9.ifnt = blob.read_shift(1);
o9.numFmtId = blob.read_shift(1);
o9.flags = blob.read_shift(2);
o9.fStyle = o9.flags >> 2 & 1;
o9.data = {};
return o9;
}
function parse_Guts(blob) {
blob.l += 4;
var out = [blob.read_shift(2), blob.read_shift(2)];
if (out[0] !== 0) out[0]--;
if (out[1] !== 0) out[1]--;
if (out[0] > 7 || out[1] > 7) throw new Error("Bad Gutters: " + out.join("|"));
return out;
}
function parse_BoolErr(blob, length, opts) {
var cell = parse_XLSCell(blob, 6, opts);
var val2 = parse_Bes(blob, 2);
cell.val = val2;
cell.t = val2 === true || val2 === false ? "b" : "e";
return cell;
}
function parse_Number(blob, length, opts) {
if (opts.biffguess && opts.biff == 2) opts.biff = 5;
var cell = parse_XLSCell(blob, 6, opts);
var xnum = parse_Xnum(blob, 8);
cell.val = xnum;
return cell;
}
function parse_SupBook(blob, length, opts) {
var end = blob.l + length;
var ctab = blob.read_shift(2);
var cch = blob.read_shift(2);
opts.sbcch = cch;
if (cch == 1025 || cch == 14849) return [cch, ctab];
if (cch < 1 || cch > 255) throw new Error("Unexpected SupBook type: " + cch);
var virtPath = parse_XLUnicodeStringNoCch(blob, cch);
var rgst = [];
while (end > blob.l) rgst.push(parse_XLUnicodeString(blob));
return [cch, ctab, virtPath, rgst];
}
function parse_ExternName(blob, length, opts) {
var flags = blob.read_shift(2);
var body;
var o9 = {
fBuiltIn: flags & 1,
fWantAdvise: flags >>> 1 & 1,
fWantPict: flags >>> 2 & 1,
fOle: flags >>> 3 & 1,
fOleLink: flags >>> 4 & 1,
cf: flags >>> 5 & 1023,
fIcon: flags >>> 15 & 1
};
if (opts.sbcch === 14849) body = parse_AddinUdf(blob, length - 2, opts);
o9.body = body || blob.read_shift(length - 2);
if (typeof body === "string") o9.Name = body;
return o9;
}
function parse_Lbl(blob, length, opts) {
var target = blob.l + length;
var flags = blob.read_shift(2);
var chKey = blob.read_shift(1);
var cch = blob.read_shift(1);
var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
var itab = 0;
if (!opts || opts.biff >= 5) {
if (opts.biff != 5) blob.l += 2;
itab = blob.read_shift(2);
if (opts.biff == 5) blob.l += 2;
blob.l += 4;
}
var name = parse_XLUnicodeStringNoCch(blob, cch, opts);
if (flags & 32) name = XLSLblBuiltIn[name.charCodeAt(0)];
var npflen = target - blob.l;
if (opts && opts.biff == 2) --npflen;
var rgce = target == blob.l || cce === 0 || !(npflen > 0) ? [] : parse_NameParsedFormula(blob, npflen, opts, cce);
return {
chKey,
Name: name,
itab,
rgce
};
}
function parse_ExternSheet(blob, length, opts) {
if (opts.biff < 8) return parse_BIFF5ExternSheet(blob, length, opts);
if (!(opts.biff > 8) && length == blob[blob.l] + (blob[blob.l + 1] == 3 ? 1 : 0) + 1) return parse_BIFF5ExternSheet(blob, length, opts);
var o9 = [], target = blob.l + length, len = blob.read_shift(opts.biff > 8 ? 4 : 2);
while (len-- !== 0) o9.push(parse_XTI(blob, opts.biff > 8 ? 12 : 6, opts));
if (blob.l != target) throw new Error("Bad ExternSheet: " + blob.l + " != " + target);
return o9;
}
function parse_BIFF5ExternSheet(blob, length, opts) {
if (blob[blob.l + 1] == 3) blob[blob.l]++;
var o9 = parse_ShortXLUnicodeString(blob, length, opts);
return o9.charCodeAt(0) == 3 ? o9.slice(1) : o9;
}
function parse_NameCmt(blob, length, opts) {
if (opts.biff < 8) {
blob.l += length;
return;
}
var cchName = blob.read_shift(2);
var cchComment = blob.read_shift(2);
var name = parse_XLUnicodeStringNoCch(blob, cchName, opts);
var comment = parse_XLUnicodeStringNoCch(blob, cchComment, opts);
return [name, comment];
}
function parse_ShrFmla(blob, length, opts) {
var ref = parse_RefU(blob, 6);
blob.l++;
var cUse = blob.read_shift(1);
length -= 8;
return [parse_SharedParsedFormula(blob, length, opts), cUse, ref];
}
function parse_Array(blob, length, opts) {
var ref = parse_Ref(blob, 6);
switch (opts.biff) {
case 2:
blob.l++;
length -= 7;
break;
case 3:
case 4:
blob.l += 2;
length -= 8;
break;
default:
blob.l += 6;
length -= 12;
}
return [ref, parse_ArrayParsedFormula(blob, length, opts, ref)];
}
function parse_MTRSettings(blob) {
var fMTREnabled = blob.read_shift(4) !== 0;
var fUserSetThreadCount = blob.read_shift(4) !== 0;
var cUserThreadCount = blob.read_shift(4);
return [fMTREnabled, fUserSetThreadCount, cUserThreadCount];
}
function parse_NoteSh(blob, length, opts) {
var row = blob.read_shift(2), col = blob.read_shift(2);
var flags = blob.read_shift(2), idObj = blob.read_shift(2);
var stAuthor = parse_XLUnicodeString2(blob, 0, opts);
return [{ r: row, c: col }, stAuthor, idObj, flags];
}
function parse_Note(blob, length, opts) {
if (opts && opts.biff < 8) {
var row = blob.read_shift(2), col = blob.read_shift(2);
if (row == 65535 || row == -1) return;
var cch = blob.read_shift(2);
var cmnt = blob.read_shift(Math.min(cch, 2048), "cpstr");
return [{ r: row, c: col }, cmnt];
}
return parse_NoteSh(blob, length, opts);
}
function parse_MergeCells(blob, length) {
var merges = [];
var cmcs = blob.read_shift(2);
while (cmcs--) merges.push(parse_Ref8U(blob, length));
return merges;
}
function parse_Obj(blob, length, opts) {
if (opts && opts.biff < 8) return parse_BIFF5Obj(blob, length, opts);
var cmo = parse_FtCmo(blob, 22);
var fts = parse_FtArray(blob, length - 22, cmo[1]);
return { cmo, ft: fts };
}
function parse_BIFF5Obj(blob, length, opts) {
blob.l += 4;
var ot = blob.read_shift(2);
var id = blob.read_shift(2);
var grbit = blob.read_shift(2);
blob.l += 2;
blob.l += 2;
blob.l += 2;
blob.l += 2;
blob.l += 2;
blob.l += 2;
blob.l += 2;
blob.l += 2;
blob.l += 2;
blob.l += 6;
length -= 36;
var fts = [];
fts.push((parse_BIFF5OT[ot] || parsenoop)(blob, length, opts));
return { cmo: [id, ot, grbit], ft: fts };
}
function parse_TxO(blob, length, opts) {
var s6 = blob.l;
var texts = "";
try {
blob.l += 4;
var ot = (opts.lastobj || { cmo: [0, 0] }).cmo[1];
var controlInfo;
if ([0, 5, 7, 11, 12, 14].indexOf(ot) == -1) blob.l += 6;
else controlInfo = parse_ControlInfo(blob, 6, opts);
var cchText = blob.read_shift(2);
blob.read_shift(2);
parseuint16(blob, 2);
var len = blob.read_shift(2);
blob.l += len;
for (var i7 = 1; i7 < blob.lens.length - 1; ++i7) {
if (blob.l - s6 != blob.lens[i7]) throw new Error("TxO: bad continue record");
var hdr = blob[blob.l];
var t6 = parse_XLUnicodeStringNoCch(blob, blob.lens[i7 + 1] - blob.lens[i7] - 1);
texts += t6;
if (texts.length >= (hdr ? cchText : 2 * cchText)) break;
}
if (texts.length !== cchText && texts.length !== cchText * 2) {
throw new Error("cchText: " + cchText + " != " + texts.length);
}
blob.l = s6 + length;
return { t: texts };
} catch (e9) {
blob.l = s6 + length;
return { t: texts };
}
}
function parse_HLink(blob, length) {
var ref = parse_Ref8U(blob, 8);
blob.l += 16;
var hlink = parse_Hyperlink(blob, length - 24);
return [ref, hlink];
}
function parse_HLinkTooltip(blob, length) {
blob.read_shift(2);
var ref = parse_Ref8U(blob, 8);
var wzTooltip = blob.read_shift((length - 10) / 2, "dbcs-cont");
wzTooltip = wzTooltip.replace(chr0, "");
return [ref, wzTooltip];
}
function parse_Country(blob) {
var o9 = [0, 0], d4;
d4 = blob.read_shift(2);
o9[0] = CountryEnum[d4] || d4;
d4 = blob.read_shift(2);
o9[1] = CountryEnum[d4] || d4;
return o9;
}
function parse_ClrtClient(blob) {
var ccv = blob.read_shift(2);
var o9 = [];
while (ccv-- > 0) o9.push(parse_LongRGB(blob, 8));
return o9;
}
function parse_Palette(blob) {
var ccv = blob.read_shift(2);
var o9 = [];
while (ccv-- > 0) o9.push(parse_LongRGB(blob, 8));
return o9;
}
function parse_XFCRC(blob) {
blob.l += 2;
var o9 = { cxfs: 0, crc: 0 };
o9.cxfs = blob.read_shift(2);
o9.crc = blob.read_shift(4);
return o9;
}
function parse_ColInfo(blob, length, opts) {
if (!opts.cellStyles) return parsenoop(blob, length);
var w3 = opts && opts.biff >= 12 ? 4 : 2;
var colFirst = blob.read_shift(w3);
var colLast = blob.read_shift(w3);
var coldx = blob.read_shift(w3);
var ixfe = blob.read_shift(w3);
var flags = blob.read_shift(2);
if (w3 == 2) blob.l += 2;
var o9 = { s: colFirst, e: colLast, w: coldx, ixfe, flags };
if (opts.biff >= 5 || !opts.biff) o9.level = flags >> 8 & 7;
return o9;
}
function parse_Setup(blob, length) {
var o9 = {};
if (length < 32) return o9;
blob.l += 16;
o9.header = parse_Xnum(blob, 8);
o9.footer = parse_Xnum(blob, 8);
blob.l += 2;
return o9;
}
function parse_ShtProps(blob, length, opts) {
var def = { area: false };
if (opts.biff != 5) {
blob.l += length;
return def;
}
var d4 = blob.read_shift(1);
blob.l += 3;
if (d4 & 16) def.area = true;
return def;
}
function parse_ImData(blob) {
var cf = blob.read_shift(2);
var env = blob.read_shift(2);
var lcb = blob.read_shift(4);
var o9 = { fmt: cf, env, len: lcb, data: blob.slice(blob.l, blob.l + lcb) };
blob.l += lcb;
return o9;
}
function parse_BIFF2STR(blob, length, opts) {
if (opts.biffguess && opts.biff == 5) opts.biff = 2;
var cell = parse_XLSCell(blob, 7, opts);
var str2 = parse_XLUnicodeString2(blob, length - 7, opts);
cell.t = "str";
cell.val = str2;
return cell;
}
function parse_BIFF2NUM(blob, length, opts) {
var cell = parse_XLSCell(blob, 7, opts);
var num = parse_Xnum(blob, 8);
cell.t = "n";
cell.val = num;
return cell;
}
function parse_BIFF2INT(blob, length, opts) {
var cell = parse_XLSCell(blob, 7, opts);
var num = blob.read_shift(2);
cell.t = "n";
cell.val = num;
return cell;
}
function parse_BIFF2STRING(blob) {
var cch = blob.read_shift(1);
if (cch === 0) {
blob.l++;
return "";
}
return blob.read_shift(cch, "sbcs-cont");
}
function parse_BIFF2BOOLERR(blob, length, opts) {
var bestart = blob.l + 7;
var cell = parse_XLSCell(blob, 6, opts);
blob.l = bestart;
var val2 = parse_Bes(blob, 2);
cell.val = val2;
cell.t = val2 === true || val2 === false ? "b" : "e";
return cell;
}
function parse_BIFF2FONTXTRA(blob, length) {
blob.l += 6;
blob.l += 2;
blob.l += 1;
blob.l += 3;
blob.l += 1;
blob.l += length - 13;
}
function parse_RString(blob, length, opts) {
var end = blob.l + length;
var cell = parse_XLSCell(blob, 6, opts);
var cch = blob.read_shift(2);
var str2 = parse_XLUnicodeStringNoCch(blob, cch, opts);
blob.l = end;
cell.t = "str";
cell.val = str2;
return cell;
}
function parse_BIFF4SheetInfo(blob) {
var flags = blob.read_shift(4);
var cch = blob.read_shift(1), name = blob.read_shift(cch, "sbcs");
if (name.length === 0) name = "Sheet1";
return { flags, name };
}
function read_wb_ID(d4, opts) {
var o9 = opts || {}, OLD_WTF = !!o9.WTF;
o9.WTF = true;
try {
var out = SYLK.to_workbook(d4, o9);
o9.WTF = OLD_WTF;
return out;
} catch (e9) {
o9.WTF = OLD_WTF;
if (e9.message.indexOf("SYLK bad record ID") == -1 && OLD_WTF) throw e9;
return PRN.to_workbook(d4, opts);
}
}
function parse_rpr(rpr) {
var font = {}, m4 = rpr.match(tagregex), i7 = 0;
var pass = false;
if (m4) for (; i7 != m4.length; ++i7) {
var y4 = parsexmltag(m4[i7]);
switch (y4[0].replace(/<\w*:/g, "<")) {
/* 18.8.12 condense CT_BooleanProperty */
/* ** not required . */
case "":
case " ":
font.shadow = 1;
break;
case "":
break;
/* 18.4.1 charset CT_IntProperty TODO */
case "":
case " ":
font.outline = 1;
break;
case "":
break;
/* 18.4.5 rFont CT_FontName */
case "":
case "":
font.strike = 1;
break;
case "":
break;
/* 18.4.13 u CT_UnderlineProperty */
case "":
case "":
font.u = 1;
break;
case "":
break;
/* 18.8.2 b */
case "":
case "":
font.b = 1;
break;
case "":
break;
/* 18.8.26 i */
case "":
case "":
font.i = 1;
break;
case "":
break;
/* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
case "":
case " ":
case " ":
break;
/* 18.8.18 family ST_FontFamily */
case "":
case " ":
case " ":
break;
/* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
case "":
case " ":
case " ":
break;
/* 18.8.35 scheme CT_FontScheme TODO */
case "":
case " ":
case " ":
break;
/* 18.2.10 extLst CT_ExtensionList ? */
case "":
case " ":
break;
case "":
pass = false;
break;
default:
if (y4[0].charCodeAt(1) !== 47 && !pass) throw new Error("Unrecognized rich format " + y4[0]);
}
}
return font;
}
function parse_si(x2, opts) {
var html = opts ? opts.cellHTML : true;
var z3 = {};
if (!x2) return { t: "" };
if (x2.match(/^\s*<(?:\w+:)?t[^>]*>/)) {
z3.t = unescapexml(utf8read(x2.slice(x2.indexOf(">") + 1).split(/<\/(?:\w+:)?t>/)[0] || ""), true);
z3.r = utf8read(x2);
if (html) z3.h = escapehtml(z3.t);
} else if (
/*y = */
x2.match(sirregex)
) {
z3.r = utf8read(x2);
z3.t = unescapexml(utf8read((str_remove_xml_ns_g(x2, "rPh").match(sitregex) || []).join("").replace(tagregex, "")), true);
if (html) z3.h = rs_to_html(parse_rs(z3.r));
}
return z3;
}
function parse_sst_xml(data, opts) {
var s6 = [], ss = "";
if (!data) return s6;
var sst = str_match_xml_ns(data, "sst");
if (sst) {
ss = sst[1].replace(sstr1, "").split(sstr2);
for (var i7 = 0; i7 != ss.length; ++i7) {
var o9 = parse_si(ss[i7].trim(), opts);
if (o9 != null) s6[s6.length] = o9;
}
sst = parsexmltag(sst[0].slice(0, sst[0].indexOf(">")));
s6.Count = sst.count;
s6.Unique = sst.uniqueCount;
}
return s6;
}
function parse_BrtBeginSst(data) {
return [data.read_shift(4), data.read_shift(4)];
}
function parse_sst_bin(data, opts) {
var s6 = [];
var pass = false;
recordhopper(data, function hopper_sst(val2, R3, RT) {
switch (RT) {
case 159:
s6.Count = val2[0];
s6.Unique = val2[1];
break;
case 19:
s6.push(val2);
break;
case 160:
return true;
case 35:
pass = true;
break;
case 36:
pass = false;
break;
default:
if (R3.T) {
}
if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
}
});
return s6;
}
function _JS2ANSI(str2) {
if (typeof $cptable !== "undefined") return $cptable.utils.encode(current_ansi, str2);
var o9 = [], oo = str2.split("");
for (var i7 = 0; i7 < oo.length; ++i7) o9[i7] = oo[i7].charCodeAt(0);
return o9;
}
function parse_CRYPTOVersion(blob, length) {
var o9 = {};
o9.Major = blob.read_shift(2);
o9.Minor = blob.read_shift(2);
if (length >= 4) blob.l += length - 4;
return o9;
}
function parse_DataSpaceVersionInfo(blob) {
var o9 = {};
o9.id = blob.read_shift(0, "lpp4");
o9.R = parse_CRYPTOVersion(blob, 4);
o9.U = parse_CRYPTOVersion(blob, 4);
o9.W = parse_CRYPTOVersion(blob, 4);
return o9;
}
function parse_DataSpaceMapEntry(blob) {
var len = blob.read_shift(4);
var end = blob.l + len - 4;
var o9 = {};
var cnt = blob.read_shift(4);
var comps = [];
while (cnt-- > 0) comps.push({ t: blob.read_shift(4), v: blob.read_shift(0, "lpp4") });
o9.name = blob.read_shift(0, "lpp4");
o9.comps = comps;
if (blob.l != end) throw new Error("Bad DataSpaceMapEntry: " + blob.l + " != " + end);
return o9;
}
function parse_DataSpaceMap(blob) {
var o9 = [];
blob.l += 4;
var cnt = blob.read_shift(4);
while (cnt-- > 0) o9.push(parse_DataSpaceMapEntry(blob));
return o9;
}
function parse_DataSpaceDefinition(blob) {
var o9 = [];
blob.l += 4;
var cnt = blob.read_shift(4);
while (cnt-- > 0) o9.push(blob.read_shift(0, "lpp4"));
return o9;
}
function parse_TransformInfoHeader(blob) {
var o9 = {};
blob.read_shift(4);
blob.l += 4;
o9.id = blob.read_shift(0, "lpp4");
o9.name = blob.read_shift(0, "lpp4");
o9.R = parse_CRYPTOVersion(blob, 4);
o9.U = parse_CRYPTOVersion(blob, 4);
o9.W = parse_CRYPTOVersion(blob, 4);
return o9;
}
function parse_Primary(blob) {
var hdr = parse_TransformInfoHeader(blob);
hdr.ename = blob.read_shift(0, "8lpp4");
hdr.blksz = blob.read_shift(4);
hdr.cmode = blob.read_shift(4);
if (blob.read_shift(4) != 4) throw new Error("Bad !Primary record");
return hdr;
}
function parse_EncryptionHeader(blob, length) {
var tgt = blob.l + length;
var o9 = {};
o9.Flags = blob.read_shift(4) & 63;
blob.l += 4;
o9.AlgID = blob.read_shift(4);
var valid = false;
switch (o9.AlgID) {
case 26126:
case 26127:
case 26128:
valid = o9.Flags == 36;
break;
case 26625:
valid = o9.Flags == 4;
break;
case 0:
valid = o9.Flags == 16 || o9.Flags == 4 || o9.Flags == 36;
break;
default:
throw "Unrecognized encryption algorithm: " + o9.AlgID;
}
if (!valid) throw new Error("Encryption Flags/AlgID mismatch");
o9.AlgIDHash = blob.read_shift(4);
o9.KeySize = blob.read_shift(4);
o9.ProviderType = blob.read_shift(4);
blob.l += 8;
o9.CSPName = blob.read_shift(tgt - blob.l >> 1, "utf16le");
blob.l = tgt;
return o9;
}
function parse_EncryptionVerifier(blob, length) {
var o9 = {}, tgt = blob.l + length;
blob.l += 4;
o9.Salt = blob.slice(blob.l, blob.l + 16);
blob.l += 16;
o9.Verifier = blob.slice(blob.l, blob.l + 16);
blob.l += 16;
blob.read_shift(4);
o9.VerifierHash = blob.slice(blob.l, tgt);
blob.l = tgt;
return o9;
}
function parse_EncryptionInfo(blob) {
var vers = parse_CRYPTOVersion(blob);
switch (vers.Minor) {
case 2:
return [vers.Minor, parse_EncInfoStd(blob, vers)];
case 3:
return [vers.Minor, parse_EncInfoExt(blob, vers)];
case 4:
return [vers.Minor, parse_EncInfoAgl(blob, vers)];
}
throw new Error("ECMA-376 Encrypted file unrecognized Version: " + vers.Minor);
}
function parse_EncInfoStd(blob) {
var flags = blob.read_shift(4);
if ((flags & 63) != 36) throw new Error("EncryptionInfo mismatch");
var sz = blob.read_shift(4);
var hdr = parse_EncryptionHeader(blob, sz);
var verifier = parse_EncryptionVerifier(blob, blob.length - blob.l);
return { t: "Std", h: hdr, v: verifier };
}
function parse_EncInfoExt() {
throw new Error("File is password-protected: ECMA-376 Extensible");
}
function parse_EncInfoAgl(blob) {
var KeyData = ["saltSize", "blockSize", "keyBits", "hashSize", "cipherAlgorithm", "cipherChaining", "hashAlgorithm", "saltValue"];
blob.l += 4;
var xml2 = blob.read_shift(blob.length - blob.l, "utf8");
var o9 = {};
xml2.replace(tagregex, function xml_agile(x2) {
var y4 = parsexmltag(x2);
switch (strip_ns(y4[0])) {
case "":
break;
case "":
case "":
break;
case "":
break;
case " 4 || vers.Major < 2) throw new Error("unrecognized major version code: " + vers.Major);
o9.Flags = blob.read_shift(4);
length -= 4;
var sz = blob.read_shift(4);
length -= 4;
o9.EncryptionHeader = parse_EncryptionHeader(blob, sz);
length -= sz;
o9.EncryptionVerifier = parse_EncryptionVerifier(blob, length);
return o9;
}
function parse_RC4Header(blob) {
var o9 = {};
var vers = o9.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4);
if (vers.Major != 1 || vers.Minor != 1) throw "unrecognized version code " + vers.Major + " : " + vers.Minor;
o9.Salt = blob.read_shift(16);
o9.EncryptedVerifier = blob.read_shift(16);
o9.EncryptedVerifierHash = blob.read_shift(16);
return o9;
}
function crypto_CreatePasswordVerifier_Method1(Password) {
var Verifier = 0, PasswordArray;
var PasswordDecoded = _JS2ANSI(Password);
var len = PasswordDecoded.length + 1, i7, PasswordByte;
var Intermediate1, Intermediate2, Intermediate3;
PasswordArray = new_raw_buf(len);
PasswordArray[0] = PasswordDecoded.length;
for (i7 = 1; i7 != len; ++i7) PasswordArray[i7] = PasswordDecoded[i7 - 1];
for (i7 = len - 1; i7 >= 0; --i7) {
PasswordByte = PasswordArray[i7];
Intermediate1 = (Verifier & 16384) === 0 ? 0 : 1;
Intermediate2 = Verifier << 1 & 32767;
Intermediate3 = Intermediate1 | Intermediate2;
Verifier = Intermediate3 ^ PasswordByte;
}
return Verifier ^ 52811;
}
function parse_XORObfuscation(blob, length, opts, out) {
var o9 = { key: parseuint16(blob), verificationBytes: parseuint16(blob) };
if (opts.password) o9.verifier = crypto_CreatePasswordVerifier_Method1(opts.password);
out.valid = o9.verificationBytes === o9.verifier;
if (out.valid) out.insitu = crypto_MakeXorDecryptor(opts.password);
return o9;
}
function parse_FilePassHeader(blob, length, oo) {
var o9 = oo || {};
o9.Info = blob.read_shift(2);
blob.l -= 2;
if (o9.Info === 1) o9.Data = parse_RC4Header(blob, length);
else o9.Data = parse_RC4CryptoHeader(blob, length);
return o9;
}
function parse_FilePass(blob, length, opts) {
var o9 = { Type: opts.biff >= 8 ? blob.read_shift(2) : 0 };
if (o9.Type) parse_FilePassHeader(blob, length - 2, o9);
else parse_XORObfuscation(blob, opts.biff >= 8 ? length : length - 2, opts, o9);
return o9;
}
function rtf_to_sheet(d4, opts) {
switch (opts.type) {
case "base64":
return rtf_to_sheet_str(Base64_decode(d4), opts);
case "binary":
return rtf_to_sheet_str(d4, opts);
case "buffer":
return rtf_to_sheet_str(has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4), opts);
case "array":
return rtf_to_sheet_str(cc2str(d4), opts);
}
throw new Error("Unrecognized type " + opts.type);
}
function rtf_to_sheet_str(str2, opts) {
var o9 = opts || {};
var ws = {};
var dense = o9.dense;
if (dense)
ws["!data"] = [];
var rows = str_match_ng(str2, "\\trowd", "\\row");
if (!rows)
throw new Error("RTF missing table");
var range2 = { s: { c: 0, r: 0 }, e: { c: 0, r: rows.length - 1 } };
var row = [];
rows.forEach(function(rowtf, R3) {
if (dense)
row = ws["!data"][R3] = [];
var rtfre = /\\[\w\-]+\b/g;
var last_index = 0;
var res;
var C3 = -1;
var payload = [];
while ((res = rtfre.exec(rowtf)) != null) {
var data = rowtf.slice(last_index, rtfre.lastIndex - res[0].length);
if (data.charCodeAt(0) == 32)
data = data.slice(1);
if (data.length)
payload.push(data);
switch (res[0]) {
case "\\cell":
++C3;
if (payload.length) {
var cell = { v: payload.join(""), t: "s" };
if (cell.v == "TRUE" || cell.v == "FALSE") {
cell.v = cell.v == "TRUE";
cell.t = "b";
} else if (!isNaN(fuzzynum(cell.v))) {
cell.t = "n";
if (o9.cellText !== false)
cell.w = cell.v;
cell.v = fuzzynum(cell.v);
} else if (RBErr[cell.v] != null) {
cell.t = "e";
cell.w = cell.v;
cell.v = RBErr[cell.v];
}
if (dense)
row[C3] = cell;
else
ws[encode_cell({ r: R3, c: C3 })] = cell;
}
payload = [];
break;
case "\\par":
payload.push("\n");
break;
}
last_index = rtfre.lastIndex;
}
if (C3 > range2.e.c)
range2.e.c = C3;
});
ws["!ref"] = encode_range(range2);
return ws;
}
function rtf_to_workbook(d4, opts) {
var wb = sheet_to_workbook(rtf_to_sheet(d4, opts), opts);
wb.bookType = "rtf";
return wb;
}
function hex2RGB(h7) {
var o9 = h7.slice(h7[0] === "#" ? 1 : 0).slice(0, 6);
return [parseInt(o9.slice(0, 2), 16), parseInt(o9.slice(2, 4), 16), parseInt(o9.slice(4, 6), 16)];
}
function rgb2Hex(rgb) {
for (var i7 = 0, o9 = 1; i7 != 3; ++i7) o9 = o9 * 256 + (rgb[i7] > 255 ? 255 : rgb[i7] < 0 ? 0 : rgb[i7]);
return o9.toString(16).toUpperCase().slice(1);
}
function rgb2HSL(rgb) {
var R3 = rgb[0] / 255, G2 = rgb[1] / 255, B3 = rgb[2] / 255;
var M4 = Math.max(R3, G2, B3), m4 = Math.min(R3, G2, B3), C3 = M4 - m4;
if (C3 === 0) return [0, 0, R3];
var H6 = 0, S5 = 0, L22 = M4 + m4;
S5 = C3 / (L22 > 1 ? 2 - L22 : L22);
switch (M4) {
case R3:
H6 = ((G2 - B3) / C3 + 6) % 6;
break;
case G2:
H6 = (B3 - R3) / C3 + 2;
break;
case B3:
H6 = (R3 - G2) / C3 + 4;
break;
}
return [H6 / 6, S5, L22 / 2];
}
function hsl2RGB(hsl) {
var H2 = hsl[0], S5 = hsl[1], L3 = hsl[2];
var C3 = S5 * 2 * (L3 < 0.5 ? L3 : 1 - L3), m4 = L3 - C3 / 2;
var rgb = [m4, m4, m4], h62 = 6 * H2;
var X4;
if (S5 !== 0) switch (h62 | 0) {
case 0:
case 6:
X4 = C3 * h62;
rgb[0] += C3;
rgb[1] += X4;
break;
case 1:
X4 = C3 * (2 - h62);
rgb[0] += X4;
rgb[1] += C3;
break;
case 2:
X4 = C3 * (h62 - 2);
rgb[1] += C3;
rgb[2] += X4;
break;
case 3:
X4 = C3 * (4 - h62);
rgb[1] += X4;
rgb[2] += C3;
break;
case 4:
X4 = C3 * (h62 - 4);
rgb[2] += C3;
rgb[0] += X4;
break;
case 5:
X4 = C3 * (6 - h62);
rgb[2] += X4;
rgb[0] += C3;
break;
}
for (var i7 = 0; i7 != 3; ++i7) rgb[i7] = Math.round(rgb[i7] * 255);
return rgb;
}
function rgb_tint(hex2, tint) {
if (tint === 0) return hex2;
var hsl = rgb2HSL(hex2RGB(hex2));
if (tint < 0) hsl[2] = hsl[2] * (1 + tint);
else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint);
return rgb2Hex(hsl2RGB(hsl));
}
function width2px(width) {
return Math.floor((width + Math.round(128 / MDW) / 256) * MDW);
}
function px2char(px) {
return Math.floor((px - 5) / MDW * 100 + 0.5) / 100;
}
function char2width(chr) {
return Math.round((chr * MDW + 5) / MDW * 256) / 256;
}
function cycle_width(collw) {
return char2width(px2char(width2px(collw)));
}
function find_mdw_colw(collw) {
var delta = Math.abs(collw - cycle_width(collw)), _MDW = MDW;
if (delta > 5e-3) {
for (MDW = MIN_MDW; MDW < MAX_MDW; ++MDW) if (Math.abs(collw - cycle_width(collw)) <= delta) {
delta = Math.abs(collw - cycle_width(collw));
_MDW = MDW;
}
}
MDW = _MDW;
}
function process_col(coll) {
if (coll.width) {
coll.wpx = width2px(coll.width);
coll.wch = px2char(coll.wpx);
coll.MDW = MDW;
} else if (coll.wpx) {
coll.wch = px2char(coll.wpx);
coll.width = char2width(coll.wch);
coll.MDW = MDW;
} else if (typeof coll.wch == "number") {
coll.width = char2width(coll.wch);
coll.wpx = width2px(coll.width);
coll.MDW = MDW;
}
if (coll.customWidth) delete coll.customWidth;
}
function px2pt(px) {
return px * 96 / PPI;
}
function pt2px(pt) {
return pt * PPI / 96;
}
function parse_borders(t6, styles2, themes, opts) {
styles2.Borders = [];
var border = {};
var pass = false;
(t6.match(tagregex) || []).forEach(function(x2) {
var y4 = parsexmltag(x2);
switch (strip_ns(y4[0])) {
case "":
case " ":
break;
/* 18.8.4 border CT_Border */
case "":
case " ":
border = /*::(*/
{};
if (y4.diagonalUp) border.diagonalUp = parsexmlbool(y4.diagonalUp);
if (y4.diagonalDown) border.diagonalDown = parsexmlbool(y4.diagonalDown);
styles2.Borders.push(border);
break;
case " ":
break;
/* note: not in spec, appears to be CT_BorderPr */
case " ":
break;
case "":
break;
case " ":
break;
/* note: not in spec, appears to be CT_BorderPr */
case " ":
break;
case "":
break;
case " ":
break;
/* 18.8.43 top CT_BorderPr */
case " ":
break;
case "":
break;
case " ":
break;
/* 18.8.6 bottom CT_BorderPr */
case " ":
break;
case "":
break;
case " ":
break;
/* 18.8.13 diagonal CT_BorderPr */
case "":
case " ":
break;
case " ":
break;
/* 18.8.25 horizontal CT_BorderPr */
case "":
case " ":
break;
case " ":
break;
/* 18.8.44 vertical CT_BorderPr */
case "":
case " ":
break;
case " ":
break;
/* 18.8.37 start CT_BorderPr */
case "":
case " ":
break;
case " ":
break;
/* 18.8.16 end CT_BorderPr */
case "":
case " ":
break;
case " ":
break;
/* 18.8.? color CT_Color */
case "":
break;
case " ":
case " ":
break;
/* 18.2.10 extLst CT_ExtensionList ? */
case "":
case " ":
break;
case "":
pass = false;
break;
default:
if (opts && opts.WTF) {
if (!pass) throw new Error("unrecognized " + y4[0] + " in borders");
}
}
});
}
function parse_fills(t6, styles2, themes, opts) {
styles2.Fills = [];
var fill3 = {};
var pass = false;
(t6.match(tagregex) || []).forEach(function(x2) {
var y4 = parsexmltag(x2);
switch (strip_ns(y4[0])) {
case "":
case " ":
break;
/* 18.8.20 fill CT_Fill */
case "":
case " ":
fill3 = {};
styles2.Fills.push(fill3);
break;
case " ":
break;
/* 18.8.24 gradientFill CT_GradientFill */
case "":
break;
case "":
styles2.Fills.push(fill3);
fill3 = {};
break;
/* 18.8.32 patternFill CT_PatternFill */
case "":
if (y4.patternType) fill3.patternType = y4.patternType;
break;
case " ":
case " ":
break;
/* 18.8.3 bgColor CT_Color */
case " ":
case "":
break;
/* 18.8.19 fgColor CT_Color */
case " ":
case "":
break;
/* 18.8.38 stop CT_GradientStop */
case " ":
break;
case "":
break;
/* 18.8.? color CT_Color */
case " ":
break;
case "":
break;
/* 18.2.10 extLst CT_ExtensionList ? */
case "":
case " ":
break;
case "":
pass = false;
break;
default:
if (opts && opts.WTF) {
if (!pass) throw new Error("unrecognized " + y4[0] + " in fills");
}
}
});
}
function parse_fonts(t6, styles2, themes, opts) {
styles2.Fonts = [];
var font = {};
var pass = false;
(t6.match(tagregex) || []).forEach(function(x2) {
var y4 = parsexmltag(x2);
switch (strip_ns(y4[0])) {
case "":
case " ":
break;
/* 18.8.22 font CT_Font */
case "":
break;
case "":
case "":
styles2.Fonts.push(font);
font = {};
break;
/* 18.8.29 name CT_FontName */
case " ":
case "":
break;
/* 18.8.2 b CT_BooleanProperty */
case "":
font.bold = 1;
break;
case "":
case "":
font.italic = 1;
break;
case "":
case "":
font.underline = 1;
break;
case "":
case "":
font.strike = 1;
break;
case "":
case "":
font.outline = 1;
break;
case "":
case "":
font.shadow = 1;
break;
case "":
case "":
font.condense = 1;
break;
case " ":
case "":
font.extend = 1;
break;
case "":
case "":
case "":
case "":
case "":
case "":
case "":
case "":
case "":
case "":
case "":
case "":
case "":
case "":
case "":
case "":
break;
case "":
pass = false;
break;
default:
if (opts && opts.WTF) {
if (!pass) throw new Error("unrecognized " + y4[0] + " in fonts");
}
}
});
}
function parse_numFmts(t6, styles2, opts) {
styles2.NumberFmt = [];
var k2 = keys(table_fmt);
for (var i7 = 0; i7 < k2.length; ++i7) styles2.NumberFmt[k2[i7]] = table_fmt[k2[i7]];
var m4 = t6.match(tagregex);
if (!m4) return;
for (i7 = 0; i7 < m4.length; ++i7) {
var y4 = parsexmltag(m4[i7]);
switch (strip_ns(y4[0])) {
case "":
case " ":
case "":
break;
case " 0) {
if (j3 > 392) {
for (j3 = 392; j3 > 60; --j3) if (styles2.NumberFmt[j3] == null) break;
styles2.NumberFmt[j3] = f4;
}
SSF__load(f4, j3);
}
}
break;
case " ":
break;
default:
if (opts.WTF) throw new Error("unrecognized " + y4[0] + " in numFmts");
}
}
}
function parse_cellXfs(t6, styles2, opts) {
styles2.CellXf = [];
var xf;
var pass = false;
(t6.match(tagregex) || []).forEach(function(x2) {
var y4 = parsexmltag(x2), i7 = 0;
switch (strip_ns(y4[0])) {
case "":
case " ":
case " ":
break;
/* 18.8.45 xf CT_Xf */
case " ":
case "":
xf = y4;
delete xf[0];
for (i7 = 0; i7 < cellXF_uint.length; ++i7) if (xf[cellXF_uint[i7]])
xf[cellXF_uint[i7]] = parseInt(xf[cellXF_uint[i7]], 10);
for (i7 = 0; i7 < cellXF_bool.length; ++i7) if (xf[cellXF_bool[i7]])
xf[cellXF_bool[i7]] = parsexmlbool(xf[cellXF_bool[i7]]);
if (styles2.NumberFmt && xf.numFmtId > 392) {
for (i7 = 392; i7 > 60; --i7) if (styles2.NumberFmt[xf.numFmtId] == styles2.NumberFmt[i7]) {
xf.numFmtId = i7;
break;
}
}
styles2.CellXf.push(xf);
break;
case " ":
break;
/* 18.8.1 alignment CT_CellAlignment */
case " ":
case "":
var alignment = {};
if (y4.vertical) alignment.vertical = y4.vertical;
if (y4.horizontal) alignment.horizontal = y4.horizontal;
if (y4.textRotation != null) alignment.textRotation = y4.textRotation;
if (y4.indent) alignment.indent = y4.indent;
if (y4.wrapText) alignment.wrapText = parsexmlbool(y4.wrapText);
xf.alignment = alignment;
break;
case " ":
break;
/* 18.8.33 protection CT_CellProtection */
case "":
break;
case " ":
case " ":
break;
/* note: sometimes mc:AlternateContent appears bare */
case "":
pass = true;
break;
case " ":
pass = false;
break;
/* 18.2.10 extLst CT_ExtensionList ? */
case "":
case " ":
break;
case "":
pass = false;
break;
default:
if (opts && opts.WTF) {
if (!pass) throw new Error("unrecognized " + y4[0] + " in cellXfs");
}
}
});
}
function parse_BrtFmt(data, length) {
var numFmtId = data.read_shift(2);
var stFmtCode = parse_XLWideString(data, length - 2);
return [numFmtId, stFmtCode];
}
function parse_BrtFont(data, length, opts) {
var out = {};
out.sz = data.read_shift(2) / 20;
var grbit = parse_FontFlags(data, 2, opts);
if (grbit.fItalic) out.italic = 1;
if (grbit.fCondense) out.condense = 1;
if (grbit.fExtend) out.extend = 1;
if (grbit.fShadow) out.shadow = 1;
if (grbit.fOutline) out.outline = 1;
if (grbit.fStrikeout) out.strike = 1;
var bls = data.read_shift(2);
if (bls === 700) out.bold = 1;
switch (data.read_shift(2)) {
/* case 0: out.vertAlign = "baseline"; break; */
case 1:
out.vertAlign = "superscript";
break;
case 2:
out.vertAlign = "subscript";
break;
}
var underline = data.read_shift(1);
if (underline != 0) out.underline = underline;
var family = data.read_shift(1);
if (family > 0) out.family = family;
var bCharSet = data.read_shift(1);
if (bCharSet > 0) out.charset = bCharSet;
data.l++;
out.color = parse_BrtColor(data, 8);
switch (data.read_shift(1)) {
/* case 0: out.scheme = "none": break; */
case 1:
out.scheme = "major";
break;
case 2:
out.scheme = "minor";
break;
}
out.name = parse_XLWideString(data, length - 21);
return out;
}
function parse_BrtXF(data, length) {
var tgt = data.l + length;
var ixfeParent = data.read_shift(2);
var ifmt = data.read_shift(2);
data.l = tgt;
return { ixfe: ixfeParent, numFmtId: ifmt };
}
function parse_sty_bin(data, themes, opts) {
var styles2 = {};
styles2.NumberFmt = [];
for (var y4 in table_fmt) styles2.NumberFmt[y4] = table_fmt[y4];
styles2.CellXf = [];
styles2.Fonts = [];
var state = [];
var pass = false;
recordhopper(data, function hopper_sty(val2, R3, RT) {
switch (RT) {
case 44:
styles2.NumberFmt[val2[0]] = val2[1];
SSF__load(val2[1], val2[0]);
break;
case 43:
styles2.Fonts.push(val2);
if (val2.color.theme != null && themes && themes.themeElements && themes.themeElements.clrScheme) {
val2.color.rgb = rgb_tint(themes.themeElements.clrScheme[val2.color.theme].rgb, val2.color.tint || 0);
}
break;
case 1025:
break;
case 45:
break;
case 46:
break;
case 47:
if (state[state.length - 1] == 617) {
styles2.CellXf.push(val2);
}
break;
case 48:
/* BrtStyle */
case 507:
/* BrtDXF */
case 572:
/* BrtMRUColor */
case 475:
break;
case 1171:
/* BrtDXF14 */
case 2102:
/* BrtDXF15 */
case 1130:
/* BrtSlicerStyleElement */
case 512:
/* BrtTableStyleElement */
case 2095:
/* BrtTimelineStyleElement */
case 3072:
break;
case 35:
pass = true;
break;
case 36:
pass = false;
break;
case 37:
state.push(RT);
pass = true;
break;
case 38:
state.pop();
pass = false;
break;
default:
if (R3.T > 0) state.push(RT);
else if (R3.T < 0) state.pop();
else if (!pass || opts.WTF && state[state.length - 1] != 37) throw new Error("Unexpected record 0x" + RT.toString(16));
}
});
return styles2;
}
function parse_clrScheme(t6, themes, opts) {
themes.themeElements.clrScheme = [];
var color2 = {};
(t6[0].match(tagregex) || []).forEach(function(x2) {
var y4 = parsexmltag(x2);
switch (y4[0]) {
/* 20.1.6.2 clrScheme (Color Scheme) CT_ColorScheme */
case "":
break;
/* 20.1.2.3.32 srgbClr CT_SRgbColor */
case "":
break;
/* 20.1.2.3.33 sysClr CT_SystemColor */
case "":
break;
/* 20.1.4.1.1 accent1 (Accent 1) */
/* 20.1.4.1.2 accent2 (Accent 2) */
/* 20.1.4.1.3 accent3 (Accent 3) */
/* 20.1.4.1.4 accent4 (Accent 4) */
/* 20.1.4.1.5 accent5 (Accent 5) */
/* 20.1.4.1.6 accent6 (Accent 6) */
/* 20.1.4.1.9 dk1 (Dark 1) */
/* 20.1.4.1.10 dk2 (Dark 2) */
/* 20.1.4.1.15 folHlink (Followed Hyperlink) */
/* 20.1.4.1.19 hlink (Hyperlink) */
/* 20.1.4.1.22 lt1 (Light 1) */
/* 20.1.4.1.23 lt2 (Light 2) */
case "":
case "":
case "":
case "":
case "":
case " ":
case "":
case " ":
case "":
case " ":
case "":
case " ":
case "":
case " ":
case "":
case " ":
case "":
case " ":
case "":
case " ":
case "":
case " ":
case "":
case " ":
if (y4[0].charAt(1) === "/") {
themes.themeElements.clrScheme[XLSXThemeClrScheme.indexOf(y4[0])] = color2;
color2 = {};
} else {
color2.name = y4[0].slice(3, y4[0].length - 1);
}
break;
default:
if (opts && opts.WTF) throw new Error("Unrecognized " + y4[0] + " in clrScheme");
}
});
}
function parse_fontScheme() {
}
function parse_fmtScheme() {
}
function parse_themeElements(data, themes, opts) {
themes.themeElements = {};
var t6;
if (!(t6 = str_match_xml(data, "a:clrScheme"))) throw new Error("clrScheme not found in themeElements");
parse_clrScheme(t6, themes, opts);
if (!(t6 = str_match_xml(data, "a:fontScheme"))) throw new Error("fontScheme not found in themeElements");
parse_fontScheme(t6, themes, opts);
if (!(t6 = str_match_xml(data, "a:fmtScheme"))) throw new Error("fmtScheme not found in themeElements");
parse_fmtScheme(t6, themes, opts);
}
function parse_theme_xml(data, opts) {
if (!data || data.length === 0) data = write_theme();
var t6;
var themes = {};
if (!(t6 = str_match_xml(data, "a:themeElements"))) throw new Error("themeElements not found in theme");
parse_themeElements(t6[0], themes, opts);
themes.raw = data;
return themes;
}
function write_theme(Themes, opts) {
if (opts && opts.themeXLSX) return opts.themeXLSX;
if (Themes && typeof Themes.raw == "string") return Themes.raw;
var o9 = [XML_HEADER];
o9[o9.length] = '';
o9[o9.length] = "";
o9[o9.length] = '';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = '';
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = " ";
o9[o9.length] = '';
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = '';
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = '';
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = " ";
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = "";
o9[o9.length] = "";
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = " ";
o9[o9.length] = "";
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = " ";
o9[o9.length] = "";
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = " ";
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = '';
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = '';
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = " ";
o9[o9.length] = " ";
o9[o9.length] = " ";
o9[o9.length] = "";
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = "";
o9[o9.length] = ' ';
o9[o9.length] = " ";
o9[o9.length] = " ";
o9[o9.length] = " ";
o9[o9.length] = " ";
return o9.join("");
}
function parse_Theme(blob, length, opts) {
var end = blob.l + length;
var dwThemeVersion = blob.read_shift(4);
if (dwThemeVersion === 124226) return;
if (!opts.cellStyles) {
blob.l = end;
return;
}
var data = blob.slice(blob.l);
blob.l = end;
var zip;
try {
zip = zip_read(data, { type: "array" });
} catch (e9) {
return;
}
var themeXML = getzipstr(zip, "theme/theme/theme1.xml", true);
if (!themeXML) return;
return parse_theme_xml(themeXML, opts);
}
function parse_ColorTheme(blob) {
return blob.read_shift(4);
}
function parse_FullColorExt(blob) {
var o9 = {};
o9.xclrType = blob.read_shift(2);
o9.nTintShade = blob.read_shift(2);
switch (o9.xclrType) {
case 0:
blob.l += 4;
break;
case 1:
o9.xclrValue = parse_IcvXF(blob, 4);
break;
case 2:
o9.xclrValue = parse_LongRGBA(blob, 4);
break;
case 3:
o9.xclrValue = parse_ColorTheme(blob, 4);
break;
case 4:
blob.l += 4;
break;
}
blob.l += 8;
return o9;
}
function parse_IcvXF(blob, length) {
return parsenoop(blob, length);
}
function parse_XFExtGradient(blob, length) {
return parsenoop(blob, length);
}
function parse_ExtProp(blob) {
var extType = blob.read_shift(2);
var cb = blob.read_shift(2) - 4;
var o9 = [extType];
switch (extType) {
case 4:
case 5:
case 7:
case 8:
case 9:
case 10:
case 11:
case 13:
o9[1] = parse_FullColorExt(blob, cb);
break;
case 6:
o9[1] = parse_XFExtGradient(blob, cb);
break;
case 14:
case 15:
o9[1] = blob.read_shift(cb === 1 ? 1 : 2);
break;
default:
throw new Error("Unrecognized ExtProp type: " + extType + " " + cb);
}
return o9;
}
function parse_XFExt(blob, length) {
var end = blob.l + length;
blob.l += 2;
var ixfe = blob.read_shift(2);
blob.l += 2;
var cexts = blob.read_shift(2);
var ext2 = [];
while (cexts-- > 0) ext2.push(parse_ExtProp(blob, end - blob.l));
return { ixfe, ext: ext2 };
}
function update_xfext(xf, xfext) {
xfext.forEach(function(xfe) {
switch (xfe[0]) {
/* 2.5.108 extPropData */
case 4:
break;
/* foreground color */
case 5:
break;
/* background color */
case 6:
break;
/* gradient fill */
case 7:
break;
/* top cell border color */
case 8:
break;
/* bottom cell border color */
case 9:
break;
/* left cell border color */
case 10:
break;
/* right cell border color */
case 11:
break;
/* diagonal cell border color */
case 13:
break;
case 14:
break;
/* font scheme */
case 15:
break;
}
});
}
function parse_BrtMdtinfo(data, length) {
return {
flags: data.read_shift(4),
version: data.read_shift(4),
name: parse_XLWideString(data, length - 8)
};
}
function parse_BrtMdb(data) {
var out = [];
var cnt = data.read_shift(4);
while (cnt-- > 0)
out.push([data.read_shift(4), data.read_shift(4)]);
return out;
}
function parse_BrtBeginEsmdb(data) {
data.l += 4;
return data.read_shift(4) != 0;
}
function parse_xlmeta_bin(data, name, _opts) {
var out = { Types: [], Cell: [], Value: [] };
var opts = _opts || {};
var state = [];
var pass = false;
var metatype = 2;
recordhopper(data, function(val2, R3, RT) {
switch (RT) {
case 335:
out.Types.push({ name: val2.name });
break;
case 51:
val2.forEach(function(r8) {
if (metatype == 1)
out.Cell.push({ type: out.Types[r8[0] - 1].name, index: r8[1] });
else if (metatype == 0)
out.Value.push({ type: out.Types[r8[0] - 1].name, index: r8[1] });
});
break;
case 337:
metatype = val2 ? 1 : 0;
break;
case 338:
metatype = 2;
break;
case 35:
state.push(RT);
pass = true;
break;
case 36:
state.pop();
pass = false;
break;
default:
if (R3.T) {
} else if (!pass || opts.WTF && state[state.length - 1] != 35)
throw new Error("Unexpected record 0x" + RT.toString(16));
}
});
return out;
}
function parse_xlmeta_xml(data, name, opts) {
var out = { Types: [], Cell: [], Value: [] };
if (!data)
return out;
var pass = false;
var metatype = 2;
var lastmeta;
data.replace(tagregex, function(x2) {
var y4 = parsexmltag(x2);
switch (strip_ns(y4[0])) {
case "":
break;
case "":
break;
case "":
break;
case "":
break;
case "":
break;
case " ":
break;
case "":
break;
case "":
metatype = 2;
break;
case "":
metatype = 2;
break;
case "":
case " ":
case " ":
break;
case "":
pass = false;
break;
case "":
case "":
break;
/* 18.6.1 c CT_CalcCell 1 */
case "]*r:id="([^<>"]*)"/) || ["", ""])[1];
return rels["!id"][id].Target;
}
function parse_vml(data, sheet, comments) {
var cidx = 0;
(str_match_xml_ns_g(data, "shape") || []).forEach(function(m4) {
var type = "";
var hidden = true;
var aidx = -1;
var R3 = -1, C3 = -1;
m4.replace(tagregex, function(x2, idx) {
var y4 = parsexmltag(x2);
switch (strip_ns(y4[0])) {
case " ":
hidden = false;
break;
case "":
aidx = idx + x2.length;
break;
case "
":
R3 = +m4.slice(aidx, idx).trim();
break;
case "":
aidx = idx + x2.length;
break;
case " ":
C3 = +m4.slice(aidx, idx).trim();
break;
}
return "";
});
switch (type) {
case "Note":
var cell = ws_get_cell_stub(sheet, R3 >= 0 && C3 >= 0 ? encode_cell({ r: R3, c: C3 }) : comments[cidx].ref);
if (cell.c) {
cell.c.hidden = hidden;
}
++cidx;
break;
}
});
}
function sheet_insert_comments(sheet, comments, threaded, people) {
var dense = sheet["!data"] != null;
var cell;
comments.forEach(function(comment) {
var r8 = decode_cell(comment.ref);
if (r8.r < 0 || r8.c < 0) return;
if (dense) {
if (!sheet["!data"][r8.r]) sheet["!data"][r8.r] = [];
cell = sheet["!data"][r8.r][r8.c];
} else cell = sheet[comment.ref];
if (!cell) {
cell = { t: "z" };
if (dense) sheet["!data"][r8.r][r8.c] = cell;
else sheet[comment.ref] = cell;
var range2 = safe_decode_range(sheet["!ref"] || "BDWGO1000001:A1");
if (range2.s.r > r8.r) range2.s.r = r8.r;
if (range2.e.r < r8.r) range2.e.r = r8.r;
if (range2.s.c > r8.c) range2.s.c = r8.c;
if (range2.e.c < r8.c) range2.e.c = r8.c;
var encoded = encode_range(range2);
sheet["!ref"] = encoded;
}
if (!cell.c) cell.c = [];
var o9 = { a: comment.author, t: comment.t, r: comment.r, T: threaded };
if (comment.h) o9.h = comment.h;
for (var i7 = cell.c.length - 1; i7 >= 0; --i7) {
if (!threaded && cell.c[i7].T) return;
if (threaded && !cell.c[i7].T) cell.c.splice(i7, 1);
}
if (threaded && people) for (i7 = 0; i7 < people.length; ++i7) {
if (o9.a == people[i7].id) {
o9.a = people[i7].name || o9.a;
break;
}
}
cell.c.push(o9);
});
}
function parse_comments_xml(data, opts) {
if (data.match(/<(?:\w+:)?comments *\/>/)) return [];
var authors = [];
var commentList = [];
var authtag = str_match_xml_ns(data, "authors");
if (authtag && authtag[1]) authtag[1].split(/<\/\w*:?author>/).forEach(function(x2) {
if (x2 === "" || x2.trim() === "") return;
var a3 = x2.match(/<(?:\w+:)?author[^<>]*>(.*)/);
if (a3) authors.push(a3[1]);
});
var cmnttag = str_match_xml_ns(data, "commentList");
if (cmnttag && cmnttag[1]) cmnttag[1].split(/<\/\w*:?comment>/).forEach(function(x2) {
if (x2 === "" || x2.trim() === "") return;
var cm = x2.match(/<(?:\w+:)?comment[^<>]*>/);
if (!cm) return;
var y4 = parsexmltag(cm[0]);
var comment = { author: y4.authorId && authors[y4.authorId] || "sheetjsghost", ref: y4.ref, guid: y4.guid };
var cell = decode_cell(y4.ref);
if (opts.sheetRows && opts.sheetRows <= cell.r) return;
var textMatch = str_match_xml_ns(x2, "text");
var rt = !!textMatch && !!textMatch[1] && parse_si(textMatch[1]) || { r: "", t: "", h: "" };
comment.r = rt.r;
if (rt.r == " ") rt.t = rt.h = "";
comment.t = (rt.t || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
if (opts.cellHTML) comment.h = rt.h;
commentList.push(comment);
});
return commentList;
}
function parse_tcmnt_xml(data, opts) {
var out = [];
var pass = false, comment = {}, tidx = 0;
data.replace(tagregex, function xml_tcmnt(x2, idx) {
var y4 = parsexmltag(x2);
switch (strip_ns(y4[0])) {
case "":
break;
/* 2.6.205 threadedComment CT_ThreadedComment */
case "":
if (comment.t != null) out.push(comment);
break;
case "":
case "":
comment.t = data.slice(tidx, idx).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
break;
/* 2.6.206 mentions CT_ThreadedCommentMentions TODO */
case "":
pass = true;
break;
case " ":
pass = false;
break;
/* 2.6.202 mention CT_Mention TODO */
/* 18.2.10 extLst CT_ExtensionList ? */
case "":
case " ":
case " ":
break;
/* 18.2.7 ext CT_Extension + */
case "":
pass = false;
break;
default:
if (!pass && opts.WTF) throw new Error("unrecognized " + y4[0] + " in threaded comments");
}
return x2;
});
return out;
}
function parse_people_xml(data, opts) {
var out = [];
var pass = false;
data.replace(tagregex, function xml_tcmnt(x2) {
var y4 = parsexmltag(x2);
switch (strip_ns(y4[0])) {
case "":
break;
/* 2.6.203 person CT_Person TODO: providers */
case "":
break;
/* 18.2.10 extLst CT_ExtensionList ? */
case "":
case " ":
case " ":
break;
/* 18.2.7 ext CT_Extension + */
case "":
pass = false;
break;
default:
if (!pass && opts.WTF) throw new Error("unrecognized " + y4[0] + " in threaded comments");
}
return x2;
});
return out;
}
function parse_BrtBeginComment(data) {
var out = {};
out.iauthor = data.read_shift(4);
var rfx = parse_UncheckedRfX(data, 16);
out.rfx = rfx.s;
out.ref = encode_cell(rfx.s);
data.l += 16;
return out;
}
function parse_comments_bin(data, opts) {
var out = [];
var authors = [];
var c6 = {};
var pass = false;
recordhopper(data, function hopper_cmnt(val2, R3, RT) {
switch (RT) {
case 632:
authors.push(val2);
break;
case 635:
c6 = val2;
break;
case 637:
c6.t = val2.t;
c6.h = val2.h;
c6.r = val2.r;
break;
case 636:
c6.author = authors[c6.iauthor];
delete c6.iauthor;
if (opts.sheetRows && c6.rfx && opts.sheetRows <= c6.rfx.r) break;
if (!c6.t) c6.t = "";
delete c6.rfx;
out.push(c6);
break;
case 3072:
break;
case 35:
pass = true;
break;
case 36:
pass = false;
break;
case 37:
break;
case 38:
break;
default:
if (R3.T) {
} else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
}
});
return out;
}
function make_vba_xls(cfb) {
var newcfb = CFB.utils.cfb_new({ root: "R" });
cfb.FullPaths.forEach(function(p4, i7) {
if (p4.slice(-1) === "/" || !p4.match(/_VBA_PROJECT_CUR/))
return;
var newpath = p4.replace(/^[^\/]*/, "R").replace(/\/_VBA_PROJECT_CUR\u0000*/, "");
CFB.utils.cfb_add(newcfb, newpath, cfb.FileIndex[i7].content);
});
return CFB.write(newcfb);
}
function parse_ds_bin() {
return { "!type": "dialog" };
}
function parse_ds_xml() {
return { "!type": "dialog" };
}
function parse_ms_bin() {
return { "!type": "macro" };
}
function parse_ms_xml() {
return { "!type": "macro" };
}
function shift_formula_str(f4, delta) {
return f4.replace(crefregex, function($0, $1, $22, $32, $4, $5) {
return $1 + ($22 == "$" ? $22 + $32 : encode_col(decode_col($32) + delta.c)) + ($4 == "$" ? $4 + $5 : encode_row(decode_row($5) + delta.r));
});
}
function shift_formula_xlsx(f4, range2, cell) {
var r8 = decode_range(range2), s6 = r8.s, c6 = decode_cell(cell);
var delta = { r: c6.r - s6.r, c: c6.c - s6.c };
return shift_formula_str(f4, delta);
}
function fuzzyfmla(f4) {
if (f4.length == 1) return false;
return true;
}
function _xlfn(f4) {
return f4.replace(/_xlfn\./g, "");
}
function parseread1(blob) {
blob.l += 1;
return;
}
function parse_ColRelU(blob, length) {
var c6 = blob.read_shift(length == 1 ? 1 : 2);
return [c6 & 16383, c6 >> 14 & 1, c6 >> 15 & 1];
}
function parse_RgceArea(blob, length, opts) {
var w3 = 2;
if (opts) {
if (opts.biff >= 2 && opts.biff <= 5) return parse_RgceArea_BIFF2(blob, length, opts);
else if (opts.biff == 12) w3 = 4;
}
var r8 = blob.read_shift(w3), R3 = blob.read_shift(w3);
var c6 = parse_ColRelU(blob, 2);
var C3 = parse_ColRelU(blob, 2);
return { s: { r: r8, c: c6[0], cRel: c6[1], rRel: c6[2] }, e: { r: R3, c: C3[0], cRel: C3[1], rRel: C3[2] } };
}
function parse_RgceArea_BIFF2(blob) {
var r8 = parse_ColRelU(blob, 2), R3 = parse_ColRelU(blob, 2);
var c6 = blob.read_shift(1);
var C3 = blob.read_shift(1);
return { s: { r: r8[0], c: c6, cRel: r8[1], rRel: r8[2] }, e: { r: R3[0], c: C3, cRel: R3[1], rRel: R3[2] } };
}
function parse_RgceAreaRel(blob, length, opts) {
if (opts.biff < 8) return parse_RgceArea_BIFF2(blob, length, opts);
var r8 = blob.read_shift(opts.biff == 12 ? 4 : 2), R3 = blob.read_shift(opts.biff == 12 ? 4 : 2);
var c6 = parse_ColRelU(blob, 2);
var C3 = parse_ColRelU(blob, 2);
return { s: { r: r8, c: c6[0], cRel: c6[1], rRel: c6[2] }, e: { r: R3, c: C3[0], cRel: C3[1], rRel: C3[2] } };
}
function parse_RgceLoc(blob, length, opts) {
if (opts && opts.biff >= 2 && opts.biff <= 5) return parse_RgceLoc_BIFF2(blob, length, opts);
var r8 = blob.read_shift(opts && opts.biff == 12 ? 4 : 2);
var c6 = parse_ColRelU(blob, 2);
return { r: r8, c: c6[0], cRel: c6[1], rRel: c6[2] };
}
function parse_RgceLoc_BIFF2(blob) {
var r8 = parse_ColRelU(blob, 2);
var c6 = blob.read_shift(1);
return { r: r8[0], c: c6, cRel: r8[1], rRel: r8[2] };
}
function parse_RgceElfLoc(blob) {
var r8 = blob.read_shift(2);
var c6 = blob.read_shift(2);
return { r: r8, c: c6 & 255, fQuoted: !!(c6 & 16384), cRel: c6 >> 15, rRel: c6 >> 15 };
}
function parse_RgceLocRel(blob, length, opts) {
var biff = opts && opts.biff ? opts.biff : 8;
if (biff >= 2 && biff <= 5) return parse_RgceLocRel_BIFF2(blob, length, opts);
var r8 = blob.read_shift(biff >= 12 ? 4 : 2);
var cl = blob.read_shift(2);
var cRel = (cl & 16384) >> 14, rRel = (cl & 32768) >> 15;
cl &= 16383;
if (rRel == 1) while (r8 > 524287) r8 -= 1048576;
if (cRel == 1) while (cl > 8191) cl = cl - 16384;
return { r: r8, c: cl, cRel, rRel };
}
function parse_RgceLocRel_BIFF2(blob) {
var rl = blob.read_shift(2);
var c6 = blob.read_shift(1);
var rRel = (rl & 32768) >> 15, cRel = (rl & 16384) >> 14;
rl &= 16383;
if (rRel == 1 && rl >= 8192) rl = rl - 16384;
if (cRel == 1 && c6 >= 128) c6 = c6 - 256;
return { r: rl, c: c6, cRel, rRel };
}
function parse_PtgArea(blob, length, opts) {
var type = (blob[blob.l++] & 96) >> 5;
var area = parse_RgceArea(blob, opts.biff >= 2 && opts.biff <= 5 ? 6 : 8, opts);
return [type, area];
}
function parse_PtgArea3d(blob, length, opts) {
var type = (blob[blob.l++] & 96) >> 5;
var ixti = blob.read_shift(2, "i");
var w3 = 8;
if (opts) switch (opts.biff) {
case 5:
blob.l += 12;
w3 = 6;
break;
case 12:
w3 = 12;
break;
}
var area = parse_RgceArea(blob, w3, opts);
return [type, ixti, area];
}
function parse_PtgAreaErr(blob, length, opts) {
var type = (blob[blob.l++] & 96) >> 5;
blob.l += opts && opts.biff > 8 ? 12 : opts.biff < 8 ? 6 : 8;
return [type];
}
function parse_PtgAreaErr3d(blob, length, opts) {
var type = (blob[blob.l++] & 96) >> 5;
var ixti = blob.read_shift(2);
var w3 = 8;
if (opts) switch (opts.biff) {
case 5:
blob.l += 12;
w3 = 6;
break;
case 12:
w3 = 12;
break;
}
blob.l += w3;
return [type, ixti];
}
function parse_PtgAreaN(blob, length, opts) {
var type = (blob[blob.l++] & 96) >> 5;
var area = parse_RgceAreaRel(blob, length - 1, opts);
return [type, area];
}
function parse_PtgArray(blob, length, opts) {
var type = (blob[blob.l++] & 96) >> 5;
blob.l += opts.biff == 2 ? 6 : opts.biff == 12 ? 14 : 7;
return [type];
}
function parse_PtgAttrBaxcel(blob) {
var bitSemi = blob[blob.l + 1] & 1;
var bitBaxcel = 1;
blob.l += 4;
return [bitSemi, bitBaxcel];
}
function parse_PtgAttrChoose(blob, length, opts) {
blob.l += 2;
var offset = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
var o9 = [];
for (var i7 = 0; i7 <= offset; ++i7) o9.push(blob.read_shift(opts && opts.biff == 2 ? 1 : 2));
return o9;
}
function parse_PtgAttrGoto(blob, length, opts) {
var bitGoto = blob[blob.l + 1] & 255 ? 1 : 0;
blob.l += 2;
return [bitGoto, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
}
function parse_PtgAttrIf(blob, length, opts) {
var bitIf = blob[blob.l + 1] & 255 ? 1 : 0;
blob.l += 2;
return [bitIf, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
}
function parse_PtgAttrIfError(blob) {
var bitIf = blob[blob.l + 1] & 255 ? 1 : 0;
blob.l += 2;
return [bitIf, blob.read_shift(2)];
}
function parse_PtgAttrSemi(blob, length, opts) {
var bitSemi = blob[blob.l + 1] & 255 ? 1 : 0;
blob.l += opts && opts.biff == 2 ? 3 : 4;
return [bitSemi];
}
function parse_PtgAttrSpaceType(blob) {
var type = blob.read_shift(1), cch = blob.read_shift(1);
return [type, cch];
}
function parse_PtgAttrSpace(blob) {
blob.read_shift(2);
return parse_PtgAttrSpaceType(blob, 2);
}
function parse_PtgAttrSpaceSemi(blob) {
blob.read_shift(2);
return parse_PtgAttrSpaceType(blob, 2);
}
function parse_PtgRef(blob, length, opts) {
var type = (blob[blob.l] & 96) >> 5;
blob.l += 1;
var loc = parse_RgceLoc(blob, 0, opts);
return [type, loc];
}
function parse_PtgRefN(blob, length, opts) {
var type = (blob[blob.l] & 96) >> 5;
blob.l += 1;
var loc = parse_RgceLocRel(blob, 0, opts);
return [type, loc];
}
function parse_PtgRef3d(blob, length, opts) {
var type = (blob[blob.l] & 96) >> 5;
blob.l += 1;
var ixti = blob.read_shift(2);
if (opts && opts.biff == 5) blob.l += 12;
var loc = parse_RgceLoc(blob, 0, opts);
return [type, ixti, loc];
}
function parse_PtgFunc(blob, length, opts) {
var type = (blob[blob.l] & 96) >> 5;
blob.l += 1;
var iftab = blob.read_shift(opts && opts.biff <= 3 ? 1 : 2);
return [FtabArgc[iftab], Ftab[iftab], type];
}
function parse_PtgFuncVar(blob, length, opts) {
var type = blob[blob.l++];
var cparams = blob.read_shift(1), tab = opts && opts.biff <= 3 ? [type == 88 ? -1 : 0, blob.read_shift(1)] : parsetab(blob);
return [cparams, (tab[0] === 0 ? Ftab : Cetab)[tab[1]]];
}
function parsetab(blob) {
return [blob[blob.l + 1] >> 7, blob.read_shift(2) & 32767];
}
function parse_PtgAttrSum(blob, length, opts) {
blob.l += opts && opts.biff == 2 ? 3 : 4;
return;
}
function parse_PtgExp(blob, length, opts) {
blob.l++;
if (opts && opts.biff == 12) return [blob.read_shift(4, "i"), 0];
var row = blob.read_shift(2);
var col = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
return [row, col];
}
function parse_PtgErr(blob) {
blob.l++;
return BErr[blob.read_shift(1)];
}
function parse_PtgInt(blob) {
blob.l++;
return blob.read_shift(2);
}
function parse_PtgBool(blob) {
blob.l++;
return blob.read_shift(1) !== 0;
}
function parse_PtgNum(blob) {
blob.l++;
return parse_Xnum(blob, 8);
}
function parse_PtgStr(blob, length, opts) {
blob.l++;
return parse_ShortXLUnicodeString(blob, length - 1, opts);
}
function parse_SerAr(blob, biff) {
var val2 = [blob.read_shift(1)];
if (biff == 12) switch (val2[0]) {
case 2:
val2[0] = 4;
break;
/* SerBool */
case 4:
val2[0] = 16;
break;
/* SerErr */
case 0:
val2[0] = 1;
break;
/* SerNum */
case 1:
val2[0] = 2;
break;
}
switch (val2[0]) {
case 4:
val2[1] = parsebool(blob, 1) ? "TRUE" : "FALSE";
if (biff != 12) blob.l += 7;
break;
case 37:
/* appears to be an alias */
case 16:
val2[1] = BErr[blob[blob.l]];
blob.l += biff == 12 ? 4 : 8;
break;
case 0:
blob.l += 8;
break;
case 1:
val2[1] = parse_Xnum(blob, 8);
break;
case 2:
val2[1] = parse_XLUnicodeString2(blob, 0, { biff: biff > 0 && biff < 8 ? 2 : biff });
break;
default:
throw new Error("Bad SerAr: " + val2[0]);
}
return val2;
}
function parse_PtgExtraMem(blob, cce, opts) {
var count = blob.read_shift(opts.biff == 12 ? 4 : 2);
var out = [];
for (var i7 = 0; i7 != count; ++i7) out.push((opts.biff == 12 ? parse_UncheckedRfX : parse_Ref8U)(blob, 8));
return out;
}
function parse_PtgExtraArray(blob, length, opts) {
var rows = 0, cols = 0;
if (opts.biff == 12) {
rows = blob.read_shift(4);
cols = blob.read_shift(4);
} else {
cols = 1 + blob.read_shift(1);
rows = 1 + blob.read_shift(2);
}
if (opts.biff >= 2 && opts.biff < 8) {
--rows;
if (--cols == 0) cols = 256;
}
for (var i7 = 0, o9 = []; i7 != rows && (o9[i7] = []); ++i7)
for (var j3 = 0; j3 != cols; ++j3) o9[i7][j3] = parse_SerAr(blob, opts.biff);
return o9;
}
function parse_PtgName(blob, length, opts) {
var type = blob.read_shift(1) >>> 5 & 3;
var w3 = !opts || opts.biff >= 8 ? 4 : 2;
var nameindex = blob.read_shift(w3);
switch (opts.biff) {
case 2:
blob.l += 5;
break;
case 3:
case 4:
blob.l += 8;
break;
case 5:
blob.l += 12;
break;
}
return [type, 0, nameindex];
}
function parse_PtgNameX(blob, length, opts) {
if (opts.biff == 5) return parse_PtgNameX_BIFF5(blob, length, opts);
var type = blob.read_shift(1) >>> 5 & 3;
var ixti = blob.read_shift(2);
var nameindex = blob.read_shift(4);
return [type, ixti, nameindex];
}
function parse_PtgNameX_BIFF5(blob) {
var type = blob.read_shift(1) >>> 5 & 3;
var ixti = blob.read_shift(2, "i");
blob.l += 8;
var nameindex = blob.read_shift(2);
blob.l += 12;
return [type, ixti, nameindex];
}
function parse_PtgMemArea(blob, length, opts) {
var type = blob.read_shift(1) >>> 5 & 3;
blob.l += opts && opts.biff == 2 ? 3 : 4;
var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
return [type, cce];
}
function parse_PtgMemFunc(blob, length, opts) {
var type = blob.read_shift(1) >>> 5 & 3;
var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
return [type, cce];
}
function parse_PtgRefErr(blob, length, opts) {
var type = blob.read_shift(1) >>> 5 & 3;
blob.l += 4;
if (opts.biff < 8) blob.l--;
if (opts.biff == 12) blob.l += 2;
return [type];
}
function parse_PtgRefErr3d(blob, length, opts) {
var type = (blob[blob.l++] & 96) >> 5;
var ixti = blob.read_shift(2);
var w3 = 4;
if (opts) switch (opts.biff) {
case 5:
w3 = 15;
break;
case 12:
w3 = 6;
break;
}
blob.l += w3;
return [type, ixti];
}
function parse_PtgElfLoc(blob, length, opts) {
blob.l += 2;
return [parse_RgceElfLoc(blob, 4, opts)];
}
function parse_PtgElfNoop(blob) {
blob.l += 6;
return [];
}
function parse_PtgElfLel(blob) {
blob.l += 2;
return [parseuint16(blob), blob.read_shift(2) & 1];
}
function parse_PtgList(blob) {
blob.l += 2;
var ixti = blob.read_shift(2);
var flags = blob.read_shift(2);
var idx = blob.read_shift(4);
var c6 = blob.read_shift(2);
var C3 = blob.read_shift(2);
var rt = PtgListRT[flags >> 2 & 31];
return { ixti, coltype: flags & 3, rt, idx, c: c6, C: C3 };
}
function parse_PtgSxName(blob) {
blob.l += 2;
return [blob.read_shift(4)];
}
function parse_PtgSheet(blob, length, opts) {
blob.l += 5;
blob.l += 2;
blob.l += opts.biff == 2 ? 1 : 4;
return ["PTGSHEET"];
}
function parse_PtgEndSheet(blob, length, opts) {
blob.l += opts.biff == 2 ? 4 : 5;
return ["PTGENDSHEET"];
}
function parse_PtgMemAreaN(blob) {
var type = blob.read_shift(1) >>> 5 & 3;
var cce = blob.read_shift(2);
return [type, cce];
}
function parse_PtgMemNoMemN(blob) {
var type = blob.read_shift(1) >>> 5 & 3;
var cce = blob.read_shift(2);
return [type, cce];
}
function parse_PtgAttrNoop(blob) {
blob.l += 4;
return [0, 0];
}
function parse_RgbExtra(blob, length, rgce, opts) {
if (opts.biff < 8) return parsenoop(blob, length);
var target = blob.l + length;
var o9 = [];
for (var i7 = 0; i7 !== rgce.length; ++i7) {
switch (rgce[i7][0]) {
case "PtgArray":
rgce[i7][1] = parse_PtgExtraArray(blob, 0, opts);
o9.push(rgce[i7][1]);
break;
case "PtgMemArea":
rgce[i7][2] = parse_PtgExtraMem(blob, rgce[i7][1], opts);
o9.push(rgce[i7][2]);
break;
case "PtgExp":
if (opts && opts.biff == 12) {
rgce[i7][1][1] = blob.read_shift(4);
o9.push(rgce[i7][1]);
}
break;
case "PtgList":
/* TODO: PtgList -> PtgExtraList */
case "PtgElfRadicalS":
/* TODO: PtgElfRadicalS -> PtgExtraElf */
case "PtgElfColS":
/* TODO: PtgElfColS -> PtgExtraElf */
case "PtgElfColSV":
throw "Unsupported " + rgce[i7][0];
default:
break;
}
}
length = target - blob.l;
if (length !== 0) o9.push(parsenoop(blob, length));
return o9;
}
function parse_Rgce(blob, length, opts) {
var target = blob.l + length;
var R3, id, ptgs = [];
while (target != blob.l) {
length = target - blob.l;
id = blob[blob.l];
R3 = PtgTypes[id] || PtgTypes[PtgDupes[id]];
if (id === 24 || id === 25) R3 = (id === 24 ? Ptg18 : Ptg19)[blob[blob.l + 1]];
if (!R3 || !R3.f) {
parsenoop(blob, length);
} else {
ptgs.push([R3.n, R3.f(blob, length, opts)]);
}
}
return ptgs;
}
function stringify_array(f4) {
var o9 = [];
for (var i7 = 0; i7 < f4.length; ++i7) {
var x2 = f4[i7], r8 = [];
for (var j3 = 0; j3 < x2.length; ++j3) {
var y4 = x2[j3];
if (y4) switch (y4[0]) {
// TODO: handle embedded quotes
case 2:
r8.push('"' + y4[1].replace(/"/g, '""') + '"');
break;
default:
r8.push(y4[1]);
}
else r8.push("");
}
o9.push(r8.join(","));
}
return o9.join(";");
}
function make_3d_range(start, end) {
var s6 = start.lastIndexOf("!"), e9 = end.lastIndexOf("!");
if (s6 == -1 && e9 == -1) return start + ":" + end;
if (s6 > 0 && e9 > 0 && start.slice(0, s6).toLowerCase() == end.slice(0, e9).toLowerCase()) return start + ":" + end.slice(e9 + 1);
console.error("Cannot hydrate range", start, end);
return start + ":" + end;
}
function get_ixti_raw(supbooks, ixti, opts) {
if (!supbooks) return "SH33TJSERR0";
if (opts.biff > 8 && (!supbooks.XTI || !supbooks.XTI[ixti])) return supbooks.SheetNames[ixti];
if (!supbooks.XTI) return "SH33TJSERR6";
var XTI = supbooks.XTI[ixti];
if (opts.biff < 8) {
if (ixti > 1e4) ixti -= 65536;
if (ixti < 0) ixti = -ixti;
return ixti == 0 ? "" : supbooks.XTI[ixti - 1];
}
if (!XTI) return "SH33TJSERR1";
var o9 = "";
if (opts.biff > 8) switch (supbooks[XTI[0]][0]) {
case 357:
o9 = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]];
return XTI[1] == XTI[2] ? o9 : o9 + ":" + supbooks.SheetNames[XTI[2]];
case 358:
if (opts.SID != null) return supbooks.SheetNames[opts.SID];
return "SH33TJSSAME" + supbooks[XTI[0]][0];
case 355:
/* 'BrtSupBookSrc' */
/* falls through */
default:
return "SH33TJSSRC" + supbooks[XTI[0]][0];
}
switch (supbooks[XTI[0]][0][0]) {
case 1025:
o9 = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]] || "SH33TJSERR3";
return XTI[1] == XTI[2] ? o9 : o9 + ":" + supbooks.SheetNames[XTI[2]];
case 14849:
return supbooks[XTI[0]].slice(1).map(function(name) {
return name.Name;
}).join(";;");
//return "SH33TJSERR8";
default:
if (!supbooks[XTI[0]][0][3]) return "SH33TJSERR2";
o9 = XTI[1] == -1 ? "#REF" : supbooks[XTI[0]][0][3][XTI[1]] || "SH33TJSERR4";
return XTI[1] == XTI[2] ? o9 : o9 + ":" + supbooks[XTI[0]][0][3][XTI[2]];
}
}
function get_ixti(supbooks, ixti, opts) {
var ixtiraw = get_ixti_raw(supbooks, ixti, opts);
return ixtiraw == "#REF" ? ixtiraw : formula_quote_sheet_name(ixtiraw, opts);
}
function stringify_formula(formula, range2, cell, supbooks, opts) {
var biff = opts && opts.biff || 8;
var _range = (
/*range != null ? range :*/
{ s: { c: 0, r: 0 }, e: { c: 0, r: 0 } }
);
var stack = [], e1, e22, c6, ixti = 0, nameidx = 0, r8, sname = "";
if (!formula[0] || !formula[0][0]) return "";
var last_sp = -1, sp = "";
for (var ff = 0, fflen = formula[0].length; ff < fflen; ++ff) {
var f4 = formula[0][ff];
switch (f4[0]) {
case "PtgUminus":
stack.push("-" + stack.pop());
break;
case "PtgUplus":
stack.push("+" + stack.pop());
break;
case "PtgPercent":
stack.push(stack.pop() + "%");
break;
case "PtgAdd":
/* [MS-XLS] 2.5.198.26 */
case "PtgConcat":
/* [MS-XLS] 2.5.198.43 */
case "PtgDiv":
/* [MS-XLS] 2.5.198.45 */
case "PtgEq":
/* [MS-XLS] 2.5.198.56 */
case "PtgGe":
/* [MS-XLS] 2.5.198.64 */
case "PtgGt":
/* [MS-XLS] 2.5.198.65 */
case "PtgLe":
/* [MS-XLS] 2.5.198.68 */
case "PtgLt":
/* [MS-XLS] 2.5.198.69 */
case "PtgMul":
/* [MS-XLS] 2.5.198.75 */
case "PtgNe":
/* [MS-XLS] 2.5.198.78 */
case "PtgPower":
/* [MS-XLS] 2.5.198.82 */
case "PtgSub":
e1 = stack.pop();
e22 = stack.pop();
if (last_sp >= 0) {
switch (formula[0][last_sp][1][0]) {
case 0:
sp = fill(" ", formula[0][last_sp][1][1]);
break;
case 1:
sp = fill("\r", formula[0][last_sp][1][1]);
break;
default:
sp = "";
if (opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
}
e22 = e22 + sp;
last_sp = -1;
}
stack.push(e22 + PtgBinOp[f4[0]] + e1);
break;
case "PtgIsect":
e1 = stack.pop();
e22 = stack.pop();
stack.push(e22 + " " + e1);
break;
case "PtgUnion":
e1 = stack.pop();
e22 = stack.pop();
stack.push(e22 + "," + e1);
break;
case "PtgRange":
e1 = stack.pop();
e22 = stack.pop();
stack.push(make_3d_range(e22, e1));
break;
case "PtgAttrChoose":
break;
case "PtgAttrGoto":
break;
case "PtgAttrIf":
break;
case "PtgAttrIfError":
break;
case "PtgRef":
c6 = shift_cell_xls(f4[1][1], _range, opts);
stack.push(encode_cell_xls(c6, biff));
break;
case "PtgRefN":
c6 = cell ? shift_cell_xls(f4[1][1], cell, opts) : f4[1][1];
stack.push(encode_cell_xls(c6, biff));
break;
case "PtgRef3d":
ixti = /*::Number(*/
f4[1][1];
c6 = shift_cell_xls(f4[1][2], _range, opts);
sname = get_ixti(supbooks, ixti, opts);
var w3 = sname;
stack.push(sname + "!" + encode_cell_xls(c6, biff));
break;
case "PtgFunc":
/* [MS-XLS] 2.5.198.62 */
case "PtgFuncVar":
var argc = f4[1][0], func = f4[1][1];
if (!argc) argc = 0;
argc &= 127;
var args = argc == 0 ? [] : stack.slice(-argc);
stack.length -= argc;
if (func === "User") func = args.shift();
stack.push(func + "(" + args.join(",") + ")");
break;
case "PtgBool":
stack.push(f4[1] ? "TRUE" : "FALSE");
break;
case "PtgInt":
stack.push(
/*::String(*/
f4[1]
/*::)*/
);
break;
case "PtgNum":
stack.push(String(f4[1]));
break;
case "PtgStr":
stack.push('"' + f4[1].replace(/"/g, '""') + '"');
break;
case "PtgErr":
stack.push(
/*::String(*/
f4[1]
/*::)*/
);
break;
case "PtgAreaN":
r8 = shift_range_xls(f4[1][1], cell ? { s: cell } : _range, opts);
stack.push(encode_range_xls(r8, opts));
break;
case "PtgArea":
r8 = shift_range_xls(f4[1][1], _range, opts);
stack.push(encode_range_xls(r8, opts));
break;
case "PtgArea3d":
ixti = /*::Number(*/
f4[1][1];
r8 = f4[1][2];
sname = get_ixti(supbooks, ixti, opts);
stack.push(sname + "!" + encode_range_xls(r8, opts));
break;
case "PtgAttrSum":
stack.push("SUM(" + stack.pop() + ")");
break;
case "PtgAttrBaxcel":
/* [MS-XLS] 2.5.198.33 */
case "PtgAttrSemi":
break;
case "PtgName":
nameidx = f4[1][2];
var lbl = (supbooks.names || [])[nameidx - 1] || (supbooks[0] || [])[nameidx];
var name = lbl ? lbl.Name : "SH33TJSNAME" + String(nameidx);
if (name && name.slice(0, 6) == "_xlfn." && !opts.xlfn) name = name.slice(6);
stack.push(name);
break;
case "PtgNameX":
var bookidx = f4[1][1];
nameidx = f4[1][2];
var externbook;
if (opts.biff <= 5) {
if (bookidx < 0) bookidx = -bookidx;
if (supbooks[bookidx]) externbook = supbooks[bookidx][nameidx];
} else {
var o9 = "";
if (((supbooks[bookidx] || [])[0] || [])[0] == 14849) {
} else if (((supbooks[bookidx] || [])[0] || [])[0] == 1025) {
if (supbooks[bookidx][nameidx] && supbooks[bookidx][nameidx].itab > 0) {
o9 = supbooks.SheetNames[supbooks[bookidx][nameidx].itab - 1] + "!";
}
} else o9 = supbooks.SheetNames[nameidx - 1] + "!";
if (supbooks[bookidx] && supbooks[bookidx][nameidx]) o9 += supbooks[bookidx][nameidx].Name;
else if (supbooks[0] && supbooks[0][nameidx]) o9 += supbooks[0][nameidx].Name;
else {
var ixtidata = (get_ixti_raw(supbooks, bookidx, opts) || "").split(";;");
if (ixtidata[nameidx - 1]) o9 = ixtidata[nameidx - 1];
else o9 += "SH33TJSERRX";
}
stack.push(o9);
break;
}
if (!externbook) externbook = { Name: "SH33TJSERRY" };
stack.push(externbook.Name);
break;
case "PtgParen":
var lp = "(", rp = ")";
if (last_sp >= 0) {
sp = "";
switch (formula[0][last_sp][1][0]) {
// $FlowIgnore
case 2:
lp = fill(" ", formula[0][last_sp][1][1]) + lp;
break;
// $FlowIgnore
case 3:
lp = fill("\r", formula[0][last_sp][1][1]) + lp;
break;
// $FlowIgnore
case 4:
rp = fill(" ", formula[0][last_sp][1][1]) + rp;
break;
// $FlowIgnore
case 5:
rp = fill("\r", formula[0][last_sp][1][1]) + rp;
break;
default:
if (opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
}
last_sp = -1;
}
stack.push(lp + stack.pop() + rp);
break;
case "PtgRefErr":
stack.push("#REF!");
break;
case "PtgRefErr3d":
stack.push("#REF!");
break;
case "PtgExp":
c6 = { c: f4[1][1], r: f4[1][0] };
var q2 = { c: cell.c, r: cell.r };
if (supbooks.sharedf[encode_cell(c6)]) {
var parsedf = supbooks.sharedf[encode_cell(c6)];
stack.push(stringify_formula(parsedf, _range, q2, supbooks, opts));
} else {
var fnd = false;
for (e1 = 0; e1 != supbooks.arrayf.length; ++e1) {
e22 = supbooks.arrayf[e1];
if (c6.c < e22[0].s.c || c6.c > e22[0].e.c) continue;
if (c6.r < e22[0].s.r || c6.r > e22[0].e.r) continue;
stack.push(stringify_formula(e22[1], _range, q2, supbooks, opts));
fnd = true;
break;
}
if (!fnd) stack.push(
/*::String(*/
f4[1]
/*::)*/
);
}
break;
case "PtgArray":
stack.push("{" + stringify_array(
/*::(*/
f4[1]
/*:: :any)*/
) + "}");
break;
case "PtgMemArea":
break;
case "PtgAttrSpace":
/* [MS-XLS] 2.5.198.38 */
case "PtgAttrSpaceSemi":
last_sp = ff;
break;
case "PtgTbl":
break;
case "PtgMemErr":
break;
case "PtgMissArg":
stack.push("");
break;
case "PtgAreaErr":
stack.push("#REF!");
break;
case "PtgAreaErr3d":
stack.push("#REF!");
break;
case "PtgList":
stack.push("Table" + f4[1].idx + "[#" + f4[1].rt + "]");
break;
case "PtgMemAreaN":
case "PtgMemNoMemN":
case "PtgAttrNoop":
case "PtgSheet":
case "PtgEndSheet":
break;
case "PtgMemFunc":
break;
case "PtgMemNoMem":
break;
case "PtgElfCol":
/* [MS-XLS] 2.5.198.46 */
case "PtgElfColS":
/* [MS-XLS] 2.5.198.47 */
case "PtgElfColSV":
/* [MS-XLS] 2.5.198.48 */
case "PtgElfColV":
/* [MS-XLS] 2.5.198.49 */
case "PtgElfLel":
/* [MS-XLS] 2.5.198.50 */
case "PtgElfRadical":
/* [MS-XLS] 2.5.198.51 */
case "PtgElfRadicalLel":
/* [MS-XLS] 2.5.198.52 */
case "PtgElfRadicalS":
/* [MS-XLS] 2.5.198.53 */
case "PtgElfRw":
/* [MS-XLS] 2.5.198.54 */
case "PtgElfRwV":
throw new Error("Unsupported ELFs");
case "PtgSxName":
throw new Error("Unrecognized Formula Token: " + String(f4));
default:
throw new Error("Unrecognized Formula Token: " + String(f4));
}
var PtgNonDisp = ["PtgAttrSpace", "PtgAttrSpaceSemi", "PtgAttrGoto"];
if (opts.biff != 3) {
if (last_sp >= 0 && PtgNonDisp.indexOf(formula[0][ff][0]) == -1) {
f4 = formula[0][last_sp];
var _left = true;
switch (f4[1][0]) {
/* note: some bad XLSB files omit the PtgParen */
case 4:
_left = false;
/* falls through */
case 0:
sp = fill(" ", f4[1][1]);
break;
case 5:
_left = false;
/* falls through */
case 1:
sp = fill("\r", f4[1][1]);
break;
default:
sp = "";
if (opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + f4[1][0]);
}
stack.push((_left ? sp : "") + stack.pop() + (_left ? "" : sp));
last_sp = -1;
}
}
}
if (stack.length > 1 && opts.WTF) throw new Error("bad formula stack");
if (stack[0] == "TRUE") return true;
if (stack[0] == "FALSE") return false;
return stack[0];
}
function parse_ArrayParsedFormula(blob, length, opts) {
var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
var rgcb, cce = blob.read_shift(len);
if (cce == 65535) return [[], parsenoop(blob, length - 2)];
var rgce = parse_Rgce(blob, cce, opts);
if (length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
blob.l = target;
return [rgce, rgcb];
}
function parse_XLSCellParsedFormula(blob, length, opts) {
var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
var rgcb, cce = blob.read_shift(len);
if (cce == 65535) return [[], parsenoop(blob, length - 2)];
var rgce = parse_Rgce(blob, cce, opts);
if (length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
blob.l = target;
return [rgce, rgcb];
}
function parse_NameParsedFormula(blob, length, opts, cce) {
var target = blob.l + length;
var rgce = parse_Rgce(blob, cce, opts);
var rgcb;
if (target !== blob.l) rgcb = parse_RgbExtra(blob, target - blob.l, rgce, opts);
return [rgce, rgcb];
}
function parse_SharedParsedFormula(blob, length, opts) {
var target = blob.l + length;
var rgcb, cce = blob.read_shift(2);
var rgce = parse_Rgce(blob, cce, opts);
if (cce == 65535) return [[], parsenoop(blob, length - 2)];
if (length !== cce + 2) rgcb = parse_RgbExtra(blob, target - cce - 2, rgce, opts);
return [rgce, rgcb];
}
function parse_FormulaValue(blob) {
var b4;
if (__readUInt16LE(blob, blob.l + 6) !== 65535) return [parse_Xnum(blob), "n"];
switch (blob[blob.l]) {
case 0:
blob.l += 8;
return ["String", "s"];
case 1:
b4 = blob[blob.l + 2] === 1;
blob.l += 8;
return [b4, "b"];
case 2:
b4 = blob[blob.l + 2];
blob.l += 8;
return [b4, "e"];
case 3:
blob.l += 8;
return ["", "s"];
}
return [];
}
function parse_Formula(blob, length, opts) {
var end = blob.l + length;
var cell = parse_XLSCell(blob, 6, opts);
var val2 = parse_FormulaValue(blob, 8);
var flags = blob.read_shift(1);
if (opts.biff != 2) {
blob.read_shift(1);
if (opts.biff >= 5) {
blob.read_shift(4);
}
}
var cbf = parse_XLSCellParsedFormula(blob, end - blob.l, opts);
return { cell, val: val2[0], formula: cbf, shared: flags >> 3 & 1, tt: val2[1] };
}
function parse_XLSBParsedFormula(data, length, opts) {
var cce = data.read_shift(4);
var rgce = parse_Rgce(data, cce, opts);
var cb = data.read_shift(4);
var rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;
return [rgce, rgcb];
}
function ods_to_csf_formula(f4) {
if (f4.slice(0, 3) == "of:") f4 = f4.slice(3);
if (f4.charCodeAt(0) == 61) {
f4 = f4.slice(1);
if (f4.charCodeAt(0) == 61) f4 = f4.slice(1);
}
f4 = f4.replace(/COM\.MICROSOFT\./g, "");
f4 = f4.replace(/\[((?:\.[A-Z]+[0-9]+)(?::\.[A-Z]+[0-9]+)?)\]/g, function($$, $1) {
return $1.replace(/\./g, "");
});
f4 = f4.replace(/\$'([^']|'')+'/g, function($$) {
return $$.slice(1);
});
f4 = f4.replace(/\$([^\]\. #$]+)/g, function($$, $1) {
return $1.match(/^([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])?(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})?$/) ? $$ : $1;
});
f4 = f4.replace(/\[.(#[A-Z]*[?!])\]/g, "$1");
return f4.replace(/[;~]/g, ",").replace(/\|/g, ";");
}
function ods_to_csf_3D(r8) {
r8 = r8.replace(/\$'([^']|'')+'/g, function($$) {
return $$.slice(1);
});
r8 = r8.replace(/\$([^\]\. #$]+)/g, function($$, $1) {
return $1.match(/^([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])?(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})?$/) ? $$ : $1;
});
var a3 = r8.split(":");
var s6 = a3[0].split(".")[0];
return [s6, a3[0].split(".")[1] + (a3.length > 1 ? ":" + (a3[1].split(".")[1] || a3[1].split(".")[0]) : "")];
}
function default_margins(margins, mode) {
if (!margins) return;
var defs = [0.7, 0.7, 0.75, 0.75, 0.3, 0.3];
if (mode == "xlml") defs = [1, 1, 1, 1, 0.5, 0.5];
if (margins.left == null) margins.left = defs[0];
if (margins.right == null) margins.right = defs[1];
if (margins.top == null) margins.top = defs[2];
if (margins.bottom == null) margins.bottom = defs[3];
if (margins.header == null) margins.header = defs[4];
if (margins.footer == null) margins.footer = defs[5];
}
function safe_format(p4, fmtid, fillid, opts, themes, styles2, date1904) {
try {
if (opts.cellNF) p4.z = table_fmt[fmtid];
} catch (e9) {
if (opts.WTF) throw e9;
}
if (p4.t === "z" && !opts.cellStyles) return;
if (p4.t === "d" && typeof p4.v === "string") p4.v = parseDate(p4.v);
if ((!opts || opts.cellText !== false) && p4.t !== "z") try {
if (table_fmt[fmtid] == null) SSF__load(SSFImplicit[fmtid] || "General", fmtid);
if (p4.t === "e") p4.w = p4.w || BErr[p4.v];
else if (fmtid === 0) {
if (p4.t === "n") {
if ((p4.v | 0) === p4.v) p4.w = p4.v.toString(10);
else p4.w = SSF_general_num(p4.v);
} else if (p4.t === "d") {
var dd = datenum(p4.v, !!date1904);
if ((dd | 0) === dd) p4.w = dd.toString(10);
else p4.w = SSF_general_num(dd);
} else if (p4.v === void 0) return "";
else p4.w = SSF_general(p4.v, _ssfopts);
} else if (p4.t === "d") p4.w = SSF_format(fmtid, datenum(p4.v, !!date1904), _ssfopts);
else p4.w = SSF_format(fmtid, p4.v, _ssfopts);
} catch (e9) {
if (opts.WTF) throw e9;
}
if (!opts.cellStyles) return;
if (fillid != null) try {
p4.s = styles2.Fills[fillid];
if (p4.s.fgColor && p4.s.fgColor.theme && !p4.s.fgColor.rgb) {
p4.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p4.s.fgColor.theme].rgb, p4.s.fgColor.tint || 0);
if (opts.WTF) p4.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p4.s.fgColor.theme].rgb;
}
if (p4.s.bgColor && p4.s.bgColor.theme) {
p4.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p4.s.bgColor.theme].rgb, p4.s.bgColor.tint || 0);
if (opts.WTF) p4.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p4.s.bgColor.theme].rgb;
}
} catch (e9) {
if (opts.WTF && styles2.Fills) throw e9;
}
}
function parse_ws_xml_dim(ws, s6) {
var d4 = safe_decode_range(s6);
if (d4.s.r <= d4.e.r && d4.s.c <= d4.e.c && d4.s.r >= 0 && d4.s.c >= 0) ws["!ref"] = encode_range(d4);
}
function parse_ws_xml(data, opts, idx, rels, wb, themes, styles2) {
if (!data) return data;
if (!rels) rels = { "!id": {} };
if (DENSE != null && opts.dense == null) opts.dense = DENSE;
var s6 = {};
if (opts.dense) s6["!data"] = [];
var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } };
var data1 = "", data2 = "";
var mtch = str_match_xml_ns(data, "sheetData");
if (mtch) {
data1 = data.slice(0, mtch.index);
data2 = data.slice(mtch.index + mtch[0].length);
} else data1 = data2 = data;
var sheetPr = data1.match(sheetprregex);
if (sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s6, wb, idx);
else if (sheetPr = str_match_xml_ns(data1, "sheetPr")) parse_ws_xml_sheetpr2(sheetPr[0], sheetPr[1] || "", s6, wb, idx, styles2, themes);
var ridx = (data1.match(/<(?:\w*:)?dimension/) || { index: -1 }).index;
if (ridx > 0) {
var ref = data1.slice(ridx, ridx + 50).match(dimregex);
if (ref && !(opts && opts.nodim)) parse_ws_xml_dim(s6, ref[1]);
}
var svs = str_match_xml_ns(data1, "sheetViews");
if (svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb);
var columns = [];
if (opts.cellStyles) {
var cols = data1.match(colregex);
if (cols) parse_ws_xml_cols(columns, cols);
}
if (mtch) parse_ws_xml_data(mtch[1], s6, opts, refguess, themes, styles2, wb);
var afilter = data2.match(afregex);
if (afilter) s6["!autofilter"] = parse_ws_xml_autofilter(afilter[0]);
var merges = [];
var _merge = data2.match(mergecregex);
if (_merge) for (ridx = 0; ridx != _merge.length; ++ridx)
merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("=") + 2));
var hlink = data2.match(hlinkregex);
if (hlink) parse_ws_xml_hlinks(s6, hlink, rels);
var margins = data2.match(marginregex);
if (margins) s6["!margins"] = parse_ws_xml_margins(parsexmltag(margins[0]));
var m4;
if (m4 = data2.match(/legacyDrawing r:id="(.*?)"/)) s6["!legrel"] = m4[1];
if (opts && opts.nodim) refguess.s.c = refguess.s.r = 0;
if (!s6["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s6["!ref"] = encode_range(refguess);
if (opts.sheetRows > 0 && s6["!ref"]) {
var tmpref = safe_decode_range(s6["!ref"]);
if (opts.sheetRows <= +tmpref.e.r) {
tmpref.e.r = opts.sheetRows - 1;
if (tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
if (tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
if (tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
if (tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
s6["!fullref"] = s6["!ref"];
s6["!ref"] = encode_range(tmpref);
}
}
if (columns.length > 0) s6["!cols"] = columns;
if (merges.length > 0) s6["!merges"] = merges;
if (rels["!id"][s6["!legrel"]]) s6["!legdrawel"] = rels["!id"][s6["!legrel"]];
return s6;
}
function parse_ws_xml_sheetpr(sheetPr, s6, wb, idx) {
var data = parsexmltag(sheetPr);
if (!wb.Sheets[idx]) wb.Sheets[idx] = {};
if (data.codeName) wb.Sheets[idx].CodeName = unescapexml(utf8read(data.codeName));
}
function parse_ws_xml_sheetpr2(sheetPr, body, s6, wb, idx) {
parse_ws_xml_sheetpr(sheetPr.slice(0, sheetPr.indexOf(">")), s6, wb, idx);
}
function parse_ws_xml_hlinks(s6, data, rels) {
var dense = s6["!data"] != null;
for (var i7 = 0; i7 != data.length; ++i7) {
var val2 = parsexmltag(utf8read(data[i7]), true);
if (!val2.ref) return;
var rel2 = ((rels || {})["!id"] || [])[val2.id];
if (rel2) {
val2.Target = rel2.Target;
if (val2.location) val2.Target += "#" + unescapexml(val2.location);
} else {
val2.Target = "#" + unescapexml(val2.location);
rel2 = { Target: val2.Target, TargetMode: "Internal" };
}
val2.Rel = rel2;
if (val2.tooltip) {
val2.Tooltip = val2.tooltip;
delete val2.tooltip;
}
var rng = safe_decode_range(val2.ref);
for (var R3 = rng.s.r; R3 <= rng.e.r; ++R3) for (var C3 = rng.s.c; C3 <= rng.e.c; ++C3) {
var addr = encode_col(C3) + encode_row(R3);
if (dense) {
if (!s6["!data"][R3]) s6["!data"][R3] = [];
if (!s6["!data"][R3][C3]) s6["!data"][R3][C3] = { t: "z", v: void 0 };
s6["!data"][R3][C3].l = val2;
} else {
if (!s6[addr]) s6[addr] = { t: "z", v: void 0 };
s6[addr].l = val2;
}
}
}
}
function parse_ws_xml_margins(margin) {
var o9 = {};
["left", "right", "top", "bottom", "header", "footer"].forEach(function(k2) {
if (margin[k2]) o9[k2] = parseFloat(margin[k2]);
});
return o9;
}
function parse_ws_xml_cols(columns, cols) {
var seencol = false;
for (var coli = 0; coli != cols.length; ++coli) {
var coll = parsexmltag(cols[coli], true);
if (coll.hidden) coll.hidden = parsexmlbool(coll.hidden);
var colm = parseInt(coll.min, 10) - 1, colM = parseInt(coll.max, 10) - 1;
if (coll.outlineLevel) coll.level = +coll.outlineLevel || 0;
delete coll.min;
delete coll.max;
coll.width = +coll.width;
if (!seencol && coll.width) {
seencol = true;
find_mdw_colw(coll.width);
}
process_col(coll);
while (colm <= colM) columns[colm++] = dup(coll);
}
}
function parse_ws_xml_autofilter(data) {
var o9 = { ref: (data.match(/ref="([^"]*)"/) || [])[1] };
return o9;
}
function parse_ws_xml_sheetviews(data, wb) {
if (!wb.Views) wb.Views = [{}];
(data.match(sviewregex) || []).forEach(function(r8, i7) {
var tag = parsexmltag(r8);
if (!wb.Views[i7]) wb.Views[i7] = {};
if (+tag.zoomScale) wb.Views[i7].zoom = +tag.zoomScale;
if (tag.rightToLeft && parsexmlbool(tag.rightToLeft)) wb.Views[i7].RTL = true;
});
}
function parse_BrtRowHdr(data, length) {
var z3 = {};
var tgt = data.l + length;
z3.r = data.read_shift(4);
data.l += 4;
var miyRw = data.read_shift(2);
data.l += 1;
var flags = data.read_shift(1);
data.l = tgt;
if (flags & 7) z3.level = flags & 7;
if (flags & 16) z3.hidden = true;
if (flags & 32) z3.hpt = miyRw / 20;
return z3;
}
function parse_BrtWsFmtInfo() {
}
function parse_BrtWsProp(data, length) {
var z3 = {};
var f4 = data[data.l];
++data.l;
z3.above = !(f4 & 64);
z3.left = !(f4 & 128);
data.l += 18;
z3.name = parse_XLSBCodeName(data, length - 19);
return z3;
}
function parse_BrtCellBlank(data) {
var cell = parse_XLSBCell(data);
return [cell];
}
function parse_BrtShortBlank(data) {
var cell = parse_XLSBShortCell(data);
return [cell];
}
function parse_BrtCellBool(data) {
var cell = parse_XLSBCell(data);
var fBool = data.read_shift(1);
return [cell, fBool, "b"];
}
function parse_BrtShortBool(data) {
var cell = parse_XLSBShortCell(data);
var fBool = data.read_shift(1);
return [cell, fBool, "b"];
}
function parse_BrtCellError(data) {
var cell = parse_XLSBCell(data);
var bError = data.read_shift(1);
return [cell, bError, "e"];
}
function parse_BrtShortError(data) {
var cell = parse_XLSBShortCell(data);
var bError = data.read_shift(1);
return [cell, bError, "e"];
}
function parse_BrtCellIsst(data) {
var cell = parse_XLSBCell(data);
var isst = data.read_shift(4);
return [cell, isst, "s"];
}
function parse_BrtShortIsst(data) {
var cell = parse_XLSBShortCell(data);
var isst = data.read_shift(4);
return [cell, isst, "s"];
}
function parse_BrtCellReal(data) {
var cell = parse_XLSBCell(data);
var value = parse_Xnum(data);
return [cell, value, "n"];
}
function parse_BrtShortReal(data) {
var cell = parse_XLSBShortCell(data);
var value = parse_Xnum(data);
return [cell, value, "n"];
}
function parse_BrtCellRk(data) {
var cell = parse_XLSBCell(data);
var value = parse_RkNumber(data);
return [cell, value, "n"];
}
function parse_BrtShortRk(data) {
var cell = parse_XLSBShortCell(data);
var value = parse_RkNumber(data);
return [cell, value, "n"];
}
function parse_BrtCellRString(data) {
var cell = parse_XLSBCell(data);
var value = parse_RichStr(data);
return [cell, value, "is"];
}
function parse_BrtCellSt(data) {
var cell = parse_XLSBCell(data);
var value = parse_XLWideString(data);
return [cell, value, "str"];
}
function parse_BrtShortSt(data) {
var cell = parse_XLSBShortCell(data);
var value = parse_XLWideString(data);
return [cell, value, "str"];
}
function parse_BrtFmlaBool(data, length, opts) {
var end = data.l + length;
var cell = parse_XLSBCell(data);
cell.r = opts["!row"];
var value = data.read_shift(1);
var o9 = [cell, value, "b"];
if (opts.cellFormula) {
data.l += 2;
var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts);
} else data.l = end;
return o9;
}
function parse_BrtFmlaError(data, length, opts) {
var end = data.l + length;
var cell = parse_XLSBCell(data);
cell.r = opts["!row"];
var value = data.read_shift(1);
var o9 = [cell, value, "e"];
if (opts.cellFormula) {
data.l += 2;
var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts);
} else data.l = end;
return o9;
}
function parse_BrtFmlaNum(data, length, opts) {
var end = data.l + length;
var cell = parse_XLSBCell(data);
cell.r = opts["!row"];
var value = parse_Xnum(data);
var o9 = [cell, value, "n"];
if (opts.cellFormula) {
data.l += 2;
var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts);
} else data.l = end;
return o9;
}
function parse_BrtFmlaString(data, length, opts) {
var end = data.l + length;
var cell = parse_XLSBCell(data);
cell.r = opts["!row"];
var value = parse_XLWideString(data);
var o9 = [cell, value, "str"];
if (opts.cellFormula) {
data.l += 2;
var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts);
} else data.l = end;
return o9;
}
function parse_BrtHLink(data, length) {
var end = data.l + length;
var rfx = parse_UncheckedRfX(data, 16);
var relId = parse_XLNullableWideString(data);
var loc = parse_XLWideString(data);
var tooltip = parse_XLWideString(data);
var display = parse_XLWideString(data);
data.l = end;
var o9 = { rfx, relId, loc, display };
if (tooltip) o9.Tooltip = tooltip;
return o9;
}
function parse_BrtPane() {
}
function parse_BrtArrFmla(data, length, opts) {
var end = data.l + length;
var rfx = parse_RfX(data, 16);
var fAlwaysCalc = data.read_shift(1);
var o9 = [rfx];
o9[2] = fAlwaysCalc;
if (opts.cellFormula) {
var formula = parse_XLSBArrayParsedFormula(data, end - data.l, opts);
o9[1] = formula;
} else data.l = end;
return o9;
}
function parse_BrtShrFmla(data, length, opts) {
var end = data.l + length;
var rfx = parse_UncheckedRfX(data, 16);
var o9 = [rfx];
if (opts.cellFormula) {
var formula = parse_XLSBSharedParsedFormula(data, end - data.l, opts);
o9[1] = formula;
data.l = end;
} else data.l = end;
return o9;
}
function parse_BrtMargins(data) {
var margins = {};
BrtMarginKeys.forEach(function(k2) {
margins[k2] = parse_Xnum(data, 8);
});
return margins;
}
function parse_BrtBeginWsView(data) {
var f4 = data.read_shift(2);
data.l += 28;
return { RTL: f4 & 32 };
}
function parse_BrtDVal() {
}
function parse_BrtDVal14() {
}
function parse_ws_bin(data, _opts, idx, rels, wb, themes, styles2) {
if (!data) return data;
var opts = _opts || {};
if (!rels) rels = { "!id": {} };
if (DENSE != null && opts.dense == null) opts.dense = DENSE;
var s6 = {};
if (opts.dense) s6["!data"] = [];
var ref;
var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } };
var state = [];
var pass = false, end = false;
var row, p4, cf, R3, C3, addr, sstr, rr, cell;
var merges = [];
opts.biff = 12;
opts["!row"] = 0;
var ai = 0, af = false;
var arrayf = [];
var sharedf = {};
var supbooks = opts.supbooks || /*::(*/
wb.supbooks || [[]];
supbooks.sharedf = sharedf;
supbooks.arrayf = arrayf;
supbooks.SheetNames = wb.SheetNames || wb.Sheets.map(function(x2) {
return x2.name;
});
if (!opts.supbooks) {
opts.supbooks = supbooks;
if (wb.Names) for (var i7 = 0; i7 < wb.Names.length; ++i7) supbooks[0][i7 + 1] = wb.Names[i7];
}
var colinfo = [], rowinfo = [];
var seencol = false;
XLSBRecordEnum[16] = { n: "BrtShortReal", f: parse_BrtShortReal };
var cm, vm;
var date1904 = 1462 * +!!((wb || {}).WBProps || {}).date1904;
recordhopper(data, function ws_parse(val2, RR, RT) {
if (end) return;
switch (RT) {
case 148:
ref = val2;
break;
case 0:
row = val2;
if (opts.sheetRows && opts.sheetRows <= row.r) end = true;
rr = encode_row(R3 = row.r);
opts["!row"] = row.r;
if (val2.hidden || val2.hpt || val2.level != null) {
if (val2.hpt) val2.hpx = pt2px(val2.hpt);
rowinfo[val2.r] = val2;
}
break;
case 2:
/* 'BrtCellRk' */
case 3:
/* 'BrtCellError' */
case 4:
/* 'BrtCellBool' */
case 5:
/* 'BrtCellReal' */
case 6:
/* 'BrtCellSt' */
case 7:
/* 'BrtCellIsst' */
case 8:
/* 'BrtFmlaString' */
case 9:
/* 'BrtFmlaNum' */
case 10:
/* 'BrtFmlaBool' */
case 11:
/* 'BrtFmlaError' */
case 13:
/* 'BrtShortRk' */
case 14:
/* 'BrtShortError' */
case 15:
/* 'BrtShortBool' */
case 16:
/* 'BrtShortReal' */
case 17:
/* 'BrtShortSt' */
case 18:
/* 'BrtShortIsst' */
case 62:
p4 = { t: val2[2] };
switch (val2[2]) {
case "n":
p4.v = val2[1];
break;
case "s":
sstr = strs[val2[1]];
p4.v = sstr.t;
p4.r = sstr.r;
break;
case "b":
p4.v = val2[1] ? true : false;
break;
case "e":
p4.v = val2[1];
if (opts.cellText !== false) p4.w = BErr[p4.v];
break;
case "str":
p4.t = "s";
p4.v = val2[1];
break;
case "is":
p4.t = "s";
p4.v = val2[1].t;
break;
}
if (cf = styles2.CellXf[val2[0].iStyleRef]) safe_format(p4, cf.numFmtId, null, opts, themes, styles2, date1904 > 0);
C3 = val2[0].c == -1 ? C3 + 1 : val2[0].c;
if (opts.dense) {
if (!s6["!data"][R3]) s6["!data"][R3] = [];
s6["!data"][R3][C3] = p4;
} else s6[encode_col(C3) + rr] = p4;
if (opts.cellFormula) {
af = false;
for (ai = 0; ai < arrayf.length; ++ai) {
var aii = arrayf[ai];
if (row.r >= aii[0].s.r && row.r <= aii[0].e.r) {
if (C3 >= aii[0].s.c && C3 <= aii[0].e.c) {
p4.F = encode_range(aii[0]);
af = true;
}
}
}
if (!af && val2.length > 3) p4.f = val2[3];
}
if (refguess.s.r > row.r) refguess.s.r = row.r;
if (refguess.s.c > C3) refguess.s.c = C3;
if (refguess.e.r < row.r) refguess.e.r = row.r;
if (refguess.e.c < C3) refguess.e.c = C3;
if (opts.cellDates && cf && p4.t == "n" && fmt_is_date(table_fmt[cf.numFmtId])) {
var _d = SSF_parse_date_code(p4.v + date1904);
if (_d) {
p4.t = "d";
p4.v = new Date(Date.UTC(_d.y, _d.m - 1, _d.d, _d.H, _d.M, _d.S, _d.u));
}
}
if (cm) {
if (cm.type == "XLDAPR") p4.D = true;
cm = void 0;
}
if (vm) vm = void 0;
break;
case 1:
/* 'BrtCellBlank' */
case 12:
if (!opts.sheetStubs || pass) break;
p4 = { t: "z", v: void 0 };
C3 = val2[0].c == -1 ? C3 + 1 : val2[0].c;
if (opts.dense) {
if (!s6["!data"][R3]) s6["!data"][R3] = [];
s6["!data"][R3][C3] = p4;
} else s6[encode_col(C3) + rr] = p4;
if (refguess.s.r > row.r) refguess.s.r = row.r;
if (refguess.s.c > C3) refguess.s.c = C3;
if (refguess.e.r < row.r) refguess.e.r = row.r;
if (refguess.e.c < C3) refguess.e.c = C3;
if (cm) {
if (cm.type == "XLDAPR") p4.D = true;
cm = void 0;
}
if (vm) vm = void 0;
break;
case 176:
merges.push(val2);
break;
case 49:
{
cm = ((opts.xlmeta || {}).Cell || [])[val2 - 1];
}
break;
case 494:
var rel2 = rels["!id"][val2.relId];
if (rel2) {
val2.Target = rel2.Target;
if (val2.loc) val2.Target += "#" + val2.loc;
val2.Rel = rel2;
} else if (val2.relId == "") {
val2.Target = "#" + val2.loc;
}
for (R3 = val2.rfx.s.r; R3 <= val2.rfx.e.r; ++R3) for (C3 = val2.rfx.s.c; C3 <= val2.rfx.e.c; ++C3) {
if (opts.dense) {
if (!s6["!data"][R3]) s6["!data"][R3] = [];
if (!s6["!data"][R3][C3]) s6["!data"][R3][C3] = { t: "z", v: void 0 };
s6["!data"][R3][C3].l = val2;
} else {
addr = encode_col(C3) + encode_row(R3);
if (!s6[addr]) s6[addr] = { t: "z", v: void 0 };
s6[addr].l = val2;
}
}
break;
case 426:
if (!opts.cellFormula) break;
arrayf.push(val2);
cell = opts.dense ? s6["!data"][R3][C3] : s6[encode_col(C3) + rr];
cell.f = stringify_formula(val2[1], refguess, { r: row.r, c: C3 }, supbooks, opts);
cell.F = encode_range(val2[0]);
break;
case 427:
if (!opts.cellFormula) break;
sharedf[encode_cell(val2[0].s)] = val2[1];
cell = opts.dense ? s6["!data"][R3][C3] : s6[encode_col(C3) + rr];
cell.f = stringify_formula(val2[1], refguess, { r: row.r, c: C3 }, supbooks, opts);
break;
/* identical to 'ColInfo' in XLS */
case 60:
if (!opts.cellStyles) break;
while (val2.e >= val2.s) {
colinfo[val2.e--] = { width: val2.w / 256, hidden: !!(val2.flags & 1), level: val2.level };
if (!seencol) {
seencol = true;
find_mdw_colw(val2.w / 256);
}
process_col(colinfo[val2.e + 1]);
}
break;
case 551:
if (val2) s6["!legrel"] = val2;
break;
case 161:
s6["!autofilter"] = { ref: encode_range(val2) };
break;
case 476:
s6["!margins"] = val2;
break;
case 147:
if (!wb.Sheets[idx]) wb.Sheets[idx] = {};
if (val2.name) wb.Sheets[idx].CodeName = val2.name;
if (val2.above || val2.left) s6["!outline"] = { above: val2.above, left: val2.left };
break;
case 137:
if (!wb.Views) wb.Views = [{}];
if (!wb.Views[0]) wb.Views[0] = {};
if (val2.RTL) wb.Views[0].RTL = true;
break;
case 485:
break;
case 64:
/* 'BrtDVal' */
case 1053:
break;
case 151:
break;
case 152:
/* 'BrtSel' */
case 175:
/* 'BrtAFilterDateGroupItem' */
case 644:
/* 'BrtActiveX' */
case 625:
/* 'BrtBigName' */
case 562:
/* 'BrtBkHim' */
case 396:
/* 'BrtBrk' */
case 1112:
/* 'BrtCFIcon' */
case 1146:
/* 'BrtCFRuleExt' */
case 471:
/* 'BrtCFVO' */
case 1050:
/* 'BrtCFVO14' */
case 649:
/* 'BrtCellIgnoreEC' */
case 1105:
/* 'BrtCellIgnoreEC14' */
case 589:
/* 'BrtCellSmartTagProperty' */
case 607:
/* 'BrtCellWatch' */
case 564:
/* 'BrtColor' */
case 1055:
/* 'BrtColor14' */
case 168:
/* 'BrtColorFilter' */
case 174:
/* 'BrtCustomFilter' */
case 1180:
/* 'BrtCustomFilter14' */
case 499:
/* 'BrtDRef' */
case 507:
/* 'BrtDXF' */
case 550:
/* 'BrtDrawing' */
case 171:
/* 'BrtDynamicFilter' */
case 167:
/* 'BrtFilter' */
case 1177:
/* 'BrtFilter14' */
case 169:
/* 'BrtIconFilter' */
case 1181:
/* 'BrtIconFilter14' */
case 552:
/* 'BrtLegacyDrawingHF' */
case 661:
/* 'BrtListPart' */
case 639:
/* 'BrtOleObject' */
case 478:
/* 'BrtPageSetup' */
case 537:
/* 'BrtPhoneticInfo' */
case 477:
/* 'BrtPrintOptions' */
case 536:
/* 'BrtRangeProtection' */
case 1103:
/* 'BrtRangeProtection14' */
case 680:
/* 'BrtRangeProtectionIso' */
case 1104:
/* 'BrtRangeProtectionIso14' */
case 1024:
/* 'BrtRwDescent' */
case 663:
/* 'BrtSheetCalcProp' */
case 535:
/* 'BrtSheetProtection' */
case 678:
/* 'BrtSheetProtectionIso' */
case 504:
/* 'BrtSlc' */
case 1043:
/* 'BrtSparkline' */
case 428:
/* 'BrtTable' */
case 170:
/* 'BrtTop10Filter' */
case 3072:
/* 'BrtUid' */
case 50:
/* 'BrtValueMeta' */
case 2070:
/* 'BrtWebExtension' */
case 1045:
break;
case 35:
pass = true;
break;
case 36:
pass = false;
break;
case 37:
state.push(RT);
pass = true;
break;
case 38:
state.pop();
pass = false;
break;
default:
if (RR.T) {
} else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
}
}, opts);
delete opts.supbooks;
delete opts["!row"];
if (!s6["!ref"] && (refguess.s.r < 2e6 || ref && (ref.e.r > 0 || ref.e.c > 0 || ref.s.r > 0 || ref.s.c > 0))) s6["!ref"] = encode_range(ref || refguess);
if (opts.sheetRows && s6["!ref"]) {
var tmpref = safe_decode_range(s6["!ref"]);
if (opts.sheetRows <= +tmpref.e.r) {
tmpref.e.r = opts.sheetRows - 1;
if (tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
if (tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
if (tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
if (tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
s6["!fullref"] = s6["!ref"];
s6["!ref"] = encode_range(tmpref);
}
}
if (merges.length > 0) s6["!merges"] = merges;
if (colinfo.length > 0) s6["!cols"] = colinfo;
if (rowinfo.length > 0) s6["!rows"] = rowinfo;
if (rels["!id"][s6["!legrel"]]) s6["!legdrawel"] = rels["!id"][s6["!legrel"]];
return s6;
}
function parse_Cache(data) {
var col = [];
var num = data.match(/^/);
var f4;
(data.match(/\/]*>([^<])<\/c:v><\/c:pt>/mg) || []).forEach(function(pt) {
var q2 = pt.match(/\/]*>([^<]*)<\/c:v><\/c:pt>/);
if (!q2) return;
col[+q2[1]] = num ? +q2[2] : q2[2];
});
var nf = unescapexml((str_match_xml(data, "c:formatCode") || ["", "General"])[1]);
(str_match_ng(data, "", " ") || []).forEach(function(F2) {
f4 = F2.replace(/<[^<>]*>/g, "");
});
return [col, nf, f4];
}
function parse_chart(data, name, opts, rels, wb, csheet) {
var cs = csheet || { "!type": "chart" };
if (!data) return csheet;
var C3 = 0, R3 = 0, col = "A";
var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } };
(str_match_ng(data, "", " ") || []).forEach(function(nc) {
var cache = parse_Cache(nc);
refguess.s.r = refguess.s.c = 0;
refguess.e.c = C3;
col = encode_col(C3);
cache[0].forEach(function(n7, i7) {
if (cs["!data"]) {
if (!cs["!data"][i7]) cs["!data"][i7] = [];
cs["!data"][i7][C3] = { t: "n", v: n7, z: cache[1] };
} else cs[col + encode_row(i7)] = { t: "n", v: n7, z: cache[1] };
R3 = i7;
});
if (refguess.e.r < R3) refguess.e.r = R3;
++C3;
});
if (C3 > 0) cs["!ref"] = encode_range(refguess);
return cs;
}
function parse_cs_xml(data, opts, idx, rels, wb) {
if (!data) return data;
if (!rels) rels = { "!id": {} };
var s6 = { "!type": "chart", "!drawel": null, "!rel": "" };
var m4;
var sheetPr = data.match(sheetprregex);
if (sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s6, wb, idx);
if (m4 = data.match(/drawing r:id="(.*?)"/)) s6["!rel"] = m4[1];
if (rels["!id"][s6["!rel"]]) s6["!drawel"] = rels["!id"][s6["!rel"]];
return s6;
}
function parse_BrtCsProp(data, length) {
data.l += 10;
var name = parse_XLWideString(data, length - 10);
return { name };
}
function parse_cs_bin(data, opts, idx, rels, wb) {
if (!data) return data;
if (!rels) rels = { "!id": {} };
var s6 = { "!type": "chart", "!drawel": null, "!rel": "" };
var state = [];
var pass = false;
recordhopper(data, function cs_parse(val2, R3, RT) {
switch (RT) {
case 550:
s6["!rel"] = val2;
break;
case 651:
if (!wb.Sheets[idx]) wb.Sheets[idx] = {};
if (val2.name) wb.Sheets[idx].CodeName = val2.name;
break;
case 562:
/* 'BrtBkHim' */
case 652:
/* 'BrtCsPageSetup' */
case 669:
/* 'BrtCsProtection' */
case 679:
/* 'BrtCsProtectionIso' */
case 551:
/* 'BrtLegacyDrawing' */
case 552:
/* 'BrtLegacyDrawingHF' */
case 476:
/* 'BrtMargins' */
case 3072:
break;
case 35:
pass = true;
break;
case 36:
pass = false;
break;
case 37:
state.push(RT);
break;
case 38:
state.pop();
break;
default:
if (R3.T > 0) state.push(RT);
else if (R3.T < 0) state.pop();
else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
}
}, opts);
if (rels["!id"][s6["!rel"]]) s6["!drawel"] = rels["!id"][s6["!rel"]];
return s6;
}
function push_defaults_array(target, defaults4) {
for (var j3 = 0; j3 != target.length; ++j3) {
var w3 = target[j3];
for (var i7 = 0; i7 != defaults4.length; ++i7) {
var z3 = defaults4[i7];
if (w3[z3[0]] == null) w3[z3[0]] = z3[1];
else switch (z3[2]) {
case "bool":
if (typeof w3[z3[0]] == "string") w3[z3[0]] = parsexmlbool(w3[z3[0]]);
break;
case "int":
if (typeof w3[z3[0]] == "string") w3[z3[0]] = parseInt(w3[z3[0]], 10);
break;
}
}
}
}
function push_defaults(target, defaults4) {
for (var i7 = 0; i7 != defaults4.length; ++i7) {
var z3 = defaults4[i7];
if (target[z3[0]] == null) target[z3[0]] = z3[1];
else switch (z3[2]) {
case "bool":
if (typeof target[z3[0]] == "string") target[z3[0]] = parsexmlbool(target[z3[0]]);
break;
case "int":
if (typeof target[z3[0]] == "string") target[z3[0]] = parseInt(target[z3[0]], 10);
break;
}
}
}
function parse_wb_defaults(wb) {
push_defaults(wb.WBProps, WBPropsDef);
push_defaults(wb.CalcPr, CalcPrDef);
push_defaults_array(wb.WBView, WBViewDef);
push_defaults_array(wb.Sheets, SheetDef);
_ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904);
}
function check_ws_name(n7, safe) {
try {
if (n7 == "") throw new Error("Sheet name cannot be blank");
if (n7.length > 31) throw new Error("Sheet name cannot exceed 31 chars");
if (n7.charCodeAt(0) == 39 || n7.charCodeAt(n7.length - 1) == 39) throw new Error("Sheet name cannot start or end with apostrophe (')");
if (n7.toLowerCase() == "history") throw new Error("Sheet name cannot be 'History'");
badchars.forEach(function(c6) {
if (n7.indexOf(c6) == -1) return;
throw new Error("Sheet name cannot contain : \\ / ? * [ ]");
});
} catch (e9) {
if (safe) return false;
throw e9;
}
return true;
}
function parse_wb_xml(data, opts) {
if (!data) throw new Error("Could not find file");
var wb = (
/*::(*/
{ AppVersion: {}, WBProps: {}, WBView: [], Sheets: [], CalcPr: {}, Names: [], xmlns: "" }
);
var pass = false, xmlns = "xmlns";
var dname = {}, dnstart = 0;
data.replace(tagregex, function xml_wb(x2, idx) {
var y4 = parsexmltag(x2);
switch (strip_ns(y4[0])) {
case "":
break;
/* 18.2.13 fileVersion CT_FileVersion ? */
case " ":
case "":
break;
/* 18.2.12 fileSharing CT_FileSharing ? */
case " ":
break;
/* 18.2.28 workbookPr CT_WorkbookPr ? */
case " ":
WBPropsDef.forEach(function(w3) {
if (y4[w3[0]] == null) return;
switch (w3[2]) {
case "bool":
wb.WBProps[w3[0]] = parsexmlbool(y4[w3[0]]);
break;
case "int":
wb.WBProps[w3[0]] = parseInt(y4[w3[0]], 10);
break;
default:
wb.WBProps[w3[0]] = y4[w3[0]];
}
});
if (y4.codeName) wb.WBProps.CodeName = utf8read(y4.codeName);
break;
case "":
break;
/* 18.2.29 workbookProtection CT_WorkbookProtection ? */
case " ":
break;
/* 18.2.1 bookViews CT_BookViews ? */
case "":
case " ":
break;
/* 18.2.30 workbookView CT_BookView + */
case " ":
delete y4[0];
wb.WBView.push(y4);
break;
case "":
break;
/* 18.2.20 sheets CT_Sheets 1 */
case "":
case " ":
break;
// aggregate sheet
/* 18.2.19 sheet CT_Sheet + */
case "":
break;
/* 18.2.15 functionGroups CT_FunctionGroups ? */
case " ":
break;
/* 18.2.14 functionGroup CT_FunctionGroup + */
case "":
case "":
break;
/* 18.2.8 externalReference CT_ExternalReference + */
case " ":
break;
case "":
case "":
pass = false;
break;
/* 18.2.5 definedName CT_DefinedName + */
case "":
{
dname.Ref = unescapexml(utf8read(data.slice(dnstart, idx)));
wb.Names.push(dname);
}
break;
case " ":
break;
/* 18.2.2 calcPr CT_CalcPr ? */
case " ":
delete y4[0];
wb.CalcPr = y4;
break;
case "":
break;
/* 18.2.16 oleSize CT_OleSize ? (ref required) */
case "":
case "":
case "":
break;
/* 18.2.18 pivotCaches CT_PivotCaches ? */
case "":
case " ":
case " ":
break;
/* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
case "":
case " ":
break;
/* 18.2.22 smartTagType CT_SmartTagType ? */
case " ":
break;
/* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
case " ":
break;
/* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
case "":
case "":
break;
/* 18.2.25 webPublishObject CT_WebPublishObject ? */
case "":
case "":
case " ":
break;
/* 18.2.7 ext CT_Extension + */
case "":
pass = false;
break;
/* Others */
case "":
pass = true;
break;
case "":
pass = false;
break;
/* TODO */
case " 8 ? parse_XLWideString(data) : "";
if (strName.length > 0) o9.CodeName = strName;
o9.autoCompressPictures = !!(flags & 65536);
o9.backupFile = !!(flags & 64);
o9.checkCompatibility = !!(flags & 4096);
o9.date1904 = !!(flags & 1);
o9.filterPrivacy = !!(flags & 8);
o9.hidePivotFieldList = !!(flags & 1024);
o9.promptedSolutions = !!(flags & 16);
o9.publishItems = !!(flags & 2048);
o9.refreshAllConnections = !!(flags & 262144);
o9.saveExternalLinkValues = !!(flags & 128);
o9.showBorderUnselectedTables = !!(flags & 4);
o9.showInkAnnotation = !!(flags & 32);
o9.showObjects = ["all", "placeholders", "none"][flags >> 13 & 3];
o9.showPivotChartFilter = !!(flags & 32768);
o9.updateLinks = ["userSet", "never", "always"][flags >> 8 & 3];
return o9;
}
function parse_BrtFRTArchID$(data, length) {
var o9 = {};
data.read_shift(4);
o9.ArchID = data.read_shift(4);
data.l += length - 8;
return o9;
}
function parse_BrtName(data, length, opts) {
var end = data.l + length;
var flags = data.read_shift(4);
data.l += 1;
var itab = data.read_shift(4);
var name = parse_XLNameWideString(data);
var formula;
var comment = "";
try {
formula = parse_XLSBNameParsedFormula(data, 0, opts);
try {
comment = parse_XLNullableWideString(data);
} catch (e9) {
}
} catch (e9) {
console.error("Could not parse defined name " + name);
}
if (flags & 32) name = "_xlnm." + name;
data.l = end;
var out = { Name: name, Ptg: formula, Flags: flags };
if (itab < 268435455) out.Sheet = itab;
if (comment) out.Comment = comment;
return out;
}
function parse_wb_bin(data, opts) {
var wb = { AppVersion: {}, WBProps: {}, WBView: [], Sheets: [], CalcPr: {}, xmlns: "" };
var state = [];
var pass = false;
if (!opts) opts = {};
opts.biff = 12;
var Names = [];
var supbooks = [[]];
supbooks.SheetNames = [];
supbooks.XTI = [];
XLSBRecordEnum[16] = { n: "BrtFRTArchID$", f: parse_BrtFRTArchID$ };
recordhopper(data, function hopper_wb(val2, R3, RT) {
switch (RT) {
case 156:
supbooks.SheetNames.push(val2.name);
wb.Sheets.push(val2);
break;
case 153:
wb.WBProps = val2;
break;
case 39:
if (val2.Sheet != null) opts.SID = val2.Sheet;
val2.Ref = val2.Ptg ? stringify_formula(val2.Ptg, null, null, supbooks, opts) : "#REF!";
delete opts.SID;
delete val2.Ptg;
Names.push(val2);
break;
case 1036:
break;
case 357:
/* 'BrtSupSelf' */
case 358:
/* 'BrtSupSame' */
case 355:
/* 'BrtSupBookSrc' */
case 667:
if (!supbooks[0].length) supbooks[0] = [RT, val2];
else supbooks.push([RT, val2]);
supbooks[supbooks.length - 1].XTI = [];
break;
case 362:
if (supbooks.length === 0) {
supbooks[0] = [];
supbooks[0].XTI = [];
}
supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val2);
supbooks.XTI = supbooks.XTI.concat(val2);
break;
case 361:
break;
case 2071:
/* 'BrtAbsPath15' */
case 158:
/* 'BrtBookView' */
case 143:
/* 'BrtBeginBundleShs' */
case 664:
/* 'BrtBeginFnGroup' */
case 353:
break;
/* case 'BrtModelTimeGroupingCalcCol' */
case 3072:
/* 'BrtUid' */
case 3073:
/* 'BrtRevisionPtr' */
case 534:
/* 'BrtBookProtection' */
case 677:
/* 'BrtBookProtectionIso' */
case 157:
/* 'BrtCalcProp' */
case 610:
/* 'BrtCrashRecErr' */
case 2050:
/* 'BrtDecoupledPivotCacheID' */
case 155:
/* 'BrtFileRecover' */
case 548:
/* 'BrtFileSharing' */
case 676:
/* 'BrtFileSharingIso' */
case 128:
/* 'BrtFileVersion' */
case 665:
/* 'BrtFnGroup' */
case 2128:
/* 'BrtModelRelationship' */
case 2125:
/* 'BrtModelTable' */
case 549:
/* 'BrtOleSize' */
case 2053:
/* 'BrtPivotTableRef' */
case 596:
/* 'BrtSmartTagType' */
case 2076:
/* 'BrtTableSlicerCacheID' */
case 2075:
/* 'BrtTableSlicerCacheIDs' */
case 2082:
/* 'BrtTimelineCachePivotCacheID' */
case 397:
/* 'BrtUserBookView' */
case 154:
/* 'BrtWbFactoid' */
case 1117:
/* 'BrtWbProp14' */
case 553:
/* 'BrtWebOpt' */
case 2091:
break;
case 35:
state.push(RT);
pass = true;
break;
case 36:
state.pop();
pass = false;
break;
case 37:
state.push(RT);
pass = true;
break;
case 38:
state.pop();
pass = false;
break;
case 16:
break;
default:
if (R3.T) {
} else if (!pass || opts.WTF && state[state.length - 1] != 37 && state[state.length - 1] != 35) throw new Error("Unexpected record 0x" + RT.toString(16));
}
}, opts);
parse_wb_defaults(wb);
wb.Names = Names;
wb.supbooks = supbooks;
return wb;
}
function parse_wb(data, name, opts) {
if (name.slice(-4) === ".bin") return parse_wb_bin(data, opts);
return parse_wb_xml(data, opts);
}
function parse_ws(data, name, idx, opts, rels, wb, themes, styles2) {
if (name.slice(-4) === ".bin") return parse_ws_bin(data, opts, idx, rels, wb, themes, styles2);
return parse_ws_xml(data, opts, idx, rels, wb, themes, styles2);
}
function parse_cs(data, name, idx, opts, rels, wb, themes, styles2) {
if (name.slice(-4) === ".bin") return parse_cs_bin(data, opts, idx, rels, wb, themes, styles2);
return parse_cs_xml(data, opts, idx, rels, wb, themes, styles2);
}
function parse_ms(data, name, idx, opts, rels, wb, themes, styles2) {
if (name.slice(-4) === ".bin") return parse_ms_bin(data, opts, idx, rels, wb, themes, styles2);
return parse_ms_xml(data, opts, idx, rels, wb, themes, styles2);
}
function parse_ds(data, name, idx, opts, rels, wb, themes, styles2) {
if (name.slice(-4) === ".bin") return parse_ds_bin(data, opts, idx, rels, wb, themes, styles2);
return parse_ds_xml(data, opts, idx, rels, wb, themes, styles2);
}
function parse_sty(data, name, themes, opts) {
if (name.slice(-4) === ".bin") return parse_sty_bin(data, themes, opts);
return parse_sty_xml(data, themes, opts);
}
function parse_sst(data, name, opts) {
if (name.slice(-4) === ".bin") return parse_sst_bin(data, opts);
return parse_sst_xml(data, opts);
}
function parse_cmnt(data, name, opts) {
if (name.slice(-4) === ".bin") return parse_comments_bin(data, opts);
return parse_comments_xml(data, opts);
}
function parse_cc(data, name, opts) {
if (name.slice(-4) === ".bin") return parse_cc_bin(data, name, opts);
return parse_cc_xml(data, name, opts);
}
function parse_xlink(data, rel2, name, opts) {
if (name.slice(-4) === ".bin") return parse_xlink_bin(data, rel2, name, opts);
return parse_xlink_xml(data, rel2, name, opts);
}
function parse_xlmeta(data, name, opts) {
if (name.slice(-4) === ".bin") return parse_xlmeta_bin(data, name, opts);
return parse_xlmeta_xml(data, name, opts);
}
function xlml_parsexmltag(tag, skip_root) {
var words = tag.split(/\s+/);
var z3 = [];
if (!skip_root) z3[0] = words[0];
if (words.length === 1) return z3;
var m4 = tag.match(attregexg2), y4, j3, w3, i7;
if (m4) for (i7 = 0; i7 != m4.length; ++i7) {
y4 = m4[i7].match(attregex2);
if ((j3 = y4[1].indexOf(":")) === -1) z3[y4[1]] = y4[2].slice(1, y4[2].length - 1);
else {
if (y4[1].slice(0, 6) === "xmlns:") w3 = "xmlns" + y4[1].slice(6);
else w3 = y4[1].slice(j3 + 1);
z3[w3] = y4[2].slice(1, y4[2].length - 1);
}
}
return z3;
}
function xlml_parsexmltagobj(tag) {
var words = tag.split(/\s+/);
var z3 = {};
if (words.length === 1) return z3;
var m4 = tag.match(attregexg2), y4, j3, w3, i7;
if (m4) for (i7 = 0; i7 != m4.length; ++i7) {
y4 = m4[i7].match(attregex2);
if ((j3 = y4[1].indexOf(":")) === -1) z3[y4[1]] = y4[2].slice(1, y4[2].length - 1);
else {
if (y4[1].slice(0, 6) === "xmlns:") w3 = "xmlns" + y4[1].slice(6);
else w3 = y4[1].slice(j3 + 1);
z3[w3] = y4[2].slice(1, y4[2].length - 1);
}
}
return z3;
}
function xlml_format(format2, value, date1904) {
var fmt = XLMLFormatMap[format2] || unescapexml(format2);
if (fmt === "General") return SSF_general(value);
return SSF_format(fmt, value, { date1904: !!date1904 });
}
function xlml_set_custprop(Custprops, key, cp, val2) {
var oval = val2;
switch ((cp[0].match(/dt:dt="([\w.]+)"/) || ["", ""])[1]) {
case "boolean":
oval = parsexmlbool(val2);
break;
case "i2":
case "int":
oval = parseInt(val2, 10);
break;
case "r4":
case "float":
oval = parseFloat(val2);
break;
case "date":
case "dateTime.tz":
oval = parseDate(val2);
break;
case "i8":
case "string":
case "fixed":
case "uuid":
case "bin.base64":
break;
default:
throw new Error("bad custprop:" + cp[0]);
}
Custprops[unescapexml(key)] = oval;
}
function safe_format_xlml(cell, nf, o9, date1904) {
if (cell.t === "z") return;
if (!o9 || o9.cellText !== false) try {
if (cell.t === "e") {
cell.w = cell.w || BErr[cell.v];
} else if (nf === "General") {
if (cell.t === "n") {
if ((cell.v | 0) === cell.v) cell.w = cell.v.toString(10);
else cell.w = SSF_general_num(cell.v);
} else cell.w = SSF_general(cell.v);
} else cell.w = xlml_format(nf || "General", cell.v, date1904);
} catch (e9) {
if (o9.WTF) throw e9;
}
try {
var z3 = XLMLFormatMap[nf] || nf || "General";
if (o9.cellNF) cell.z = z3;
if (o9.cellDates && cell.t == "n" && fmt_is_date(z3)) {
var _d = SSF_parse_date_code(cell.v + (date1904 ? 1462 : 0));
if (_d) {
cell.t = "d";
cell.v = new Date(Date.UTC(_d.y, _d.m - 1, _d.d, _d.H, _d.M, _d.S, _d.u));
}
}
} catch (e9) {
if (o9.WTF) throw e9;
}
}
function process_style_xlml(styles2, stag, opts) {
if (opts.cellStyles) {
if (stag.Interior) {
var I3 = stag.Interior;
if (I3.Pattern) I3.patternType = XLMLPatternTypeMap[I3.Pattern] || I3.Pattern;
}
}
styles2[stag.ID] = stag;
}
function parse_xlml_data(xml2, ss, data, cell, base, styles2, csty, row, arrayf, o9, date1904) {
var nf = "General", sid = cell.StyleID, S5 = {};
o9 = o9 || {};
var interiors = [];
var i7 = 0;
if (sid === void 0 && row) sid = row.StyleID;
if (sid === void 0 && csty) sid = csty.StyleID;
while (styles2[sid] !== void 0) {
var ssid = styles2[sid];
if (ssid.nf) nf = ssid.nf;
if (ssid.Interior) interiors.push(ssid.Interior);
if (!ssid.Parent) break;
sid = ssid.Parent;
}
switch (data.Type) {
case "Boolean":
cell.t = "b";
cell.v = parsexmlbool(xml2);
break;
case "String":
cell.t = "s";
cell.r = xlml_fixstr(unescapexml(xml2));
cell.v = xml2.indexOf("<") > -1 ? unescapexml(ss || xml2).replace(/<[^<>]*>/g, "") : cell.r;
break;
case "DateTime":
if (xml2.slice(-1) != "Z") xml2 += "Z";
cell.v = datenum(parseDate(xml2, date1904), date1904);
if (cell.v !== cell.v) cell.v = unescapexml(xml2);
if (!nf || nf == "General") nf = "yyyy-mm-dd";
/* falls through */
case "Number":
if (cell.v === void 0) cell.v = +xml2;
if (!cell.t) cell.t = "n";
break;
case "Error":
cell.t = "e";
cell.v = RBErr[xml2];
if (o9.cellText !== false) cell.w = xml2;
break;
default:
if (xml2 == "" && ss == "") {
cell.t = "z";
} else {
cell.t = "s";
cell.v = xlml_fixstr(ss || xml2);
}
break;
}
safe_format_xlml(cell, nf, o9, date1904);
if (o9.cellFormula !== false) {
if (cell.Formula) {
var fstr = unescapexml(cell.Formula);
if (fstr.charCodeAt(0) == 61) fstr = fstr.slice(1);
cell.f = rc_to_a1(fstr, base);
delete cell.Formula;
if (cell.ArrayRange == "RC") cell.F = rc_to_a1("RC:RC", base);
else if (cell.ArrayRange) {
cell.F = rc_to_a1(cell.ArrayRange, base);
arrayf.push([safe_decode_range(cell.F), cell.F]);
}
} else {
for (i7 = 0; i7 < arrayf.length; ++i7)
if (base.r >= arrayf[i7][0].s.r && base.r <= arrayf[i7][0].e.r) {
if (base.c >= arrayf[i7][0].s.c && base.c <= arrayf[i7][0].e.c)
cell.F = arrayf[i7][1];
}
}
}
if (o9.cellStyles) {
interiors.forEach(function(x2) {
if (!S5.patternType && x2.patternType) S5.patternType = x2.patternType;
});
cell.s = S5;
}
if (cell.StyleID !== void 0) cell.ixfe = cell.StyleID;
}
function xlml_prefix_dname(dname) {
return XLSLblBuiltIn.indexOf("_xlnm." + dname) > -1 ? "_xlnm." + dname : dname;
}
function xlml_clean_comment(comment) {
comment.t = comment.v || "";
comment.t = comment.t.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
comment.v = comment.w = comment.ixfe = void 0;
}
function parse_xlml_xml(d4, _opts) {
var opts = _opts || {};
make_ssf();
var str2 = debom(xlml_normalize(d4));
if (opts.type == "binary" || opts.type == "array" || opts.type == "base64") {
if (typeof $cptable !== "undefined") str2 = $cptable.utils.decode(65001, char_codes(str2));
else str2 = utf8read(str2);
}
var opening = str2.slice(0, 1024).toLowerCase(), ishtml = false;
opening = opening.replace(/".*?"/g, "");
if ((opening.indexOf(">") & 1023) > Math.min(opening.indexOf(",") & 1023, opening.indexOf(";") & 1023)) {
var _o = dup(opts);
_o.type = "string";
return PRN.to_workbook(str2, _o);
}
if (opening.indexOf("= 0) ishtml = true;
});
if (ishtml) return html_to_workbook(str2, opts);
XLMLFormatMap = {
"General Number": "General",
"General Date": table_fmt[22],
"Long Date": "dddd, mmmm dd, yyyy",
"Medium Date": table_fmt[15],
"Short Date": table_fmt[14],
"Long Time": table_fmt[19],
"Medium Time": table_fmt[18],
"Short Time": table_fmt[20],
"Currency": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
"Fixed": table_fmt[2],
"Standard": table_fmt[4],
"Percent": table_fmt[10],
"Scientific": table_fmt[11],
"Yes/No": '"Yes";"Yes";"No";@',
"True/False": '"True";"True";"False";@',
"On/Off": '"Yes";"Yes";"No";@'
};
var Rn;
var state = [], tmp;
if (DENSE != null && opts.dense == null) opts.dense = DENSE;
var sheets = {}, sheetnames = [], cursheet = {}, sheetname = "";
if (opts.dense) cursheet["!data"] = [];
var cell = {}, row = {};
var dtag = xlml_parsexmltag(''), didx = 0;
var c6 = 0, r8 = 0;
var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } };
var styles2 = {}, stag = {};
var ss = "", fidx = 0;
var merges = [];
var Props = {}, Custprops = {}, pidx = 0, cp = [];
var comments = [], comment = {};
var cstys = [], csty, seencol = false;
var arrayf = [];
var rowinfo = [], rowobj = {}, cc = 0, rr = 0;
var Workbook = { Sheets: [], WBProps: { date1904: false } }, wsprops = {};
xlmlregex.lastIndex = 0;
str2 = str_remove_ng(str2, "");
var raw_Rn3 = "";
while (Rn = xlmlregex.exec(str2)) switch (Rn[3] = (raw_Rn3 = Rn[3]).toLowerCase()) {
case "data":
if (raw_Rn3 == "data") {
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]);
break;
}
if (state[state.length - 1][1]) break;
if (Rn[1] === "/") parse_xlml_data(str2.slice(didx, Rn.index), ss, dtag, state[state.length - 1][0] == /*"Comment"*/
"comment" ? comment : cell, { c: c6, r: r8 }, styles2, cstys[c6], row, arrayf, opts, Workbook.WBProps.date1904);
else {
ss = "";
dtag = xlml_parsexmltag(Rn[0]);
didx = Rn.index + Rn[0].length;
}
break;
case "cell":
if (Rn[1] === "/") {
if (comments.length > 0) cell.c = comments;
if ((!opts.sheetRows || opts.sheetRows > r8) && cell.v !== void 0) {
if (opts.dense) {
if (!cursheet["!data"][r8]) cursheet["!data"][r8] = [];
cursheet["!data"][r8][c6] = cell;
} else cursheet[encode_col(c6) + encode_row(r8)] = cell;
}
if (cell.HRef) {
cell.l = { Target: unescapexml(cell.HRef) };
if (cell.HRefScreenTip) cell.l.Tooltip = cell.HRefScreenTip;
delete cell.HRef;
delete cell.HRefScreenTip;
}
if (cell.MergeAcross || cell.MergeDown) {
cc = c6 + (parseInt(cell.MergeAcross, 10) | 0);
rr = r8 + (parseInt(cell.MergeDown, 10) | 0);
if (cc > c6 || rr > r8) merges.push({ s: { c: c6, r: r8 }, e: { c: cc, r: rr } });
}
if (!opts.sheetStubs) {
if (cell.MergeAcross) c6 = cc + 1;
else ++c6;
} else if (cell.MergeAcross || cell.MergeDown) {
for (var cma = c6; cma <= cc; ++cma) {
for (var cmd = r8; cmd <= rr; ++cmd) {
if (cma > c6 || cmd > r8) {
if (opts.dense) {
if (!cursheet["!data"][cmd]) cursheet["!data"][cmd] = [];
cursheet["!data"][cmd][cma] = { t: "z" };
} else cursheet[encode_col(cma) + encode_row(cmd)] = { t: "z" };
}
}
}
c6 = cc + 1;
} else ++c6;
} else {
cell = xlml_parsexmltagobj(Rn[0]);
if (cell.Index) c6 = +cell.Index - 1;
if (c6 < refguess.s.c) refguess.s.c = c6;
if (c6 > refguess.e.c) refguess.e.c = c6;
if (Rn[0].slice(-2) === "/>") ++c6;
comments = [];
}
break;
case "row":
if (Rn[1] === "/" || Rn[0].slice(-2) === "/>") {
if (r8 < refguess.s.r) refguess.s.r = r8;
if (r8 > refguess.e.r) refguess.e.r = r8;
if (Rn[0].slice(-2) === "/>") {
row = xlml_parsexmltag(Rn[0]);
if (row.Index) r8 = +row.Index - 1;
}
c6 = 0;
++r8;
} else {
row = xlml_parsexmltag(Rn[0]);
if (row.Index) r8 = +row.Index - 1;
rowobj = {};
if (row.AutoFitHeight == "0" || row.Height) {
rowobj.hpx = parseInt(row.Height, 10);
rowobj.hpt = px2pt(rowobj.hpx);
rowinfo[r8] = rowobj;
}
if (row.Hidden == "1") {
rowobj.hidden = true;
rowinfo[r8] = rowobj;
}
}
break;
case "worksheet":
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
sheetnames.push(sheetname);
if (refguess.s.r <= refguess.e.r && refguess.s.c <= refguess.e.c) {
cursheet["!ref"] = encode_range(refguess);
if (opts.sheetRows && opts.sheetRows <= refguess.e.r) {
cursheet["!fullref"] = cursheet["!ref"];
refguess.e.r = opts.sheetRows - 1;
cursheet["!ref"] = encode_range(refguess);
}
}
if (merges.length) cursheet["!merges"] = merges;
if (cstys.length > 0) cursheet["!cols"] = cstys;
if (rowinfo.length > 0) cursheet["!rows"] = rowinfo;
sheets[sheetname] = cursheet;
} else {
refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } };
r8 = c6 = 0;
state.push([Rn[3], false]);
tmp = xlml_parsexmltag(Rn[0]);
sheetname = unescapexml(tmp.Name);
cursheet = {};
if (opts.dense) cursheet["!data"] = [];
merges = [];
arrayf = [];
rowinfo = [];
wsprops = { name: sheetname, Hidden: 0 };
Workbook.Sheets.push(wsprops);
}
break;
case "table":
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
} else if (Rn[0].slice(-2) == "/>") break;
else {
state.push([Rn[3], false]);
cstys = [];
seencol = false;
}
break;
case "style":
if (Rn[1] === "/") process_style_xlml(styles2, stag, opts);
else stag = xlml_parsexmltag(Rn[0]);
break;
case "numberformat":
stag.nf = unescapexml(xlml_parsexmltag(Rn[0]).Format || "General");
if (XLMLFormatMap[stag.nf]) stag.nf = XLMLFormatMap[stag.nf];
for (var ssfidx = 0; ssfidx != 392; ++ssfidx) if (table_fmt[ssfidx] == stag.nf) break;
if (ssfidx == 392) {
for (ssfidx = 57; ssfidx != 392; ++ssfidx) if (table_fmt[ssfidx] == null) {
SSF__load(stag.nf, ssfidx);
break;
}
}
break;
case "column":
if (state[state.length - 1][0] !== /*'Table'*/
"table") break;
if (Rn[1] === "/") break;
csty = xlml_parsexmltag(Rn[0]);
if (csty.Hidden) {
csty.hidden = true;
delete csty.Hidden;
}
if (csty.Width) csty.wpx = parseInt(csty.Width, 10);
if (!seencol && csty.wpx > 10) {
seencol = true;
MDW = DEF_MDW;
for (var _col = 0; _col < cstys.length; ++_col) if (cstys[_col]) process_col(cstys[_col]);
}
if (seencol) process_col(csty);
cstys[csty.Index - 1 || cstys.length] = csty;
for (var i7 = 0; i7 < +csty.Span; ++i7) cstys[cstys.length] = dup(csty);
break;
case "namedrange":
if (Rn[1] === "/") break;
if (!Workbook.Names) Workbook.Names = [];
var _NamedRange = parsexmltag(Rn[0]);
var _DefinedName = {
Name: xlml_prefix_dname(_NamedRange.Name),
Ref: rc_to_a1(_NamedRange.RefersTo.slice(1), { r: 0, c: 0 })
};
if (Workbook.Sheets.length > 0) _DefinedName.Sheet = Workbook.Sheets.length - 1;
Workbook.Names.push(_DefinedName);
break;
case "namedcell":
break;
case "b":
break;
case "i":
break;
case "u":
break;
case "s":
break;
case "em":
break;
case "h2":
break;
case "h3":
break;
case "sub":
break;
case "sup":
break;
case "span":
break;
case "alignment":
break;
case "borders":
break;
case "border":
break;
case "font":
if (Rn[0].slice(-2) === "/>") break;
else if (Rn[1] === "/") ss += str2.slice(fidx, Rn.index);
else fidx = Rn.index + Rn[0].length;
break;
case "interior":
if (!opts.cellStyles) break;
stag.Interior = xlml_parsexmltag(Rn[0]);
break;
case "protection":
break;
case "author":
case "title":
case "description":
case "created":
case "keywords":
case "subject":
case "category":
case "company":
case "lastauthor":
case "lastsaved":
case "lastprinted":
case "version":
case "revision":
case "totaltime":
case "hyperlinkbase":
case "manager":
case "contentstatus":
case "identifier":
case "language":
case "appname":
if (Rn[0].slice(-2) === "/>") break;
else if (Rn[1] === "/") xlml_set_prop(Props, raw_Rn3, str2.slice(pidx, Rn.index));
else pidx = Rn.index + Rn[0].length;
break;
case "paragraphs":
break;
case "styles":
case "workbook":
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
} else state.push([Rn[3], false]);
break;
case "comment":
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
xlml_clean_comment(comment);
comments.push(comment);
} else {
state.push([Rn[3], false]);
tmp = xlml_parsexmltag(Rn[0]);
if (!parsexmlbool(tmp["ShowAlways"] || "0")) comments.hidden = true;
comment = { a: tmp.Author };
}
break;
case "autofilter":
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
var AutoFilter = xlml_parsexmltag(Rn[0]);
cursheet["!autofilter"] = { ref: rc_to_a1(AutoFilter.Range).replace(/\$/g, "") };
state.push([Rn[3], true]);
}
break;
case "name":
break;
case "datavalidation":
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
} else {
if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]);
}
break;
case "pixelsperinch":
break;
case "componentoptions":
case "documentproperties":
case "customdocumentproperties":
case "officedocumentsettings":
case "pivottable":
case "pivotcache":
case "names":
case "mapinfo":
case "pagebreaks":
case "querytable":
case "sorting":
case "schema":
//case 'data' /*case 'data'*/:
case "conditionalformatting":
case "smarttagtype":
case "smarttags":
case "excelworkbook":
case "workbookoptions":
case "worksheetoptions":
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|"));
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]);
break;
case "null":
break;
default:
if (state.length == 0 && Rn[3] == "document") return parse_fods(str2, opts);
if (state.length == 0 && Rn[3] == "uof") return parse_fods(str2, opts);
var seen = true;
switch (state[state.length - 1][0]) {
/* OfficeDocumentSettings */
case "officedocumentsettings":
switch (Rn[3]) {
case "allowpng":
break;
case "removepersonalinformation":
break;
case "downloadcomponents":
break;
case "locationofcomponents":
break;
case "colors":
break;
case "color":
break;
case "index":
break;
case "rgb":
break;
case "targetscreensize":
break;
case "readonlyrecommended":
break;
default:
seen = false;
}
break;
/* ComponentOptions */
case "componentoptions":
switch (Rn[3]) {
case "toolbar":
break;
case "hideofficelogo":
break;
case "spreadsheetautofit":
break;
case "label":
break;
case "caption":
break;
case "maxheight":
break;
case "maxwidth":
break;
case "nextsheetnumber":
break;
default:
seen = false;
}
break;
/* ExcelWorkbook */
case "excelworkbook":
switch (Rn[3]) {
case "date1904":
Workbook.WBProps.date1904 = true;
break;
case "hidehorizontalscrollbar":
break;
case "hideverticalscrollbar":
break;
case "hideworkbooktabs":
break;
case "windowheight":
break;
case "windowwidth":
break;
case "windowtopx":
break;
case "windowtopy":
break;
case "tabratio":
break;
case "protectstructure":
break;
case "protectwindow":
break;
case "protectwindows":
break;
case "activesheet":
break;
case "displayinknotes":
break;
case "firstvisiblesheet":
break;
case "supbook":
break;
case "sheetname":
break;
case "sheetindex":
break;
case "sheetindexfirst":
break;
case "sheetindexlast":
break;
case "dll":
break;
case "acceptlabelsinformulas":
break;
case "donotsavelinkvalues":
break;
case "iteration":
break;
case "maxiterations":
break;
case "maxchange":
break;
case "path":
break;
case "xct":
break;
case "count":
break;
case "selectedsheets":
break;
case "calculation":
break;
case "uncalced":
break;
case "startupprompt":
break;
case "crn":
break;
case "externname":
break;
case "formula":
break;
case "colfirst":
break;
case "collast":
break;
case "wantadvise":
break;
case "boolean":
break;
case "error":
break;
case "text":
break;
case "ole":
break;
case "noautorecover":
break;
case "publishobjects":
break;
case "donotcalculatebeforesave":
break;
case "number":
break;
case "refmoder1c1":
break;
case "embedsavesmarttags":
break;
default:
seen = false;
}
break;
/* WorkbookOptions */
case "workbookoptions":
switch (Rn[3]) {
case "owcversion":
break;
case "height":
break;
case "width":
break;
default:
seen = false;
}
break;
/* WorksheetOptions */
case "worksheetoptions":
switch (Rn[3]) {
case "visible":
if (Rn[0].slice(-2) === "/>") {
} else if (Rn[1] === "/") switch (str2.slice(pidx, Rn.index)) {
case "SheetHidden":
wsprops.Hidden = 1;
break;
case "SheetVeryHidden":
wsprops.Hidden = 2;
break;
}
else pidx = Rn.index + Rn[0].length;
break;
case "header":
if (!cursheet["!margins"]) default_margins(cursheet["!margins"] = {}, "xlml");
if (!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet["!margins"].header = +parsexmltag(Rn[0]).Margin;
break;
case "footer":
if (!cursheet["!margins"]) default_margins(cursheet["!margins"] = {}, "xlml");
if (!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet["!margins"].footer = +parsexmltag(Rn[0]).Margin;
break;
case "pagemargins":
var pagemargins = parsexmltag(Rn[0]);
if (!cursheet["!margins"]) default_margins(cursheet["!margins"] = {}, "xlml");
if (!isNaN(+pagemargins.Top)) cursheet["!margins"].top = +pagemargins.Top;
if (!isNaN(+pagemargins.Left)) cursheet["!margins"].left = +pagemargins.Left;
if (!isNaN(+pagemargins.Right)) cursheet["!margins"].right = +pagemargins.Right;
if (!isNaN(+pagemargins.Bottom)) cursheet["!margins"].bottom = +pagemargins.Bottom;
break;
case "displayrighttoleft":
if (!Workbook.Views) Workbook.Views = [];
if (!Workbook.Views[0]) Workbook.Views[0] = {};
Workbook.Views[0].RTL = true;
break;
case "freezepanes":
break;
case "frozennosplit":
break;
case "splithorizontal":
case "splitvertical":
break;
case "donotdisplaygridlines":
break;
case "activerow":
break;
case "activecol":
break;
case "toprowbottompane":
break;
case "leftcolumnrightpane":
break;
case "unsynced":
break;
case "print":
break;
case "printerrors":
break;
case "panes":
break;
case "scale":
break;
case "pane":
break;
case "number":
break;
case "layout":
break;
case "pagesetup":
break;
case "selected":
break;
case "protectobjects":
break;
case "enableselection":
break;
case "protectscenarios":
break;
case "validprinterinfo":
break;
case "horizontalresolution":
break;
case "verticalresolution":
break;
case "numberofcopies":
break;
case "activepane":
break;
case "toprowvisible":
break;
case "leftcolumnvisible":
break;
case "fittopage":
break;
case "rangeselection":
break;
case "papersizeindex":
break;
case "pagelayoutzoom":
break;
case "pagebreakzoom":
break;
case "filteron":
break;
case "fitwidth":
break;
case "fitheight":
break;
case "commentslayout":
break;
case "zoom":
break;
case "lefttoright":
break;
case "gridlines":
break;
case "allowsort":
break;
case "allowfilter":
break;
case "allowinsertrows":
break;
case "allowdeleterows":
break;
case "allowinsertcols":
break;
case "allowdeletecols":
break;
case "allowinserthyperlinks":
break;
case "allowformatcells":
break;
case "allowsizecols":
break;
case "allowsizerows":
break;
case "nosummaryrowsbelowdetail":
if (!cursheet["!outline"]) cursheet["!outline"] = {};
cursheet["!outline"].above = true;
break;
case "tabcolorindex":
break;
case "donotdisplayheadings":
break;
case "showpagelayoutzoom":
break;
case "nosummarycolumnsrightdetail":
if (!cursheet["!outline"]) cursheet["!outline"] = {};
cursheet["!outline"].left = true;
break;
case "blackandwhite":
break;
case "donotdisplayzeros":
break;
case "displaypagebreak":
break;
case "rowcolheadings":
break;
case "donotdisplayoutline":
break;
case "noorientation":
break;
case "allowusepivottables":
break;
case "zeroheight":
break;
case "viewablerange":
break;
case "selection":
break;
case "protectcontents":
break;
default:
seen = false;
}
break;
/* PivotTable */
case "pivottable":
case "pivotcache":
switch (Rn[3]) {
case "immediateitemsondrop":
break;
case "showpagemultipleitemlabel":
break;
case "compactrowindent":
break;
case "location":
break;
case "pivotfield":
break;
case "orientation":
break;
case "layoutform":
break;
case "layoutsubtotallocation":
break;
case "layoutcompactrow":
break;
case "position":
break;
case "pivotitem":
break;
case "datatype":
break;
case "datafield":
break;
case "sourcename":
break;
case "parentfield":
break;
case "ptlineitems":
break;
case "ptlineitem":
break;
case "countofsameitems":
break;
case "item":
break;
case "itemtype":
break;
case "ptsource":
break;
case "cacheindex":
break;
case "consolidationreference":
break;
case "filename":
break;
case "reference":
break;
case "nocolumngrand":
break;
case "norowgrand":
break;
case "blanklineafteritems":
break;
case "hidden":
break;
case "subtotal":
break;
case "basefield":
break;
case "mapchilditems":
break;
case "function":
break;
case "refreshonfileopen":
break;
case "printsettitles":
break;
case "mergelabels":
break;
case "defaultversion":
break;
case "refreshname":
break;
case "refreshdate":
break;
case "refreshdatecopy":
break;
case "versionlastrefresh":
break;
case "versionlastupdate":
break;
case "versionupdateablemin":
break;
case "versionrefreshablemin":
break;
case "calculation":
break;
default:
seen = false;
}
break;
/* PageBreaks */
case "pagebreaks":
switch (Rn[3]) {
case "colbreaks":
break;
case "colbreak":
break;
case "rowbreaks":
break;
case "rowbreak":
break;
case "colstart":
break;
case "colend":
break;
case "rowend":
break;
default:
seen = false;
}
break;
/* AutoFilter */
case "autofilter":
switch (Rn[3]) {
case "autofiltercolumn":
break;
case "autofiltercondition":
break;
case "autofilterand":
break;
case "autofilteror":
break;
default:
seen = false;
}
break;
/* QueryTable */
case "querytable":
switch (Rn[3]) {
case "id":
break;
case "autoformatfont":
break;
case "autoformatpattern":
break;
case "querysource":
break;
case "querytype":
break;
case "enableredirections":
break;
case "refreshedinxl9":
break;
case "urlstring":
break;
case "htmltables":
break;
case "connection":
break;
case "commandtext":
break;
case "refreshinfo":
break;
case "notitles":
break;
case "nextid":
break;
case "columninfo":
break;
case "overwritecells":
break;
case "donotpromptforfile":
break;
case "textwizardsettings":
break;
case "source":
break;
case "number":
break;
case "decimal":
break;
case "thousandseparator":
break;
case "trailingminusnumbers":
break;
case "formatsettings":
break;
case "fieldtype":
break;
case "delimiters":
break;
case "tab":
break;
case "comma":
break;
case "autoformatname":
break;
case "versionlastedit":
break;
case "versionlastrefresh":
break;
default:
seen = false;
}
break;
case "datavalidation":
switch (Rn[3]) {
case "range":
break;
case "type":
break;
case "min":
break;
case "max":
break;
case "sort":
break;
case "descending":
break;
case "order":
break;
case "casesensitive":
break;
case "value":
break;
case "errorstyle":
break;
case "errormessage":
break;
case "errortitle":
break;
case "inputmessage":
break;
case "inputtitle":
break;
case "combohide":
break;
case "inputhide":
break;
case "condition":
break;
case "qualifier":
break;
case "useblank":
break;
case "value1":
break;
case "value2":
break;
case "format":
break;
case "cellrangelist":
break;
default:
seen = false;
}
break;
case "sorting":
case "conditionalformatting":
switch (Rn[3]) {
case "range":
break;
case "type":
break;
case "min":
break;
case "max":
break;
case "sort":
break;
case "descending":
break;
case "order":
break;
case "casesensitive":
break;
case "value":
break;
case "errorstyle":
break;
case "errormessage":
break;
case "errortitle":
break;
case "cellrangelist":
break;
case "inputmessage":
break;
case "inputtitle":
break;
case "combohide":
break;
case "inputhide":
break;
case "condition":
break;
case "qualifier":
break;
case "useblank":
break;
case "value1":
break;
case "value2":
break;
case "format":
break;
default:
seen = false;
}
break;
/* MapInfo (schema) */
case "mapinfo":
case "schema":
case "data":
switch (Rn[3]) {
case "map":
break;
case "entry":
break;
case "range":
break;
case "xpath":
break;
case "field":
break;
case "xsdtype":
break;
case "filteron":
break;
case "aggregate":
break;
case "elementtype":
break;
case "attributetype":
break;
/* These are from xsd (XML Schema Definition) */
case "schema":
case "element":
case "complextype":
case "datatype":
case "all":
case "attribute":
case "extends":
break;
case "row":
break;
default:
seen = false;
}
break;
/* SmartTags (can be anything) */
case "smarttags":
break;
default:
seen = false;
break;
}
if (seen) break;
if (Rn[3].match(/!\[CDATA/)) break;
if (!state[state.length - 1][1]) throw "Unrecognized tag: " + Rn[3] + "|" + state.join("|");
if (state[state.length - 1][0] === /*'CustomDocumentProperties'*/
"customdocumentproperties") {
if (Rn[0].slice(-2) === "/>") break;
else if (Rn[1] === "/") xlml_set_custprop(Custprops, raw_Rn3, cp, str2.slice(pidx, Rn.index));
else {
cp = Rn;
pidx = Rn.index + Rn[0].length;
}
break;
}
if (opts.WTF) throw "Unrecognized tag: " + Rn[3] + "|" + state.join("|");
}
var out = {};
if (!opts.bookSheets && !opts.bookProps) out.Sheets = sheets;
out.SheetNames = sheetnames;
out.Workbook = Workbook;
out.SSF = dup(table_fmt);
out.Props = Props;
out.Custprops = Custprops;
out.bookType = "xlml";
return out;
}
function parse_xlml(data, opts) {
fix_read_opts(opts = opts || {});
switch (opts.type || "base64") {
case "base64":
return parse_xlml_xml(Base64_decode(data), opts);
case "binary":
case "buffer":
case "file":
return parse_xlml_xml(data, opts);
case "array":
return parse_xlml_xml(a2s(data), opts);
}
}
function parse_compobj(obj) {
var v4 = {};
var o9 = obj.content;
o9.l = 28;
v4.AnsiUserType = o9.read_shift(0, "lpstr-ansi");
v4.AnsiClipboardFormat = parse_ClipboardFormatOrAnsiString(o9);
if (o9.length - o9.l <= 4) return v4;
var m4 = o9.read_shift(4);
if (m4 == 0 || m4 > 40) return v4;
o9.l -= 4;
v4.Reserved1 = o9.read_shift(0, "lpstr-ansi");
if (o9.length - o9.l <= 4) return v4;
m4 = o9.read_shift(4);
if (m4 !== 1907505652) return v4;
v4.UnicodeClipboardFormat = parse_ClipboardFormatOrUnicodeString(o9);
m4 = o9.read_shift(4);
if (m4 == 0 || m4 > 40) return v4;
o9.l -= 4;
v4.Reserved2 = o9.read_shift(0, "lpwstr");
}
function slurp(RecordType, R3, blob, length, opts) {
var l5 = length;
var bufs = [];
var d4 = blob.slice(blob.l, blob.l + l5);
if (opts && opts.enc && opts.enc.insitu && d4.length > 0) switch (RecordType) {
case 9:
case 521:
case 1033:
case 2057:
case 47:
case 405:
case 225:
case 406:
case 312:
case 404:
case 10:
break;
case 133:
break;
default:
opts.enc.insitu(d4);
}
bufs.push(d4);
blob.l += l5;
var nextrt = __readUInt16LE(blob, blob.l), next = XLSRecordEnum[nextrt];
var start = 0;
while (next != null && CONTINUE_RT.indexOf(nextrt) > -1) {
l5 = __readUInt16LE(blob, blob.l + 2);
start = blob.l + 4;
if (nextrt == 2066) start += 4;
else if (nextrt == 2165 || nextrt == 2175) {
start += 12;
}
d4 = blob.slice(start, blob.l + 4 + l5);
bufs.push(d4);
blob.l += 4 + l5;
next = XLSRecordEnum[nextrt = __readUInt16LE(blob, blob.l)];
}
var b4 = bconcat(bufs);
prep_blob(b4, 0);
var ll = 0;
b4.lens = [];
for (var j3 = 0; j3 < bufs.length; ++j3) {
b4.lens.push(ll);
ll += bufs[j3].length;
}
if (b4.length < length) throw "XLS Record 0x" + RecordType.toString(16) + " Truncated: " + b4.length + " < " + length;
return R3.f(b4, b4.length, opts);
}
function safe_format_xf(p4, opts, date1904) {
if (p4.t === "z") return;
if (!p4.XF) return;
var fmtid = 0;
try {
fmtid = p4.z || p4.XF.numFmtId || 0;
if (opts.cellNF && p4.z == null) p4.z = table_fmt[fmtid];
} catch (e9) {
if (opts.WTF) throw e9;
}
if (!opts || opts.cellText !== false) try {
if (p4.t === "e") {
p4.w = p4.w || BErr[p4.v];
} else if (fmtid === 0 || fmtid == "General") {
if (p4.t === "n") {
if ((p4.v | 0) === p4.v) p4.w = p4.v.toString(10);
else p4.w = SSF_general_num(p4.v);
} else p4.w = SSF_general(p4.v);
} else p4.w = SSF_format(fmtid, p4.v, { date1904: !!date1904, dateNF: opts && opts.dateNF });
} catch (e9) {
if (opts.WTF) throw e9;
}
if (opts.cellDates && fmtid && p4.t == "n" && fmt_is_date(table_fmt[fmtid] || String(fmtid))) {
var _d = SSF_parse_date_code(p4.v + (date1904 ? 1462 : 0));
if (_d) {
p4.t = "d";
p4.v = new Date(Date.UTC(_d.y, _d.m - 1, _d.d, _d.H, _d.M, _d.S, _d.u));
}
}
}
function make_cell(val2, ixfe, t6) {
return { v: val2, ixfe, t: t6 };
}
function parse_workbook(blob, options) {
var wb = { opts: {} };
var Sheets = {};
if (DENSE != null && options.dense == null) options.dense = DENSE;
var out = {};
if (options.dense) out["!data"] = [];
var Directory = {};
var range2 = {};
var last_formula = null;
var sst = [];
var cur_sheet = "";
var Preamble = {};
var lastcell, last_cell = "", cc, cmnt, rngC, rngR;
var sharedf = {};
var arrayf = [];
var temp_val;
var country;
var XFs = [];
var palette = [];
var Workbook = { Sheets: [], WBProps: { date1904: false }, Views: [{}] }, wsprops = {};
var biff4w = false;
var get_rgb = function getrgb(icv) {
if (icv < 8) return XLSIcv[icv];
if (icv < 64) return palette[icv - 8] || XLSIcv[icv];
return XLSIcv[icv];
};
var process_cell_style = function pcs(line, options2) {
var xfd = line.XF.data;
if (!xfd || !xfd.patternType || !options2 || !options2.cellStyles) return;
line.s = {};
line.s.patternType = xfd.patternType;
var t6;
if (t6 = rgb2Hex(get_rgb(xfd.icvFore))) {
line.s.fgColor = { rgb: t6 };
}
if (t6 = rgb2Hex(get_rgb(xfd.icvBack))) {
line.s.bgColor = { rgb: t6 };
}
};
var addcell = function addcell2(cell, line, options2) {
if (!biff4w && file_depth > 1) return;
if (options2.sheetRows && cell.r >= options2.sheetRows) return;
if (options2.cellStyles && line.XF && line.XF.data) process_cell_style(line, options2);
delete line.ixfe;
delete line.XF;
lastcell = cell;
last_cell = encode_cell(cell);
if (!range2 || !range2.s || !range2.e) range2 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
if (cell.r < range2.s.r) range2.s.r = cell.r;
if (cell.c < range2.s.c) range2.s.c = cell.c;
if (cell.r + 1 > range2.e.r) range2.e.r = cell.r + 1;
if (cell.c + 1 > range2.e.c) range2.e.c = cell.c + 1;
if (options2.cellFormula && line.f) {
for (var afi = 0; afi < arrayf.length; ++afi) {
if (arrayf[afi][0].s.c > cell.c || arrayf[afi][0].s.r > cell.r) continue;
if (arrayf[afi][0].e.c < cell.c || arrayf[afi][0].e.r < cell.r) continue;
line.F = encode_range(arrayf[afi][0]);
if (arrayf[afi][0].s.c != cell.c || arrayf[afi][0].s.r != cell.r) delete line.f;
if (line.f) line.f = "" + stringify_formula(arrayf[afi][1], range2, cell, supbooks, opts);
break;
}
}
{
if (options2.dense) {
if (!out["!data"][cell.r]) out["!data"][cell.r] = [];
out["!data"][cell.r][cell.c] = line;
} else out[last_cell] = line;
}
};
var opts = {
enc: false,
// encrypted
sbcch: 0,
// cch in the preceding SupBook
snames: [],
// sheetnames
sharedf,
// shared formulae by address
arrayf,
// array formulae array
rrtabid: [],
// RRTabId
lastuser: "",
// Last User from WriteAccess
biff: 8,
// BIFF version
codepage: 0,
// CP from CodePage record
winlocked: 0,
// fLockWn from WinProtect
cellStyles: !!options && !!options.cellStyles,
WTF: !!options && !!options.wtf
};
if (options.password) opts.password = options.password;
var themes;
var merges = [];
var objects = [];
var colinfo = [], rowinfo = [];
var seencol = false;
var supbooks = [];
supbooks.SheetNames = opts.snames;
supbooks.sharedf = opts.sharedf;
supbooks.arrayf = opts.arrayf;
supbooks.names = [];
supbooks.XTI = [];
var last_RT = 0;
var file_depth = 0;
var BIFF2Fmt = 0, BIFF2FmtTable = [];
var FilterDatabases = [];
var last_lbl;
opts.codepage = 1200;
set_cp(1200);
var seen_codepage = false;
while (blob.l < blob.length - 1) {
var s6 = blob.l;
var RecordType = blob.read_shift(2);
if (RecordType === 0 && last_RT === 10) break;
var length = blob.l === blob.length ? 0 : blob.read_shift(2);
var R3 = XLSRecordEnum[RecordType];
if (file_depth == 0 && [9, 521, 1033, 2057].indexOf(RecordType) == -1) break;
if (R3 && R3.f) {
if (options.bookSheets) {
if (last_RT === 133 && RecordType !== 133) break;
}
last_RT = RecordType;
if (R3.r === 2 || R3.r == 12) {
var rt = blob.read_shift(2);
length -= 2;
if (!opts.enc && rt !== RecordType && ((rt & 255) << 8 | rt >> 8) !== RecordType) throw new Error("rt mismatch: " + rt + "!=" + RecordType);
if (R3.r == 12) {
blob.l += 10;
length -= 10;
}
}
var val2 = {};
if (RecordType === 10) val2 = /*::(*/
R3.f(blob, length, opts);
else val2 = /*::(*/
slurp(RecordType, R3, blob, length, opts);
if (file_depth == 0 && [9, 521, 1033, 2057].indexOf(last_RT) === -1) continue;
switch (RecordType) {
case 34:
wb.opts.Date1904 = Workbook.WBProps.date1904 = val2;
break;
case 134:
wb.opts.WriteProtect = true;
break;
case 47:
if (!opts.enc) blob.l = 0;
opts.enc = val2;
if (!options.password) throw new Error("File is password-protected");
if (val2.valid == null) throw new Error("Encryption scheme unsupported");
if (!val2.valid) throw new Error("Password is incorrect");
break;
case 92:
opts.lastuser = val2;
break;
case 66:
var cpval = Number(val2);
switch (cpval) {
case 21010:
cpval = 1200;
break;
case 32768:
cpval = 1e4;
break;
case 32769:
cpval = 1252;
break;
}
set_cp(opts.codepage = cpval);
seen_codepage = true;
break;
case 317:
opts.rrtabid = val2;
break;
case 25:
opts.winlocked = val2;
break;
case 439:
wb.opts["RefreshAll"] = val2;
break;
case 12:
wb.opts["CalcCount"] = val2;
break;
case 16:
wb.opts["CalcDelta"] = val2;
break;
case 17:
wb.opts["CalcIter"] = val2;
break;
case 13:
wb.opts["CalcMode"] = val2;
break;
case 14:
wb.opts["CalcPrecision"] = val2;
break;
case 95:
wb.opts["CalcSaveRecalc"] = val2;
break;
case 15:
opts.CalcRefMode = val2;
break;
// TODO: implement R1C1
case 2211:
wb.opts.FullCalc = val2;
break;
case 129:
if (val2.fDialog) out["!type"] = "dialog";
if (!val2.fBelow) (out["!outline"] || (out["!outline"] = {})).above = true;
if (!val2.fRight) (out["!outline"] || (out["!outline"] = {})).left = true;
break;
// TODO
case 67:
/* BIFF2XF */
case 579:
/* BIFF3XF */
case 1091:
/* BIFF4XF */
case 224:
XFs.push(val2);
break;
case 430:
supbooks.push([val2]);
supbooks[supbooks.length - 1].XTI = [];
break;
case 35:
case 547:
supbooks[supbooks.length - 1].push(val2);
break;
case 24:
case 536:
last_lbl = {
Name: val2.Name,
Ref: stringify_formula(val2.rgce, range2, null, supbooks, opts)
};
if (val2.itab > 0) last_lbl.Sheet = val2.itab - 1;
supbooks.names.push(last_lbl);
if (!supbooks[0]) {
supbooks[0] = [];
supbooks[0].XTI = [];
}
supbooks[supbooks.length - 1].push(val2);
if (val2.Name == "_xlnm._FilterDatabase" && val2.itab > 0) {
if (val2.rgce && val2.rgce[0] && val2.rgce[0][0] && val2.rgce[0][0][0] == "PtgArea3d")
FilterDatabases[val2.itab - 1] = { ref: encode_range(val2.rgce[0][0][1][2]) };
}
break;
case 22:
opts.ExternCount = val2;
break;
case 23:
if (supbooks.length == 0) {
supbooks[0] = [];
supbooks[0].XTI = [];
}
supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val2);
supbooks.XTI = supbooks.XTI.concat(val2);
break;
case 2196:
if (opts.biff < 8) break;
if (last_lbl != null) last_lbl.Comment = val2[1];
break;
case 18:
out["!protect"] = val2;
break;
/* for sheet or book */
case 19:
if (val2 !== 0 && opts.WTF) console.error("Password verifier: " + val2);
break;
case 133:
{
Directory[opts.biff == 4 ? opts.snames.length : val2.pos] = val2;
opts.snames.push(val2.name);
}
break;
case 10:
{
if (--file_depth ? !biff4w : biff4w) break;
if (range2.e) {
if (range2.e.r > 0 && range2.e.c > 0) {
range2.e.r--;
range2.e.c--;
out["!ref"] = encode_range(range2);
if (options.sheetRows && options.sheetRows <= range2.e.r) {
var tmpri = range2.e.r;
range2.e.r = options.sheetRows - 1;
out["!fullref"] = out["!ref"];
out["!ref"] = encode_range(range2);
range2.e.r = tmpri;
}
range2.e.r++;
range2.e.c++;
}
if (merges.length > 0) out["!merges"] = merges;
if (objects.length > 0) out["!objects"] = objects;
if (colinfo.length > 0) out["!cols"] = colinfo;
if (rowinfo.length > 0) out["!rows"] = rowinfo;
Workbook.Sheets.push(wsprops);
}
if (cur_sheet === "") Preamble = out;
else Sheets[cur_sheet] = out;
out = {};
if (options.dense) out["!data"] = [];
}
break;
case 9:
case 521:
case 1033:
case 2057:
{
if (opts.biff === 8) opts.biff = {
9: 2,
521: 3,
1033: 4
}[RecordType] || {
512: 2,
768: 3,
1024: 4,
1280: 5,
1536: 8,
2: 2,
7: 2
}[val2.BIFFVer] || 8;
opts.biffguess = val2.BIFFVer == 0;
if (val2.BIFFVer == 0 && val2.dt == 4096) {
opts.biff = 5;
seen_codepage = true;
set_cp(opts.codepage = 28591);
}
if (opts.biff == 4 && val2.dt & 256) biff4w = true;
if (opts.biff == 8 && val2.BIFFVer == 0 && val2.dt == 16) opts.biff = 2;
if (file_depth++ && !biff4w) break;
out = {};
if (options.dense) out["!data"] = [];
if (opts.biff < 8 && !seen_codepage) {
seen_codepage = true;
set_cp(opts.codepage = options.codepage || 1252);
}
if (opts.biff == 4 && biff4w) {
cur_sheet = (Directory[opts.snames.indexOf(cur_sheet) + 1] || { name: "" }).name;
} else if (opts.biff < 5 || val2.BIFFVer == 0 && val2.dt == 4096) {
if (cur_sheet === "") cur_sheet = "Sheet1";
range2 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
var fakebs8 = { pos: blob.l - length, name: cur_sheet };
Directory[fakebs8.pos] = fakebs8;
opts.snames.push(cur_sheet);
} else cur_sheet = (Directory[s6] || { name: "" }).name;
if (val2.dt == 32) out["!type"] = "chart";
if (val2.dt == 64) out["!type"] = "macro";
merges = [];
objects = [];
opts.arrayf = arrayf = [];
colinfo = [];
rowinfo = [];
seencol = false;
wsprops = { Hidden: (Directory[s6] || { hs: 0 }).hs, name: cur_sheet };
}
break;
case 515:
case 3:
case 2:
{
if (out["!type"] == "chart") {
if (options.dense ? (out["!data"][val2.r] || [])[val2.c] : out[encode_col(val2.c) + encode_row(val2.r)]) ++val2.c;
}
temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe] || {}, v: val2.val, t: "n" };
if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
safe_format_xf(temp_val, options, wb.opts.Date1904);
addcell({ c: val2.c, r: val2.r }, temp_val, options);
}
break;
case 5:
case 517:
{
temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe], v: val2.val, t: val2.t };
if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
safe_format_xf(temp_val, options, wb.opts.Date1904);
addcell({ c: val2.c, r: val2.r }, temp_val, options);
}
break;
case 638:
{
temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe], v: val2.rknum, t: "n" };
if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
safe_format_xf(temp_val, options, wb.opts.Date1904);
addcell({ c: val2.c, r: val2.r }, temp_val, options);
}
break;
case 189:
{
for (var j3 = val2.c; j3 <= val2.C; ++j3) {
var ixfe = val2.rkrec[j3 - val2.c][0];
temp_val = { ixfe, XF: XFs[ixfe], v: val2.rkrec[j3 - val2.c][1], t: "n" };
if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
safe_format_xf(temp_val, options, wb.opts.Date1904);
addcell({ c: j3, r: val2.r }, temp_val, options);
}
}
break;
case 6:
case 518:
case 1030:
{
if (val2.val == "String") {
last_formula = val2;
break;
}
temp_val = make_cell(val2.val, val2.cell.ixfe, val2.tt);
temp_val.XF = XFs[temp_val.ixfe];
if (options.cellFormula) {
var _f = val2.formula;
if (_f && _f[0] && _f[0][0] && _f[0][0][0] == "PtgExp") {
var _fr = _f[0][0][1][0], _fc = _f[0][0][1][1];
var _fe = encode_cell({ r: _fr, c: _fc });
if (sharedf[_fe]) temp_val.f = "" + stringify_formula(val2.formula, range2, val2.cell, supbooks, opts);
else temp_val.F = ((options.dense ? (out["!data"][_fr] || [])[_fc] : out[_fe]) || {}).F;
} else temp_val.f = "" + stringify_formula(val2.formula, range2, val2.cell, supbooks, opts);
}
if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
safe_format_xf(temp_val, options, wb.opts.Date1904);
addcell(val2.cell, temp_val, options);
last_formula = val2;
}
break;
case 7:
case 519:
{
if (last_formula) {
last_formula.val = val2;
temp_val = make_cell(val2, last_formula.cell.ixfe, "s");
temp_val.XF = XFs[temp_val.ixfe];
if (options.cellFormula) {
temp_val.f = "" + stringify_formula(last_formula.formula, range2, last_formula.cell, supbooks, opts);
}
if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
safe_format_xf(temp_val, options, wb.opts.Date1904);
addcell(last_formula.cell, temp_val, options);
last_formula = null;
} else throw new Error("String record expects Formula");
}
break;
case 33:
case 545:
{
arrayf.push(val2);
var _arraystart = encode_cell(val2[0].s);
cc = options.dense ? (out["!data"][val2[0].s.r] || [])[val2[0].s.c] : out[_arraystart];
if (options.cellFormula && cc) {
if (!last_formula) break;
if (!_arraystart || !cc) break;
cc.f = "" + stringify_formula(val2[1], range2, val2[0], supbooks, opts);
cc.F = encode_range(val2[0]);
}
}
break;
case 1212:
{
if (!options.cellFormula) break;
if (last_cell) {
if (!last_formula) break;
sharedf[encode_cell(last_formula.cell)] = val2[0];
cc = options.dense ? (out["!data"][last_formula.cell.r] || [])[last_formula.cell.c] : out[encode_cell(last_formula.cell)];
(cc || {}).f = "" + stringify_formula(val2[0], range2, lastcell, supbooks, opts);
}
}
break;
case 253:
temp_val = make_cell(sst[val2.isst].t, val2.ixfe, "s");
if (sst[val2.isst].h) temp_val.h = sst[val2.isst].h;
temp_val.XF = XFs[temp_val.ixfe];
if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
safe_format_xf(temp_val, options, wb.opts.Date1904);
addcell({ c: val2.c, r: val2.r }, temp_val, options);
break;
case 513:
if (options.sheetStubs) {
temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe], t: "z" };
if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
safe_format_xf(temp_val, options, wb.opts.Date1904);
addcell({ c: val2.c, r: val2.r }, temp_val, options);
}
break;
case 190:
if (options.sheetStubs) {
for (var _j = val2.c; _j <= val2.C; ++_j) {
var _ixfe = val2.ixfe[_j - val2.c];
temp_val = { ixfe: _ixfe, XF: XFs[_ixfe], t: "z" };
if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
safe_format_xf(temp_val, options, wb.opts.Date1904);
addcell({ c: _j, r: val2.r }, temp_val, options);
}
}
break;
case 214:
case 516:
case 4:
temp_val = make_cell(val2.val, val2.ixfe, "s");
temp_val.XF = XFs[temp_val.ixfe];
if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63];
safe_format_xf(temp_val, options, wb.opts.Date1904);
addcell({ c: val2.c, r: val2.r }, temp_val, options);
break;
case 0:
case 512:
{
if (file_depth === 1) range2 = val2;
}
break;
case 252:
{
sst = val2;
}
break;
case 1054:
{
if (opts.biff >= 3 && opts.biff <= 4) {
BIFF2FmtTable[BIFF2Fmt++] = val2[1];
for (var b4idx = 0; b4idx < BIFF2Fmt + 163; ++b4idx) if (table_fmt[b4idx] == val2[1]) break;
if (b4idx >= 163) SSF__load(val2[1], BIFF2Fmt + 163);
} else SSF__load(val2[1], val2[0]);
}
break;
case 30:
{
BIFF2FmtTable[BIFF2Fmt++] = val2;
for (var b2idx = 0; b2idx < BIFF2Fmt + 163; ++b2idx) if (table_fmt[b2idx] == val2) break;
if (b2idx >= 163) SSF__load(val2, BIFF2Fmt + 163);
}
break;
case 229:
merges = merges.concat(val2);
break;
case 93:
objects[val2.cmo[0]] = opts.lastobj = val2;
break;
case 438:
opts.lastobj.TxO = val2;
break;
case 127:
opts.lastobj.ImData = val2;
break;
case 440:
{
for (rngR = val2[0].s.r; rngR <= val2[0].e.r; ++rngR)
for (rngC = val2[0].s.c; rngC <= val2[0].e.c; ++rngC) {
cc = options.dense ? (out["!data"][rngR] || [])[rngC] : out[encode_cell({ c: rngC, r: rngR })];
if (cc) cc.l = val2[1];
}
}
break;
case 2048:
{
for (rngR = val2[0].s.r; rngR <= val2[0].e.r; ++rngR)
for (rngC = val2[0].s.c; rngC <= val2[0].e.c; ++rngC) {
cc = options.dense ? (out["!data"][rngR] || [])[rngC] : out[encode_cell({ c: rngC, r: rngR })];
if (cc && cc.l) cc.l.Tooltip = val2[1];
}
}
break;
case 28:
{
cc = options.dense ? (out["!data"][val2[0].r] || [])[val2[0].c] : out[encode_cell(val2[0])];
if (!cc) {
if (options.dense) {
if (!out["!data"][val2[0].r]) out["!data"][val2[0].r] = [];
cc = out["!data"][val2[0].r][val2[0].c] = { t: "z" };
} else {
cc = out[encode_cell(val2[0])] = { t: "z" };
}
range2.e.r = Math.max(range2.e.r, val2[0].r);
range2.s.r = Math.min(range2.s.r, val2[0].r);
range2.e.c = Math.max(range2.e.c, val2[0].c);
range2.s.c = Math.min(range2.s.c, val2[0].c);
}
if (!cc.c) cc.c = [];
if (opts.biff <= 5 && opts.biff >= 2) cmnt = { a: "SheetJ5", t: val2[1] };
else {
var noteobj = objects[val2[2]];
cmnt = { a: val2[1], t: noteobj.TxO.t };
if (val2[3] != null && !(val2[3] & 2)) cc.c.hidden = true;
}
cc.c.push(cmnt);
}
break;
case 2173:
update_xfext(XFs[val2.ixfe], val2.ext);
break;
case 125:
{
if (!opts.cellStyles) break;
while (val2.e >= val2.s) {
colinfo[val2.e--] = { width: val2.w / 256, level: val2.level || 0, hidden: !!(val2.flags & 1) };
if (!seencol) {
seencol = true;
find_mdw_colw(val2.w / 256);
}
process_col(colinfo[val2.e + 1]);
}
}
break;
case 520:
{
var rowobj = {};
if (val2.level != null) {
rowinfo[val2.r] = rowobj;
rowobj.level = val2.level;
}
if (val2.hidden) {
rowinfo[val2.r] = rowobj;
rowobj.hidden = true;
}
if (val2.hpt) {
rowinfo[val2.r] = rowobj;
rowobj.hpt = val2.hpt;
rowobj.hpx = pt2px(val2.hpt);
}
}
break;
case 38:
case 39:
case 40:
case 41:
if (!out["!margins"]) default_margins(out["!margins"] = {});
out["!margins"][{ 38: "left", 39: "right", 40: "top", 41: "bottom" }[RecordType]] = val2;
break;
case 161:
if (!out["!margins"]) default_margins(out["!margins"] = {});
out["!margins"].header = val2.header;
out["!margins"].footer = val2.footer;
break;
case 574:
if (val2.RTL) Workbook.Views[0].RTL = true;
break;
case 146:
palette = val2;
break;
case 2198:
themes = val2;
break;
case 140:
country = val2;
break;
case 442:
{
if (!cur_sheet) Workbook.WBProps.CodeName = val2 || "ThisWorkbook";
else wsprops.CodeName = val2 || wsprops.name;
}
break;
}
} else {
if (!R3) console.error("Missing Info for XLS Record 0x" + RecordType.toString(16));
blob.l += length;
}
}
wb.SheetNames = keys(Directory).sort(function(a3, b4) {
return Number(a3) - Number(b4);
}).map(function(x2) {
return Directory[x2].name;
});
if (!options.bookSheets) wb.Sheets = Sheets;
if (!wb.SheetNames.length && Preamble["!ref"]) {
wb.SheetNames.push("Sheet1");
if (wb.Sheets) wb.Sheets["Sheet1"] = Preamble;
} else wb.Preamble = Preamble;
if (wb.Sheets) FilterDatabases.forEach(function(r8, i7) {
wb.Sheets[wb.SheetNames[i7]]["!autofilter"] = r8;
});
wb.Strings = sst;
wb.SSF = dup(table_fmt);
if (opts.enc) wb.Encryption = opts.enc;
if (themes) wb.Themes = themes;
wb.Metadata = {};
if (country !== void 0) wb.Metadata.Country = country;
if (supbooks.names.length > 0) Workbook.Names = supbooks.names;
wb.Workbook = Workbook;
return wb;
}
function parse_xls_props(cfb, props, o9) {
var DSI = CFB.find(cfb, "/!DocumentSummaryInformation");
if (DSI && DSI.size > 0) try {
var DocSummary = parse_PropertySetStream(DSI, DocSummaryPIDDSI, PSCLSID.DSI);
for (var d4 in DocSummary) props[d4] = DocSummary[d4];
} catch (e9) {
if (o9.WTF) throw e9;
}
var SI = CFB.find(cfb, "/!SummaryInformation");
if (SI && SI.size > 0) try {
var Summary = parse_PropertySetStream(SI, SummaryPIDSI, PSCLSID.SI);
for (var s6 in Summary) if (props[s6] == null) props[s6] = Summary[s6];
} catch (e9) {
if (o9.WTF) throw e9;
}
if (props.HeadingPairs && props.TitlesOfParts) {
load_props_pairs(props.HeadingPairs, props.TitlesOfParts, props, o9);
delete props.HeadingPairs;
delete props.TitlesOfParts;
}
}
function parse_xlscfb(cfb, options) {
if (!options) options = {};
fix_read_opts(options);
reset_cp();
if (options.codepage) set_ansi(options.codepage);
var CompObj, WB;
if (cfb.FullPaths) {
if (CFB.find(cfb, "/encryption")) throw new Error("File is password-protected");
CompObj = CFB.find(cfb, "!CompObj");
WB = CFB.find(cfb, "/Workbook") || CFB.find(cfb, "/Book");
} else {
switch (options.type) {
case "base64":
cfb = s2a(Base64_decode(cfb));
break;
case "binary":
cfb = s2a(cfb);
break;
case "buffer":
break;
case "array":
if (!Array.isArray(cfb)) cfb = Array.prototype.slice.call(cfb);
break;
}
prep_blob(cfb, 0);
WB = { content: cfb };
}
var WorkbookP;
var _data;
if (CompObj) parse_compobj(CompObj);
if (options.bookProps && !options.bookSheets) WorkbookP = {};
else {
var T3 = has_buf ? "buffer" : "array";
if (WB && WB.content) WorkbookP = parse_workbook(WB.content, options);
else if ((_data = CFB.find(cfb, "PerfectOffice_MAIN")) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T3, options));
else if ((_data = CFB.find(cfb, "NativeContent_MAIN")) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T3, options));
else if ((_data = CFB.find(cfb, "MN0")) && _data.content) throw new Error("Unsupported Works 4 for Mac file");
else throw new Error("Cannot find Workbook stream");
if (options.bookVBA && cfb.FullPaths && CFB.find(cfb, "/_VBA_PROJECT_CUR/VBA/dir")) WorkbookP.vbaraw = make_vba_xls(cfb);
}
var props = {};
if (cfb.FullPaths) parse_xls_props(
/*::((*/
cfb,
props,
options
);
WorkbookP.Props = WorkbookP.Custprops = props;
if (options.bookFiles) WorkbookP.cfb = cfb;
return WorkbookP;
}
function write_biff_rec(ba, type, payload, length) {
var t6 = type;
if (isNaN(t6)) return;
var len = length || (payload || []).length || 0;
var o9 = ba.next(4);
o9.write_shift(2, t6);
o9.write_shift(2, len);
if (
/*:: len != null &&*/
len > 0 && is_buf(payload)
) ba.push(payload);
}
function html_to_sheet(str2, _opts) {
var opts = _opts || {};
var dense = opts.dense != null ? opts.dense : DENSE;
var ws = {};
if (dense) ws["!data"] = [];
str2 = str_remove_ng(str2, "");
var mtch = str2.match(/");
var mtch2 = str2.match(/<\/table/i);
var i7 = mtch.index, j3 = mtch2 && mtch2.index || str2.length;
var rows = split_regex(str2.slice(i7, j3), /(:?]*>)/i, " ");
var R3 = -1, C3 = 0, RS = 0, CS = 0;
var range2 = { s: { r: 1e7, c: 1e7 }, e: { r: 0, c: 0 } };
var merges = [];
for (i7 = 0; i7 < rows.length; ++i7) {
var row = rows[i7].trim();
var hd = row.slice(0, 3).toLowerCase();
if (hd == " /i);
for (j3 = 0; j3 < cells.length; ++j3) {
var cell = cells[j3].trim();
if (!cell.match(/")) > -1) m4 = m4.slice(cc + 1);
for (var midx = 0; midx < merges.length; ++midx) {
var _merge = merges[midx];
if (_merge.s.c == C3 && _merge.s.r < R3 && R3 <= _merge.e.r) {
C3 = _merge.e.c + 1;
midx = -1;
}
}
var tag = parsexmltag(cell.slice(0, cell.indexOf(">")));
CS = tag.colspan ? +tag.colspan : 1;
if ((RS = +tag.rowspan) > 1 || CS > 1) merges.push({ s: { r: R3, c: C3 }, e: { r: R3 + (RS || 1) - 1, c: C3 + CS - 1 } });
var _t = tag.t || tag["data-t"] || "";
if (!m4.length) {
C3 += CS;
continue;
}
m4 = htmldecode(m4);
if (range2.s.r > R3) range2.s.r = R3;
if (range2.e.r < R3) range2.e.r = R3;
if (range2.s.c > C3) range2.s.c = C3;
if (range2.e.c < C3) range2.e.c = C3;
if (!m4.length) {
C3 += CS;
continue;
}
var o9 = { t: "s", v: m4 };
if (opts.raw || !m4.trim().length || _t == "s") {
} else if (m4 === "TRUE") o9 = { t: "b", v: true };
else if (m4 === "FALSE") o9 = { t: "b", v: false };
else if (!isNaN(fuzzynum(m4))) o9 = { t: "n", v: fuzzynum(m4) };
else if (!isNaN(fuzzydate(m4).getDate())) {
o9 = { t: "d", v: parseDate(m4) };
if (opts.UTC === false) o9.v = utc_to_local(o9.v);
if (!opts.cellDates) o9 = { t: "n", v: datenum(o9.v) };
o9.z = opts.dateNF || table_fmt[14];
} else if (m4.charCodeAt(0) == 35 && RBErr[m4] != null) {
o9.t = "e";
o9.w = m4;
o9.v = RBErr[m4];
}
if (o9.cellText !== false) o9.w = m4;
if (dense) {
if (!ws["!data"][R3]) ws["!data"][R3] = [];
ws["!data"][R3][C3] = o9;
} else ws[encode_cell({ r: R3, c: C3 })] = o9;
C3 += CS;
}
}
ws["!ref"] = encode_range(range2);
if (merges.length) ws["!merges"] = merges;
return ws;
}
function make_html_row(ws, r8, R3, o9) {
var M4 = ws["!merges"] || [];
var oo = [];
var sp = {};
var dense = ws["!data"] != null;
for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
var RS = 0, CS = 0;
for (var j3 = 0; j3 < M4.length; ++j3) {
if (M4[j3].s.r > R3 || M4[j3].s.c > C3) continue;
if (M4[j3].e.r < R3 || M4[j3].e.c < C3) continue;
if (M4[j3].s.r < R3 || M4[j3].s.c < C3) {
RS = -1;
break;
}
RS = M4[j3].e.r - M4[j3].s.r + 1;
CS = M4[j3].e.c - M4[j3].s.c + 1;
break;
}
if (RS < 0) continue;
var coord = encode_col(C3) + encode_row(R3);
var cell = dense ? (ws["!data"][R3] || [])[C3] : ws[coord];
if (cell && cell.t == "n" && cell.v != null && !isFinite(cell.v)) {
if (isNaN(cell.v)) cell = { t: "e", v: 36, w: BErr[36] };
else cell = { t: "e", v: 7, w: BErr[7] };
}
var w3 = cell && cell.v != null && (cell.h || escapehtml(cell.w || (format_cell(cell), cell.w) || "")) || "";
sp = {};
if (RS > 1) sp.rowspan = RS;
if (CS > 1) sp.colspan = CS;
if (o9.editable) w3 = '' + w3 + "";
else if (cell) {
sp["data-t"] = cell && cell.t || "z";
if (cell.v != null) sp["data-v"] = escapehtml(cell.v instanceof Date ? cell.v.toISOString() : cell.v);
if (cell.z != null) sp["data-z"] = cell.z;
if (cell.l && (cell.l.Target || "#").charAt(0) != "#") w3 = '' + w3 + "";
}
sp.id = (o9.id || "sjs") + "-" + coord;
oo.push(writextag("td", w3, sp));
}
var preamble = "";
return preamble + oo.join("") + " ";
}
function html_to_workbook(str2, opts) {
var mtch = str_match_xml_ig(str2, "table");
if (!mtch || mtch.length == 0) throw new Error("Invalid HTML: could not find ");
if (mtch.length == 1) {
var w3 = sheet_to_workbook(html_to_sheet(mtch[0], opts), opts);
w3.bookType = "html";
return w3;
}
var wb = book_new();
mtch.forEach(function(s6, idx) {
book_append_sheet(wb, html_to_sheet(s6, opts), "Sheet" + (idx + 1));
});
wb.bookType = "html";
return wb;
}
function make_html_preamble(ws, R3, o9) {
var out = [];
return out.join("") + "";
}
function sheet_to_html(ws, opts) {
var o9 = opts || {};
var header = o9.header != null ? o9.header : HTML_BEGIN;
var footer = o9.footer != null ? o9.footer : HTML_END;
var out = [header];
var r8 = decode_range(ws["!ref"] || "A1");
out.push(make_html_preamble(ws, r8, o9));
if (ws["!ref"]) for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) out.push(make_html_row(ws, r8, R3, o9));
out.push("
" + footer);
return out.join("");
}
function sheet_add_dom(ws, table, _opts) {
var rows = table.rows;
if (!rows) {
throw "Unsupported origin when " + table.tagName + " is not a TABLE";
}
var opts = _opts || {};
var dense = ws["!data"] != null;
var or_R = 0, or_C = 0;
if (opts.origin != null) {
if (typeof opts.origin == "number") or_R = opts.origin;
else {
var _origin2 = typeof opts.origin == "string" ? decode_cell(opts.origin) : opts.origin;
or_R = _origin2.r;
or_C = _origin2.c;
}
}
var sheetRows = Math.min(opts.sheetRows || 1e7, rows.length);
var range2 = { s: { r: 0, c: 0 }, e: { r: or_R, c: or_C } };
if (ws["!ref"]) {
var _range = decode_range(ws["!ref"]);
range2.s.r = Math.min(range2.s.r, _range.s.r);
range2.s.c = Math.min(range2.s.c, _range.s.c);
range2.e.r = Math.max(range2.e.r, _range.e.r);
range2.e.c = Math.max(range2.e.c, _range.e.c);
if (or_R == -1) range2.e.r = or_R = _range.e.r + 1;
}
var merges = [], midx = 0;
var rowinfo = ws["!rows"] || (ws["!rows"] = []);
var _R = 0, R3 = 0, _C = 0, C3 = 0, RS = 0, CS = 0;
if (!ws["!cols"]) ws["!cols"] = [];
for (; _R < rows.length && R3 < sheetRows; ++_R) {
var row = rows[_R];
if (is_dom_element_hidden(row)) {
if (opts.display) continue;
rowinfo[R3] = { hidden: true };
}
var elts = row.cells;
for (_C = C3 = 0; _C < elts.length; ++_C) {
var elt = elts[_C];
if (opts.display && is_dom_element_hidden(elt)) continue;
var v4 = elt.hasAttribute("data-v") ? elt.getAttribute("data-v") : elt.hasAttribute("v") ? elt.getAttribute("v") : htmldecode(elt.innerHTML);
var z3 = elt.getAttribute("data-z") || elt.getAttribute("z");
for (midx = 0; midx < merges.length; ++midx) {
var m4 = merges[midx];
if (m4.s.c == C3 + or_C && m4.s.r < R3 + or_R && R3 + or_R <= m4.e.r) {
C3 = m4.e.c + 1 - or_C;
midx = -1;
}
}
CS = +elt.getAttribute("colspan") || 1;
if ((RS = +elt.getAttribute("rowspan") || 1) > 1 || CS > 1) merges.push({ s: { r: R3 + or_R, c: C3 + or_C }, e: { r: R3 + or_R + (RS || 1) - 1, c: C3 + or_C + (CS || 1) - 1 } });
var o9 = { t: "s", v: v4 };
var _t = elt.getAttribute("data-t") || elt.getAttribute("t") || "";
if (v4 != null) {
if (v4.length == 0) o9.t = _t || "z";
else if (opts.raw || v4.trim().length == 0 || _t == "s") {
} else if (_t == "e" && BErr[+v4]) o9 = { t: "e", v: +v4, w: BErr[+v4] };
else if (v4 === "TRUE") o9 = { t: "b", v: true };
else if (v4 === "FALSE") o9 = { t: "b", v: false };
else if (!isNaN(fuzzynum(v4))) o9 = { t: "n", v: fuzzynum(v4) };
else if (!isNaN(fuzzydate(v4).getDate())) {
o9 = { t: "d", v: parseDate(v4) };
if (opts.UTC) o9.v = local_to_utc(o9.v);
if (!opts.cellDates) o9 = { t: "n", v: datenum(o9.v) };
o9.z = opts.dateNF || table_fmt[14];
} else if (v4.charCodeAt(0) == 35 && RBErr[v4] != null) o9 = { t: "e", v: RBErr[v4], w: v4 };
}
if (o9.z === void 0 && z3 != null) o9.z = z3;
var l5 = "", Aelts = elt.getElementsByTagName("A");
if (Aelts && Aelts.length) {
for (var Aelti = 0; Aelti < Aelts.length; ++Aelti) if (Aelts[Aelti].hasAttribute("href")) {
l5 = Aelts[Aelti].getAttribute("href");
if (l5.charAt(0) != "#") break;
}
}
if (l5 && l5.charAt(0) != "#" && l5.slice(0, 11).toLowerCase() != "javascript:") o9.l = { Target: l5 };
if (dense) {
if (!ws["!data"][R3 + or_R]) ws["!data"][R3 + or_R] = [];
ws["!data"][R3 + or_R][C3 + or_C] = o9;
} else ws[encode_cell({ c: C3 + or_C, r: R3 + or_R })] = o9;
if (range2.e.c < C3 + or_C) range2.e.c = C3 + or_C;
C3 += CS;
}
++R3;
}
if (merges.length) ws["!merges"] = (ws["!merges"] || []).concat(merges);
range2.e.r = Math.max(range2.e.r, R3 - 1 + or_R);
ws["!ref"] = encode_range(range2);
if (R3 >= sheetRows) ws["!fullref"] = encode_range((range2.e.r = rows.length - _R + R3 - 1 + or_R, range2));
return ws;
}
function parse_dom_table(table, _opts) {
var opts = _opts || {};
var ws = {};
if (opts.dense) ws["!data"] = [];
return sheet_add_dom(ws, table, _opts);
}
function table_to_book(table, opts) {
var o9 = sheet_to_workbook(parse_dom_table(table, opts), opts);
return o9;
}
function is_dom_element_hidden(element) {
var display = "";
var get_computed_style = get_get_computed_style_function(element);
if (get_computed_style) display = get_computed_style(element).getPropertyValue("display");
if (!display) display = element.style && element.style.display;
return display === "none";
}
function get_get_computed_style_function(element) {
if (element.ownerDocument.defaultView && typeof element.ownerDocument.defaultView.getComputedStyle === "function") return element.ownerDocument.defaultView.getComputedStyle;
if (typeof getComputedStyle === "function") return getComputedStyle;
return null;
}
function parse_text_p(text3) {
var fixed = text3.replace(/[\t\r\n]/g, " ").trim().replace(/ +/g, " ").replace(/ /g, " ").replace(/ /g, function($$, $1) {
return Array(parseInt($1, 10) + 1).join(" ");
}).replace(/]*\/>/g, " ").replace(/ /g, "\n");
var v4 = unescapexml(fixed.replace(/<[^<>]*>/g, ""));
return [v4];
}
function parse_ods_styles(d4, _opts, _nfm) {
var number_format_map = _nfm || {};
var str2 = xlml_normalize(d4);
xlmlregex.lastIndex = 0;
str2 = remove_doctype(str_remove_ng(str2, ""));
var Rn, NFtag, NF = "", tNF = "", y4, etpos = 0, tidx = -1, infmt = false, payload = "";
while (Rn = xlmlregex.exec(str2)) {
switch (Rn[3] = Rn[3].replace(/_[\s\S]*$/, "")) {
/* Number Format Definitions */
case "number-style":
// 16.29.2
case "currency-style":
// 16.29.8
case "percentage-style":
// 16.29.10
case "date-style":
// 16.29.11
case "time-style":
// 16.29.19
case "text-style":
if (Rn[1] === "/") {
infmt = false;
if (NFtag["truncate-on-overflow"] == "false") {
if (NF.match(/h/)) NF = NF.replace(/h+/, "[$&]");
else if (NF.match(/m/)) NF = NF.replace(/m+/, "[$&]");
else if (NF.match(/s/)) NF = NF.replace(/s+/, "[$&]");
}
number_format_map[NFtag.name] = NF;
NF = "";
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
infmt = true;
NF = "";
NFtag = parsexmltag(Rn[0], false);
}
break;
// LibreOffice bug https://bugs.documentfoundation.org/show_bug.cgi?id=149484
case "boolean-style":
if (Rn[1] === "/") {
infmt = false;
number_format_map[NFtag.name] = "General";
NF = "";
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
infmt = true;
NF = "";
NFtag = parsexmltag(Rn[0], false);
}
break;
/* Number Format Elements */
case "boolean":
NF += "General";
break;
case "text":
if (Rn[1] === "/") {
payload = str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length);
if (payload == "%" && NFtag[0] == " 16.29.17
case "quarter":
console.error("Excel does not support ODS format token " + Rn[3]);
break;
case "fill-character":
if (Rn[1] === "/") {
payload = str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length);
NF += '"' + payload.replace(/"/g, '""') + '"*';
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
tidx = xlmlregex.lastIndex;
}
break;
case "scientific-number":
y4 = parsexmltag(Rn[0], false);
NF += "0." + fill("0", +y4["min-decimal-places"] || +y4["decimal-places"] || 2) + fill("?", +y4["decimal-places"] - +y4["min-decimal-places"] || 0) + "E" + (parsexmlbool(y4["forced-exponent-sign"]) ? "+" : "") + fill("0", +y4["min-exponent-digits"] || 2);
break;
case "fraction":
y4 = parsexmltag(Rn[0], false);
if (!+y4["min-integer-digits"]) NF += "#";
else NF += fill("0", +y4["min-integer-digits"]);
NF += " ";
NF += fill("?", +y4["min-numerator-digits"] || 1);
NF += "/";
if (+y4["denominator-value"]) NF += y4["denominator-value"];
else NF += fill("?", +y4["min-denominator-digits"] || 1);
break;
case "currency-symbol":
if (Rn[1] === "/") {
NF += '"' + str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"';
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
tidx = xlmlregex.lastIndex;
} else NF += "$";
break;
case "text-properties":
y4 = parsexmltag(Rn[0], false);
switch ((y4["color"] || "").toLowerCase().replace("#", "")) {
case "ff0000":
case "red":
NF = "[Red]" + NF;
break;
}
break;
case "text-content":
NF += "@";
break;
case "map":
y4 = parsexmltag(Rn[0], false);
if (unescapexml(y4["condition"]) == "value()>=0") NF = number_format_map[y4["apply-style-name"]] + ";" + NF;
else console.error("ODS number format may be incorrect: " + y4["condition"]);
break;
case "number":
if (Rn[1] === "/") break;
y4 = parsexmltag(Rn[0], false);
tNF = "";
tNF += fill("0", +y4["min-integer-digits"] || 1);
if (parsexmlbool(y4["grouping"])) tNF = commaify(fill("#", Math.max(0, 4 - tNF.length)) + tNF);
if (+y4["min-decimal-places"] || +y4["decimal-places"]) tNF += ".";
if (+y4["min-decimal-places"]) tNF += fill("0", +y4["min-decimal-places"] || 1);
if (+y4["decimal-places"] - (+y4["min-decimal-places"] || 0)) tNF += fill("0", +y4["decimal-places"] - (+y4["min-decimal-places"] || 0));
NF += tNF;
break;
case "embedded-text":
if (Rn[1] === "/") {
if (etpos == 0) NF += '"' + str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"';
else NF = NF.slice(0, etpos) + '"' + str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"' + NF.slice(etpos);
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
tidx = xlmlregex.lastIndex;
etpos = -+parsexmltag(Rn[0], false)["position"] || 0;
}
break;
}
}
return number_format_map;
}
function parse_content_xml(d4, _opts, _nfm) {
var opts = _opts || {};
if (DENSE != null && opts.dense == null) opts.dense = DENSE;
var str2 = xlml_normalize(d4);
var state = [], tmp;
var tag;
var nfidx, NF = "", pidx = 0;
var sheetag;
var rowtag;
var Sheets = {}, SheetNames = [];
var ws = {};
if (opts.dense) ws["!data"] = [];
var Rn, q2;
var ctag = { value: "" }, ctag2 = {};
var textp = "", textpidx = 0, textptag, oldtextp = "", oldtextpidx = 0;
var textR = [], oldtextR = [];
var R3 = -1, C3 = -1, range2 = { s: { r: 1e6, c: 1e7 }, e: { r: 0, c: 0 } };
var row_ol = 0;
var number_format_map = _nfm || {}, styles2 = {};
var merges = [], mrange = {}, mR = 0, mC = 0;
var rowinfo = [], rowpeat = 1, colpeat = 1;
var arrayf = [];
var WB = { Names: [], WBProps: {} };
var atag = {};
var _Ref = ["", ""];
var comments = [], comment = {};
var creator = "", creatoridx = 0;
var isstub = false, intable = false;
var i7 = 0;
xlmlregex.lastIndex = 0;
str2 = remove_doctype(str_remove_ng(str2, ""));
while (Rn = xlmlregex.exec(str2)) switch (Rn[3] = Rn[3].replace(/_[\s\S]*$/, "")) {
case "table":
case "\u5DE5\u4F5C\u8868":
if (Rn[1] === "/") {
if (range2.e.c >= range2.s.c && range2.e.r >= range2.s.r) ws["!ref"] = encode_range(range2);
else ws["!ref"] = "A1:A1";
if (opts.sheetRows > 0 && opts.sheetRows <= range2.e.r) {
ws["!fullref"] = ws["!ref"];
range2.e.r = opts.sheetRows - 1;
ws["!ref"] = encode_range(range2);
}
if (merges.length) ws["!merges"] = merges;
if (rowinfo.length) ws["!rows"] = rowinfo;
sheetag.name = sheetag["\u540D\u79F0"] || sheetag.name;
if (typeof JSON !== "undefined") JSON.stringify(sheetag);
SheetNames.push(sheetag.name);
Sheets[sheetag.name] = ws;
intable = false;
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
sheetag = parsexmltag(Rn[0], false);
R3 = C3 = -1;
range2.s.r = range2.s.c = 1e7;
range2.e.r = range2.e.c = 0;
ws = {};
if (opts.dense) ws["!data"] = [];
merges = [];
rowinfo = [];
intable = true;
}
break;
case "table-row-group":
if (Rn[1] === "/") --row_ol;
else ++row_ol;
break;
case "table-row":
case "\u884C":
if (Rn[1] === "/") {
R3 += rowpeat;
rowpeat = 1;
break;
}
rowtag = parsexmltag(Rn[0], false);
if (rowtag["\u884C\u53F7"]) R3 = rowtag["\u884C\u53F7"] - 1;
else if (R3 == -1) R3 = 0;
rowpeat = +rowtag["number-rows-repeated"] || 1;
if (rowpeat < 10) {
for (i7 = 0; i7 < rowpeat; ++i7) if (row_ol > 0) rowinfo[R3 + i7] = { level: row_ol };
}
C3 = -1;
break;
case "covered-table-cell":
if (Rn[1] !== "/") {
++C3;
ctag = parsexmltag(Rn[0], false);
colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10) || 1;
if (opts.sheetStubs) {
while (colpeat-- > 0) {
if (opts.dense) {
if (!ws["!data"][R3]) ws["!data"][R3] = [];
ws["!data"][R3][C3] = { t: "z" };
} else ws[encode_cell({ r: R3, c: C3 })] = { t: "z" };
++C3;
}
--C3;
} else C3 += colpeat - 1;
}
textp = "";
textR = [];
break;
/* stub */
case "table-cell":
case "\u6570\u636E":
if (Rn[0].charAt(Rn[0].length - 2) === "/") {
++C3;
ctag = parsexmltag(Rn[0], false);
colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10) || 1;
q2 = {
t: "z",
v: null
/*:: , z:null, w:"",c:[]*/
};
if (ctag.formula && opts.cellFormula != false) q2.f = ods_to_csf_formula(unescapexml(ctag.formula));
if (ctag["style-name"] && styles2[ctag["style-name"]]) q2.z = styles2[ctag["style-name"]];
if ((ctag["\u6570\u636E\u7C7B\u578B"] || ctag["value-type"]) == "string") {
q2.t = "s";
q2.v = unescapexml(ctag["string-value"] || "");
if (opts.dense) {
if (!ws["!data"][R3]) ws["!data"][R3] = [];
ws["!data"][R3][C3] = q2;
} else {
ws[encode_col(C3) + encode_row(R3)] = q2;
}
}
C3 += colpeat - 1;
} else if (Rn[1] !== "/") {
++C3;
textp = oldtextp = "";
textpidx = oldtextpidx = 0;
textR = [];
oldtextR = [];
colpeat = 1;
var rptR = rowpeat ? R3 + rowpeat - 1 : R3;
if (C3 > range2.e.c) range2.e.c = C3;
if (C3 < range2.s.c) range2.s.c = C3;
if (R3 < range2.s.r) range2.s.r = R3;
if (rptR > range2.e.r) range2.e.r = rptR;
ctag = parsexmltag(Rn[0], false);
ctag2 = parsexmltagraw(Rn[0], true);
comments = [];
comment = {};
q2 = {
t: ctag["\u6570\u636E\u7C7B\u578B"] || ctag["value-type"],
v: null
/*:: , z:null, w:"",c:[]*/
};
if (ctag["style-name"] && styles2[ctag["style-name"]]) q2.z = styles2[ctag["style-name"]];
if (opts.cellFormula) {
if (ctag.formula) ctag.formula = unescapexml(ctag.formula);
if (ctag["number-matrix-columns-spanned"] && ctag["number-matrix-rows-spanned"]) {
mR = parseInt(ctag["number-matrix-rows-spanned"], 10) || 0;
mC = parseInt(ctag["number-matrix-columns-spanned"], 10) || 0;
mrange = { s: { r: R3, c: C3 }, e: { r: R3 + mR - 1, c: C3 + mC - 1 } };
q2.F = encode_range(mrange);
arrayf.push([mrange, q2.F]);
}
if (ctag.formula) q2.f = ods_to_csf_formula(ctag.formula);
else for (i7 = 0; i7 < arrayf.length; ++i7)
if (R3 >= arrayf[i7][0].s.r && R3 <= arrayf[i7][0].e.r) {
if (C3 >= arrayf[i7][0].s.c && C3 <= arrayf[i7][0].e.c)
q2.F = arrayf[i7][1];
}
}
if (ctag["number-columns-spanned"] || ctag["number-rows-spanned"]) {
mR = parseInt(ctag["number-rows-spanned"] || "1", 10) || 1;
mC = parseInt(ctag["number-columns-spanned"] || "1", 10) || 1;
if (mR * mC > 1) {
mrange = { s: { r: R3, c: C3 }, e: { r: R3 + mR - 1, c: C3 + mC - 1 } };
merges.push(mrange);
}
}
if (ctag["number-columns-repeated"]) colpeat = parseInt(ctag["number-columns-repeated"], 10);
switch (q2.t) {
case "boolean":
q2.t = "b";
q2.v = parsexmlbool(ctag["boolean-value"]) || +ctag["boolean-value"] >= 1;
break;
case "float":
q2.t = "n";
q2.v = parseFloat(ctag.value);
if (opts.cellDates && q2.z && fmt_is_date(q2.z)) {
q2.v = numdate(q2.v + (WB.WBProps.date1904 ? 1462 : 0));
q2.t = typeof q2.v == "number" ? "n" : "d";
}
break;
case "percentage":
q2.t = "n";
q2.v = parseFloat(ctag.value);
break;
case "currency":
q2.t = "n";
q2.v = parseFloat(ctag.value);
break;
case "date":
q2.t = "d";
q2.v = parseDate(ctag["date-value"], WB.WBProps.date1904);
if (!opts.cellDates) {
q2.t = "n";
q2.v = datenum(q2.v, WB.WBProps.date1904);
}
if (!q2.z) q2.z = "m/d/yy";
break;
/* NOTE: for `time`, Excel ODS export incorrectly uses durations relative to 1900 epoch even if 1904 is specified */
case "time":
q2.t = "n";
q2.v = parse_isodur(ctag["time-value"]) / 86400;
if (opts.cellDates) {
q2.v = numdate(q2.v);
q2.t = typeof q2.v == "number" ? "n" : "d";
}
if (!q2.z) q2.z = "HH:MM:SS";
break;
case "number":
q2.t = "n";
q2.v = parseFloat(ctag["\u6570\u636E\u6570\u503C"]);
break;
default:
if (q2.t === "string" || q2.t === "text" || !q2.t) {
q2.t = "s";
if (ctag["string-value"] != null) {
textp = unescapexml(ctag["string-value"]);
textR = [];
}
} else throw new Error("Unsupported value type " + q2.t);
}
} else {
isstub = false;
if (ctag2["calcext:value-type"] == "error" && RBErr[textp] != null) {
q2.t = "e";
q2.w = textp;
q2.v = RBErr[textp];
}
if (q2.t === "s") {
q2.v = textp || "";
if (textR.length) q2.R = textR;
isstub = textpidx == 0;
}
if (atag.Target) q2.l = atag;
if (comments.length > 0) {
q2.c = comments;
comments = [];
}
if (textp && opts.cellText !== false) q2.w = textp;
if (isstub) {
q2.t = "z";
delete q2.v;
}
if (!isstub || opts.sheetStubs) {
if (!(opts.sheetRows && opts.sheetRows <= R3)) {
for (var rpt = 0; rpt < rowpeat; ++rpt) {
colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10);
if (opts.dense) {
if (!ws["!data"][R3 + rpt]) ws["!data"][R3 + rpt] = [];
ws["!data"][R3 + rpt][C3] = rpt == 0 ? q2 : dup(q2);
while (--colpeat > 0) ws["!data"][R3 + rpt][C3 + colpeat] = dup(q2);
} else {
ws[encode_cell({ r: R3 + rpt, c: C3 })] = q2;
while (--colpeat > 0) ws[encode_cell({ r: R3 + rpt, c: C3 + colpeat })] = dup(q2);
}
if (range2.e.c <= C3) range2.e.c = C3;
}
}
}
colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10);
C3 += colpeat - 1;
colpeat = 0;
q2 = {
/*:: t:"", v:null, z:null, w:"",c:[]*/
};
textp = "";
textR = [];
}
atag = {};
break;
// 9.1.4
/* pure state */
case "document":
// TODO: is the root for FODS
case "document-content":
case "\u7535\u5B50\u8868\u683C\u6587\u6863":
// 3.1.3.2
case "spreadsheet":
case "\u4E3B\u4F53":
// 3.7
case "scripts":
// 3.12
case "styles":
// TODO
case "font-face-decls":
// 3.14
case "master-styles":
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw "Bad state: " + tmp;
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]);
break;
case "annotation":
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw "Bad state: " + tmp;
comment.t = textp;
if (textR.length) comment.R = textR;
comment.a = creator;
comments.push(comment);
textp = oldtextp;
textpidx = oldtextpidx;
textR = oldtextR;
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
state.push([Rn[3], false]);
var annotag = parsexmltag(Rn[0], true);
if (!(annotag["display"] && parsexmlbool(annotag["display"]))) comments.hidden = true;
oldtextp = textp;
oldtextpidx = textpidx;
oldtextR = textR;
textp = "";
textpidx = 0;
textR = [];
}
creator = "";
creatoridx = 0;
break;
case "creator":
if (Rn[1] === "/") {
creator = str2.slice(creatoridx, Rn.index);
} else creatoridx = Rn.index + Rn[0].length;
break;
/* ignore state */
case "meta":
case "\u5143\u6570\u636E":
// TODO: FODS/UOF
case "settings":
// TODO:
case "config-item-set":
// TODO:
case "config-item-map-indexed":
// TODO:
case "config-item-map-entry":
// TODO:
case "config-item-map-named":
// TODO:
case "shapes":
// 9.2.8
case "frame":
// 10.4.2
case "text-box":
// 10.4.3
case "image":
// 10.4.4
case "data-pilot-tables":
// 9.6.2
case "list-style":
// 16.30
case "form":
// 13.13
case "dde-links":
// 9.8
case "event-listeners":
// TODO
case "chart":
if (Rn[1] === "/") {
if ((tmp = state.pop())[0] !== Rn[3]) throw "Bad state: " + tmp;
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], false]);
textp = "";
textpidx = 0;
textR = [];
break;
case "scientific-number":
//
case "currency-symbol":
//
case "fill-character":
break;
case "text-style":
// 16.27.25
case "boolean-style":
// 16.27.23
case "number-style":
// 16.27.2
case "currency-style":
// 16.29.8
case "percentage-style":
// 16.27.9
case "date-style":
// 16.27.10
case "time-style":
if (Rn[1] === "/") {
var xlmlidx = xlmlregex.lastIndex;
parse_ods_styles(str2.slice(nfidx, xlmlregex.lastIndex), _opts, number_format_map);
xlmlregex.lastIndex = xlmlidx;
} else if (Rn[0].charAt(Rn[0].length - 2) !== "/") {
nfidx = xlmlregex.lastIndex - Rn[0].length;
}
break;
case "script":
break;
// 3.13
case "libraries":
break;
// TODO:
case "automatic-styles":
break;
// 3.15.3
case "default-style":
// TODO:
case "page-layout":
break;
// TODO:
case "style":
{
var styletag = parsexmltag(Rn[0], false);
if (styletag["family"] == "table-cell" && number_format_map[styletag["data-style-name"]]) styles2[styletag["name"]] = number_format_map[styletag["data-style-name"]];
}
break;
case "map":
break;
// 16.3
case "font-face":
break;
// 16.21
case "paragraph-properties":
break;
// 17.6
case "table-properties":
break;
// 17.15
case "table-column-properties":
break;
// 17.16
case "table-row-properties":
break;
// 17.17
case "table-cell-properties":
break;
// 17.18
case "number":
break;
case "fraction":
break;
// TODO 16.27.6
case "day":
// 16.27.11
case "month":
// 16.27.12
case "year":
// 16.27.13
case "era":
// 16.27.14
case "day-of-week":
// 16.27.15
case "week-of-year":
// 16.27.16
case "quarter":
// 16.27.17
case "hours":
// 16.27.19
case "minutes":
// 16.27.20
case "seconds":
// 16.27.21
case "am-pm":
break;
case "boolean":
break;
// 16.27.24
case "text":
if (Rn[0].slice(-2) === "/>") break;
else if (Rn[1] === "/") switch (state[state.length - 1][0]) {
case "number-style":
case "date-style":
case "time-style":
NF += str2.slice(pidx, Rn.index);
break;
}
else pidx = Rn.index + Rn[0].length;
break;
case "named-range":
tag = parsexmltag(Rn[0], false);
_Ref = ods_to_csf_3D(tag["cell-range-address"]);
var nrange = { Name: tag.name, Ref: _Ref[0] + "!" + _Ref[1] };
if (intable) nrange.Sheet = SheetNames.length;
WB.Names.push(nrange);
break;
case "text-content":
break;
// 16.27.27
case "text-properties":
break;
// 16.27.27
case "embedded-text":
break;
// 16.27.4
case "body":
case "\u7535\u5B50\u8868\u683C":
break;
// 3.3 16.9.6 19.726.3
case "forms":
break;
// 12.25.2 13.2
case "table-column":
break;
// 9.1.6
case "table-header-rows":
break;
// 9.1.7
case "table-rows":
break;
// 9.1.12
/* TODO: outline levels */
case "table-column-group":
break;
// 9.1.10
case "table-header-columns":
break;
// 9.1.11
case "table-columns":
break;
// 9.1.12
case "null-date":
tag = parsexmltag(Rn[0], false);
switch (tag["date-value"]) {
case "1904-01-01":
WB.WBProps.date1904 = true;
break;
}
break;
case "graphic-properties":
break;
// 17.21
case "calculation-settings":
break;
// 9.4.1
case "named-expressions":
break;
// 9.4.11
case "label-range":
break;
// 9.4.9
case "label-ranges":
break;
// 9.4.10
case "named-expression":
break;
// 9.4.13
case "sort":
break;
// 9.4.19
case "sort-by":
break;
// 9.4.20
case "sort-groups":
break;
// 9.4.22
case "tab":
break;
// 6.1.4
case "line-break":
break;
// 6.1.5
case "span":
break;
// 6.1.7
case "p":
case "\u6587\u672C\u4E32":
if (["master-styles"].indexOf(state[state.length - 1][0]) > -1) break;
if (Rn[1] === "/" && (!ctag || !ctag["string-value"])) {
var ptp = parse_text_p(str2.slice(textpidx, Rn.index), textptag);
textp = (textp.length > 0 ? textp + "\n" : "") + ptp[0];
} else if (Rn[0].slice(-2) == "/>") {
textp += "\n";
} else {
textptag = parsexmltag(Rn[0], false);
textpidx = Rn.index + Rn[0].length;
}
break;
//
case "s":
break;
//
case "database-range":
if (Rn[1] === "/") break;
try {
_Ref = ods_to_csf_3D(parsexmltag(Rn[0])["target-range-address"]);
Sheets[_Ref[0]]["!autofilter"] = { ref: _Ref[1] };
} catch (e9) {
}
break;
case "date":
break;
// <*:date>
case "object":
break;
// 10.4.6.2
case "title":
case "\u6807\u9898":
break;
// <*:title> OR
case "desc":
break;
// <*:desc>
case "binary-data":
break;
// 10.4.5 TODO: b64 blob
/* 9.2 Advanced Tables */
case "table-source":
break;
// 9.2.6
case "scenario":
break;
// 9.2.6
case "iteration":
break;
// 9.4.3
case "content-validations":
break;
// 9.4.4
/* 9.5 Filters */
case "filter":
break;
// 9.5.2
case "filter-and":
break;
// 9.5.3
case "filter-or":
break;
// 9.5.4
case "filter-condition":
break;
// 9.5.5
case "filter-set-item":
break;
// 9.5.6
case "list-level-style-bullet":
break;
// 16.31
case "page-count":
break;
// TODO
case "time":
break;
// TODO
/* 9.3 Advanced Table Cells */
case "cell-range-source":
break;
// 9.3.1
case "property":
break;
// 13.8
case "a":
if (Rn[1] !== "/") {
atag = parsexmltag(Rn[0], false);
if (!atag.href) break;
atag.Target = unescapexml(atag.href);
delete atag.href;
if (atag.Target.charAt(0) == "#" && atag.Target.indexOf(".") > -1) {
_Ref = ods_to_csf_3D(atag.Target.slice(1));
atag.Target = "#" + _Ref[0] + "!" + _Ref[1];
} else if (atag.Target.match(/^\.\.[\\\/]/)) atag.Target = atag.Target.slice(3);
}
break;
/* non-standard */
case "table-protection":
break;
case "data-pilot-grand-total":
break;
// > 1 & 1431655765;
x2 = (x2 & 858993459) + (x2 >> 2 & 858993459);
return (x2 + (x2 >> 4) & 252645135) * 16843009 >>> 24;
}
function readDecimal128LE(buf, offset) {
var exp = (buf[offset + 15] & 127) << 7 | buf[offset + 14] >> 1;
var mantissa = buf[offset + 14] & 1;
for (var j3 = offset + 13; j3 >= offset; --j3)
mantissa = mantissa * 256 + buf[j3];
return (buf[offset + 15] & 128 ? -mantissa : mantissa) * Math.pow(10, exp - 6176);
}
function parse_varint49(buf, ptr) {
var l5 = ptr.l;
var usz = buf[l5] & 127;
varint:
if (buf[l5++] >= 128) {
usz |= (buf[l5] & 127) << 7;
if (buf[l5++] < 128)
break varint;
usz |= (buf[l5] & 127) << 14;
if (buf[l5++] < 128)
break varint;
usz |= (buf[l5] & 127) << 21;
if (buf[l5++] < 128)
break varint;
usz += (buf[l5] & 127) * Math.pow(2, 28);
++l5;
if (buf[l5++] < 128)
break varint;
usz += (buf[l5] & 127) * Math.pow(2, 35);
++l5;
if (buf[l5++] < 128)
break varint;
usz += (buf[l5] & 127) * Math.pow(2, 42);
++l5;
if (buf[l5++] < 128)
break varint;
}
ptr.l = l5;
return usz;
}
function varint_to_i32(buf) {
var l5 = 0, i32 = buf[l5] & 127;
if (buf[l5++] < 128)
return i32;
i32 |= (buf[l5] & 127) << 7;
if (buf[l5++] < 128)
return i32;
i32 |= (buf[l5] & 127) << 14;
if (buf[l5++] < 128)
return i32;
i32 |= (buf[l5] & 127) << 21;
if (buf[l5++] < 128)
return i32;
i32 |= (buf[l5] & 15) << 28;
return i32;
}
function parse_shallow(buf) {
var out = [], ptr = { l: 0 };
while (ptr.l < buf.length) {
var off = ptr.l;
var num = parse_varint49(buf, ptr);
var type = num & 7;
num = num / 8 | 0;
var data;
var l5 = ptr.l;
switch (type) {
case 0:
{
while (buf[l5++] >= 128)
;
data = buf[subarray](ptr.l, l5);
ptr.l = l5;
}
break;
case 1:
{
data = buf[subarray](l5, l5 + 8);
ptr.l = l5 + 8;
}
break;
case 2:
{
var len = parse_varint49(buf, ptr);
data = buf[subarray](ptr.l, ptr.l + len);
ptr.l += len;
}
break;
case 5:
{
data = buf[subarray](l5, l5 + 4);
ptr.l = l5 + 4;
}
break;
default:
throw new Error("PB Type ".concat(type, " for Field ").concat(num, " at offset ").concat(off));
}
var v4 = { data, type };
if (out[num] == null)
out[num] = [];
out[num].push(v4);
}
return out;
}
function mappa(data, cb) {
return (data == null ? void 0 : data.map(function(d4) {
return cb(d4.data);
})) || [];
}
function parse_iwa_file(buf) {
var _a7;
var out = [], ptr = { l: 0 };
while (ptr.l < buf.length) {
var len = parse_varint49(buf, ptr);
var ai = parse_shallow(buf[subarray](ptr.l, ptr.l + len));
ptr.l += len;
var res = {
id: varint_to_i32(ai[1][0].data),
messages: []
};
ai[2].forEach(function(b4) {
var mi = parse_shallow(b4.data);
var fl = varint_to_i32(mi[3][0].data);
res.messages.push({
meta: mi,
data: buf[subarray](ptr.l, ptr.l + fl)
});
ptr.l += fl;
});
if ((_a7 = ai[3]) == null ? void 0 : _a7[0])
res.merge = varint_to_i32(ai[3][0].data) >>> 0 > 0;
out.push(res);
}
return out;
}
function parse_snappy_chunk(type, buf) {
if (type != 0)
throw new Error("Unexpected Snappy chunk type ".concat(type));
var ptr = { l: 0 };
var usz = parse_varint49(buf, ptr);
var chunks = [];
var l5 = ptr.l;
while (l5 < buf.length) {
var tag = buf[l5] & 3;
if (tag == 0) {
var len = buf[l5++] >> 2;
if (len < 60)
++len;
else {
var c6 = len - 59;
len = buf[l5];
if (c6 > 1)
len |= buf[l5 + 1] << 8;
if (c6 > 2)
len |= buf[l5 + 2] << 16;
if (c6 > 3)
len |= buf[l5 + 3] << 24;
len >>>= 0;
len++;
l5 += c6;
}
chunks.push(buf[subarray](l5, l5 + len));
l5 += len;
continue;
} else {
var offset = 0, length = 0;
if (tag == 1) {
length = (buf[l5] >> 2 & 7) + 4;
offset = (buf[l5++] & 224) << 3;
offset |= buf[l5++];
} else {
length = (buf[l5++] >> 2) + 1;
if (tag == 2) {
offset = buf[l5] | buf[l5 + 1] << 8;
l5 += 2;
} else {
offset = (buf[l5] | buf[l5 + 1] << 8 | buf[l5 + 2] << 16 | buf[l5 + 3] << 24) >>> 0;
l5 += 4;
}
}
if (offset == 0)
throw new Error("Invalid offset 0");
var j3 = chunks.length - 1, off = offset;
while (j3 >= 0 && off >= chunks[j3].length) {
off -= chunks[j3].length;
--j3;
}
if (j3 < 0) {
if (off == 0)
off = chunks[j3 = 0].length;
else
throw new Error("Invalid offset beyond length");
}
if (length < off)
chunks.push(chunks[j3][subarray](chunks[j3].length - off, chunks[j3].length - off + length));
else {
if (off > 0) {
chunks.push(chunks[j3][subarray](chunks[j3].length - off));
length -= off;
}
++j3;
while (length >= chunks[j3].length) {
chunks.push(chunks[j3]);
length -= chunks[j3].length;
++j3;
}
if (length)
chunks.push(chunks[j3][subarray](0, length));
}
if (chunks.length > 25)
chunks = [u8concat(chunks)];
}
}
var clen = 0;
for (var u8i = 0; u8i < chunks.length; ++u8i)
clen += chunks[u8i].length;
if (clen != usz)
throw new Error("Unexpected length: ".concat(clen, " != ").concat(usz));
return chunks;
}
function decompress_iwa_file(buf) {
if (Array.isArray(buf))
buf = new Uint8Array(buf);
var out = [];
var l5 = 0;
while (l5 < buf.length) {
var t6 = buf[l5++];
var len = buf[l5] | buf[l5 + 1] << 8 | buf[l5 + 2] << 16;
l5 += 3;
out.push.apply(out, parse_snappy_chunk(t6, buf[subarray](l5, l5 + len)));
l5 += len;
}
if (l5 !== buf.length)
throw new Error("data is not a valid framed stream!");
return out.length == 1 ? out[0] : u8concat(out);
}
function numbers_format_cell(cell, t6, flags, ofmt, nfmt) {
var _a7, _b, _c, _d;
var ctype = t6 & 255, ver = t6 >> 8;
var fmt = ver >= 5 ? nfmt : ofmt;
dur:
if (flags & (ver > 4 ? 8 : 4) && cell.t == "n" && ctype == 7) {
var dstyle = ((_a7 = fmt[7]) == null ? void 0 : _a7[0]) ? varint_to_i32(fmt[7][0].data) : -1;
if (dstyle == -1)
break dur;
var dmin = ((_b = fmt[15]) == null ? void 0 : _b[0]) ? varint_to_i32(fmt[15][0].data) : -1;
var dmax = ((_c = fmt[16]) == null ? void 0 : _c[0]) ? varint_to_i32(fmt[16][0].data) : -1;
var auto = ((_d = fmt[40]) == null ? void 0 : _d[0]) ? varint_to_i32(fmt[40][0].data) : -1;
var d4 = cell.v, dd = d4;
autodur:
if (auto) {
if (d4 == 0) {
dmin = dmax = 2;
break autodur;
}
if (d4 >= 604800)
dmin = 1;
else if (d4 >= 86400)
dmin = 2;
else if (d4 >= 3600)
dmin = 4;
else if (d4 >= 60)
dmin = 8;
else if (d4 >= 1)
dmin = 16;
else
dmin = 32;
if (Math.floor(d4) != d4)
dmax = 32;
else if (d4 % 60)
dmax = 16;
else if (d4 % 3600)
dmax = 8;
else if (d4 % 86400)
dmax = 4;
else if (d4 % 604800)
dmax = 2;
if (dmax < dmin)
dmax = dmin;
}
if (dmin == -1 || dmax == -1)
break dur;
var dstr = [], zstr = [];
if (dmin == 1) {
dd = d4 / 604800;
if (dmax == 1) {
zstr.push('d"d"');
} else {
dd |= 0;
d4 -= 604800 * dd;
}
dstr.push(dd + (dstyle == 2 ? " week" + (dd == 1 ? "" : "s") : dstyle == 1 ? "w" : ""));
}
if (dmin <= 2 && dmax >= 2) {
dd = d4 / 86400;
if (dmax > 2) {
dd |= 0;
d4 -= 86400 * dd;
}
zstr.push('d"d"');
dstr.push(dd + (dstyle == 2 ? " day" + (dd == 1 ? "" : "s") : dstyle == 1 ? "d" : ""));
}
if (dmin <= 4 && dmax >= 4) {
dd = d4 / 3600;
if (dmax > 4) {
dd |= 0;
d4 -= 3600 * dd;
}
zstr.push((dmin >= 4 ? "[h]" : "h") + '"h"');
dstr.push(dd + (dstyle == 2 ? " hour" + (dd == 1 ? "" : "s") : dstyle == 1 ? "h" : ""));
}
if (dmin <= 8 && dmax >= 8) {
dd = d4 / 60;
if (dmax > 8) {
dd |= 0;
d4 -= 60 * dd;
}
zstr.push((dmin >= 8 ? "[m]" : "m") + '"m"');
if (dstyle == 0)
dstr.push((dmin == 8 && dmax == 8 || dd >= 10 ? "" : "0") + dd);
else
dstr.push(dd + (dstyle == 2 ? " minute" + (dd == 1 ? "" : "s") : dstyle == 1 ? "m" : ""));
}
if (dmin <= 16 && dmax >= 16) {
dd = d4;
if (dmax > 16) {
dd |= 0;
d4 -= dd;
}
zstr.push((dmin >= 16 ? "[s]" : "s") + '"s"');
if (dstyle == 0)
dstr.push((dmax == 16 && dmin == 16 || dd >= 10 ? "" : "0") + dd);
else
dstr.push(dd + (dstyle == 2 ? " second" + (dd == 1 ? "" : "s") : dstyle == 1 ? "s" : ""));
}
if (dmax >= 32) {
dd = Math.round(1e3 * d4);
if (dmin < 32)
zstr.push('.000"ms"');
if (dstyle == 0)
dstr.push((dd >= 100 ? "" : dd >= 10 ? "0" : "00") + dd);
else
dstr.push(dd + (dstyle == 2 ? " millisecond" + (dd == 1 ? "" : "s") : dstyle == 1 ? "ms" : ""));
}
cell.w = dstr.join(dstyle == 0 ? ":" : " ");
cell.z = zstr.join(dstyle == 0 ? '":"' : " ");
if (dstyle == 0)
cell.w = cell.w.replace(/:(\d\d\d)$/, ".$1");
}
}
function parse_old_storage(buf, lut, v4, opts) {
var dv = u8_to_dataview(buf);
var flags = dv.getUint32(4, true);
var ridx = -1, sidx = -1, zidx = -1, ieee = NaN, dc = 0, dt = new Date(Date.UTC(2001, 0, 1));
var doff = v4 > 1 ? 12 : 8;
if (flags & 2) {
zidx = dv.getUint32(doff, true);
doff += 4;
}
doff += popcnt(flags & (v4 > 1 ? 3468 : 396)) * 4;
if (flags & 512) {
ridx = dv.getUint32(doff, true);
doff += 4;
}
doff += popcnt(flags & (v4 > 1 ? 12288 : 4096)) * 4;
if (flags & 16) {
sidx = dv.getUint32(doff, true);
doff += 4;
}
if (flags & 32) {
ieee = dv.getFloat64(doff, true);
doff += 8;
}
if (flags & 64) {
dt.setTime(dt.getTime() + (dc = dv.getFloat64(doff, true)) * 1e3);
doff += 8;
}
if (v4 > 1) {
flags = dv.getUint32(8, true) >>> 16;
if (flags & 255) {
if (zidx == -1)
zidx = dv.getUint32(doff, true);
doff += 4;
}
}
var ret;
var t6 = buf[v4 >= 4 ? 1 : 2];
switch (t6) {
case 0:
return void 0;
case 2:
ret = { t: "n", v: ieee };
break;
case 3:
ret = { t: "s", v: lut.sst[sidx] };
break;
case 5:
{
if (opts == null ? void 0 : opts.cellDates)
ret = { t: "d", v: dt };
else
ret = { t: "n", v: dc / 86400 + 35430, z: table_fmt[14] };
}
break;
case 6:
ret = { t: "b", v: ieee > 0 };
break;
case 7:
ret = { t: "n", v: ieee };
break;
case 8:
ret = { t: "e", v: 0 };
break;
case 9:
{
if (ridx > -1) {
var rts = lut.rsst[ridx];
ret = { t: "s", v: rts.v };
if (rts.l)
ret.l = { Target: rts.l };
} else
throw new Error("Unsupported cell type ".concat(buf[subarray](0, 4)));
}
break;
default:
throw new Error("Unsupported cell type ".concat(buf[subarray](0, 4)));
}
if (zidx > -1)
numbers_format_cell(ret, t6 | v4 << 8, flags, lut.ofmt[zidx], lut.nfmt[zidx]);
if (t6 == 7)
ret.v /= 86400;
return ret;
}
function parse_new_storage(buf, lut, opts) {
var dv = u8_to_dataview(buf);
var flags = dv.getUint32(4, true);
var fields = dv.getUint32(8, true);
var doff = 12;
var ridx = -1, sidx = -1, zidx = -1, d128 = NaN, ieee = NaN, dc = 0, dt = new Date(Date.UTC(2001, 0, 1)), eidx = -1, fidx = -1;
if (fields & 1) {
d128 = readDecimal128LE(buf, doff);
doff += 16;
}
if (fields & 2) {
ieee = dv.getFloat64(doff, true);
doff += 8;
}
if (fields & 4) {
dt.setTime(dt.getTime() + (dc = dv.getFloat64(doff, true)) * 1e3);
doff += 8;
}
if (fields & 8) {
sidx = dv.getUint32(doff, true);
doff += 4;
}
if (fields & 16) {
ridx = dv.getUint32(doff, true);
doff += 4;
}
doff += popcnt(fields & 480) * 4;
if (fields & 512) {
fidx = dv.getUint32(doff, true);
doff += 4;
}
doff += popcnt(fields & 1024) * 4;
if (fields & 2048) {
eidx = dv.getUint32(doff, true);
doff += 4;
}
var ret;
var t6 = buf[1];
switch (t6) {
case 0:
ret = { t: "z" };
break;
case 2:
ret = { t: "n", v: d128 };
break;
case 3:
ret = { t: "s", v: lut.sst[sidx] };
break;
case 5:
{
if (opts == null ? void 0 : opts.cellDates)
ret = { t: "d", v: dt };
else
ret = { t: "n", v: dc / 86400 + 35430, z: table_fmt[14] };
}
break;
case 6:
ret = { t: "b", v: ieee > 0 };
break;
case 7:
ret = { t: "n", v: ieee };
break;
case 8:
ret = { t: "e", v: 0 };
break;
case 9:
{
if (ridx > -1) {
var rts = lut.rsst[ridx];
ret = { t: "s", v: rts.v };
if (rts.l)
ret.l = { Target: rts.l };
} else
throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(fields & 31, " : ").concat(buf[subarray](0, 4)));
}
break;
case 10:
ret = { t: "n", v: d128 };
break;
default:
throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(fields & 31, " : ").concat(buf[subarray](0, 4)));
}
doff += popcnt(fields & 4096) * 4;
if (fields & 516096) {
if (zidx == -1)
zidx = dv.getUint32(doff, true);
doff += 4;
}
if (fields & 524288) {
var cmntidx = dv.getUint32(doff, true);
doff += 4;
if (lut.cmnt[cmntidx])
ret.c = iwa_to_s5s_comment(lut.cmnt[cmntidx]);
}
if (zidx > -1)
numbers_format_cell(ret, t6 | 5 << 8, fields >> 13, lut.ofmt[zidx], lut.nfmt[zidx]);
if (t6 == 7)
ret.v /= 86400;
return ret;
}
function parse_cell_storage(buf, lut, opts) {
switch (buf[0]) {
case 0:
case 1:
case 2:
case 3:
case 4:
return parse_old_storage(buf, lut, buf[0], opts);
case 5:
return parse_new_storage(buf, lut, opts);
default:
throw new Error("Unsupported payload version ".concat(buf[0]));
}
}
function parse_TSP_Reference(buf) {
var pb = parse_shallow(buf);
return varint_to_i32(pb[1][0].data);
}
function parse_TST_TableDataList(M4, root) {
var pb = parse_shallow(root.data);
var type = varint_to_i32(pb[1][0].data);
var entries = pb[3];
var data = [];
(entries || []).forEach(function(entry) {
var _a7, _b;
var le2 = parse_shallow(entry.data);
if (!le2[1])
return;
var key = varint_to_i32(le2[1][0].data) >>> 0;
switch (type) {
case 1:
data[key] = u8str(le2[3][0].data);
break;
case 8:
{
var rt = M4[parse_TSP_Reference(le2[9][0].data)][0];
var rtp = parse_shallow(rt.data);
var rtpref = M4[parse_TSP_Reference(rtp[1][0].data)][0];
var mtype = varint_to_i32(rtpref.meta[1][0].data);
if (mtype != 2001)
throw new Error("2000 unexpected reference to ".concat(mtype));
var tswpsa = parse_shallow(rtpref.data);
var richtext = { v: tswpsa[3].map(function(x2) {
return u8str(x2.data);
}).join("") };
data[key] = richtext;
sfields:
if ((_a7 = tswpsa == null ? void 0 : tswpsa[11]) == null ? void 0 : _a7[0]) {
var smartfields = (_b = parse_shallow(tswpsa[11][0].data)) == null ? void 0 : _b[1];
if (!smartfields)
break sfields;
smartfields.forEach(function(sf) {
var _a22, _b2, _c;
var attr = parse_shallow(sf.data);
if ((_a22 = attr[2]) == null ? void 0 : _a22[0]) {
var obj = M4[parse_TSP_Reference((_b2 = attr[2]) == null ? void 0 : _b2[0].data)][0];
var objtype = varint_to_i32(obj.meta[1][0].data);
switch (objtype) {
case 2032:
var hlink = parse_shallow(obj.data);
if (((_c = hlink == null ? void 0 : hlink[2]) == null ? void 0 : _c[0]) && !richtext.l)
richtext.l = u8str(hlink[2][0].data);
break;
case 2039:
break;
default:
console.log("unrecognized ObjectAttribute type ".concat(objtype));
}
}
});
}
}
break;
case 2:
data[key] = parse_shallow(le2[6][0].data);
break;
case 3:
data[key] = parse_shallow(le2[5][0].data);
break;
case 10:
{
var cs = M4[parse_TSP_Reference(le2[10][0].data)][0];
data[key] = parse_TSD_CommentStorageArchive(M4, cs.data);
}
break;
default:
throw type;
}
});
return data;
}
function parse_TST_TileRowInfo(u8, type) {
var _a7, _b, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n;
var pb = parse_shallow(u8);
var R3 = varint_to_i32(pb[1][0].data) >>> 0;
var cnt = varint_to_i32(pb[2][0].data) >>> 0;
var wide_offsets = ((_b = (_a7 = pb[8]) == null ? void 0 : _a7[0]) == null ? void 0 : _b.data) && varint_to_i32(pb[8][0].data) > 0 || false;
var used_storage_u8, used_storage;
if (((_d = (_c = pb[7]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) && type != 0) {
used_storage_u8 = (_f = (_e2 = pb[7]) == null ? void 0 : _e2[0]) == null ? void 0 : _f.data;
used_storage = (_h = (_g = pb[6]) == null ? void 0 : _g[0]) == null ? void 0 : _h.data;
} else if (((_j = (_i = pb[4]) == null ? void 0 : _i[0]) == null ? void 0 : _j.data) && type != 1) {
used_storage_u8 = (_l = (_k = pb[4]) == null ? void 0 : _k[0]) == null ? void 0 : _l.data;
used_storage = (_n = (_m = pb[3]) == null ? void 0 : _m[0]) == null ? void 0 : _n.data;
} else
throw "NUMBERS Tile missing ".concat(type, " cell storage");
var width = wide_offsets ? 4 : 1;
var used_storage_offsets = u8_to_dataview(used_storage_u8);
var offsets = [];
for (var C3 = 0; C3 < used_storage_u8.length / 2; ++C3) {
var off = used_storage_offsets.getUint16(C3 * 2, true);
if (off < 65535)
offsets.push([C3, off]);
}
if (offsets.length != cnt)
throw "Expected ".concat(cnt, " cells, found ").concat(offsets.length);
var cells = [];
for (C3 = 0; C3 < offsets.length - 1; ++C3)
cells[offsets[C3][0]] = used_storage[subarray](offsets[C3][1] * width, offsets[C3 + 1][1] * width);
if (offsets.length >= 1)
cells[offsets[offsets.length - 1][0]] = used_storage[subarray](offsets[offsets.length - 1][1] * width);
return { R: R3, cells };
}
function parse_TST_Tile(M4, root) {
var _a7;
var pb = parse_shallow(root.data);
var storage2 = -1;
if ((_a7 = pb == null ? void 0 : pb[7]) == null ? void 0 : _a7[0]) {
if (varint_to_i32(pb[7][0].data) >>> 0)
storage2 = 1;
else
storage2 = 0;
}
var ri = mappa(pb[5], function(u8) {
return parse_TST_TileRowInfo(u8, storage2);
});
return {
nrows: varint_to_i32(pb[4][0].data) >>> 0,
data: ri.reduce(function(acc, x2) {
if (!acc[x2.R])
acc[x2.R] = [];
x2.cells.forEach(function(cell, C3) {
if (acc[x2.R][C3])
throw new Error("Duplicate cell r=".concat(x2.R, " c=").concat(C3));
acc[x2.R][C3] = cell;
});
return acc;
}, [])
};
}
function parse_TSD_CommentStorageArchive(M4, data) {
var _a7, _b, _c, _d, _e2, _f, _g, _h, _i, _j;
var out = { t: "", a: "" };
var csp = parse_shallow(data);
if ((_b = (_a7 = csp == null ? void 0 : csp[1]) == null ? void 0 : _a7[0]) == null ? void 0 : _b.data)
out.t = u8str((_d = (_c = csp == null ? void 0 : csp[1]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) || "";
if ((_f = (_e2 = csp == null ? void 0 : csp[3]) == null ? void 0 : _e2[0]) == null ? void 0 : _f.data) {
var as = M4[parse_TSP_Reference((_h = (_g = csp == null ? void 0 : csp[3]) == null ? void 0 : _g[0]) == null ? void 0 : _h.data)][0];
var asp = parse_shallow(as.data);
if ((_j = (_i = asp[1]) == null ? void 0 : _i[0]) == null ? void 0 : _j.data)
out.a = u8str(asp[1][0].data);
}
if (csp == null ? void 0 : csp[4]) {
out.replies = [];
csp[4].forEach(function(pi) {
var cs = M4[parse_TSP_Reference(pi.data)][0];
out.replies.push(parse_TSD_CommentStorageArchive(M4, cs.data));
});
}
return out;
}
function iwa_to_s5s_comment(iwa) {
var out = [];
out.push({ t: iwa.t || "", a: iwa.a, T: iwa.replies && iwa.replies.length > 0 });
if (iwa.replies)
iwa.replies.forEach(function(reply) {
out.push({ t: reply.t || "", a: reply.a, T: true });
});
return out;
}
function parse_TST_TableModelArchive(M4, root, ws, opts) {
var _a7, _b, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n;
var pb = parse_shallow(root.data);
var range2 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
range2.e.r = (varint_to_i32(pb[6][0].data) >>> 0) - 1;
if (range2.e.r < 0)
throw new Error("Invalid row varint ".concat(pb[6][0].data));
range2.e.c = (varint_to_i32(pb[7][0].data) >>> 0) - 1;
if (range2.e.c < 0)
throw new Error("Invalid col varint ".concat(pb[7][0].data));
ws["!ref"] = encode_range(range2);
var dense = ws["!data"] != null, dws = ws;
var store = parse_shallow(pb[4][0].data);
var lut = numbers_lut_new();
if ((_a7 = store[4]) == null ? void 0 : _a7[0])
lut.sst = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[4][0].data)][0]);
if ((_b = store[6]) == null ? void 0 : _b[0])
lut.fmla = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[6][0].data)][0]);
if ((_c = store[11]) == null ? void 0 : _c[0])
lut.ofmt = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[11][0].data)][0]);
if ((_d = store[12]) == null ? void 0 : _d[0])
lut.ferr = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[12][0].data)][0]);
if ((_e2 = store[17]) == null ? void 0 : _e2[0])
lut.rsst = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[17][0].data)][0]);
if ((_f = store[19]) == null ? void 0 : _f[0])
lut.cmnt = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[19][0].data)][0]);
if ((_g = store[22]) == null ? void 0 : _g[0])
lut.nfmt = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[22][0].data)][0]);
var tile = parse_shallow(store[3][0].data);
var _R = 0;
if (!((_h = store[9]) == null ? void 0 : _h[0]))
throw "NUMBERS file missing row tree";
var rtt = parse_shallow(store[9][0].data)[1].map(function(p4) {
return parse_shallow(p4.data);
});
rtt.forEach(function(kv) {
_R = varint_to_i32(kv[1][0].data);
var tidx = varint_to_i32(kv[2][0].data);
var t6 = tile[1][tidx];
if (!t6)
throw "NUMBERS missing tile " + tidx;
var tl = parse_shallow(t6.data);
var ref2 = M4[parse_TSP_Reference(tl[2][0].data)][0];
var mtype2 = varint_to_i32(ref2.meta[1][0].data);
if (mtype2 != 6002)
throw new Error("6001 unexpected reference to ".concat(mtype2));
var _tile = parse_TST_Tile(M4, ref2);
_tile.data.forEach(function(row, R3) {
row.forEach(function(buf, C3) {
var res = parse_cell_storage(buf, lut, opts);
if (res) {
if (dense) {
if (!dws["!data"][_R + R3])
dws["!data"][_R + R3] = [];
dws["!data"][_R + R3][C3] = res;
} else {
ws[encode_col(C3) + encode_row(_R + R3)] = res;
}
}
});
});
_R += _tile.nrows;
});
if ((_i = store[13]) == null ? void 0 : _i[0]) {
var ref = M4[parse_TSP_Reference(store[13][0].data)][0];
var mtype = varint_to_i32(ref.meta[1][0].data);
if (mtype != 6144)
throw new Error("Expected merge type 6144, found ".concat(mtype));
ws["!merges"] = (_j = parse_shallow(ref.data)) == null ? void 0 : _j[1].map(function(pi) {
var merge2 = parse_shallow(pi.data);
var origin = u8_to_dataview(parse_shallow(merge2[1][0].data)[1][0].data), size = u8_to_dataview(parse_shallow(merge2[2][0].data)[1][0].data);
return {
s: { r: origin.getUint16(0, true), c: origin.getUint16(2, true) },
e: {
r: origin.getUint16(0, true) + size.getUint16(0, true) - 1,
c: origin.getUint16(2, true) + size.getUint16(2, true) - 1
}
};
});
}
if (!((_k = ws["!merges"]) == null ? void 0 : _k.length) && ((_l = pb[47]) == null ? void 0 : _l[0])) {
var merge_owner = parse_shallow(pb[47][0].data);
if ((_m = merge_owner[2]) == null ? void 0 : _m[0]) {
var formula_store = parse_shallow(merge_owner[2][0].data);
if ((_n = formula_store[3]) == null ? void 0 : _n[0]) {
ws["!merges"] = mappa(formula_store[3], function(u5) {
var _a22, _b2, _c2, _d2, _e22;
var formula_pair = parse_shallow(u5);
var formula = parse_shallow(formula_pair[2][0].data);
var AST_node_array = parse_shallow(formula[1][0].data);
if (!((_a22 = AST_node_array[1]) == null ? void 0 : _a22[0]))
return;
var AST_node0 = parse_shallow(AST_node_array[1][0].data);
var AST_node_type = varint_to_i32(AST_node0[1][0].data);
if (AST_node_type != 67)
return;
var AST_colon_tract = parse_shallow(AST_node0[40][0].data);
if (!((_b2 = AST_colon_tract[3]) == null ? void 0 : _b2[0]) || !((_c2 = AST_colon_tract[4]) == null ? void 0 : _c2[0]))
return;
var colrange = parse_shallow(AST_colon_tract[3][0].data);
var rowrange = parse_shallow(AST_colon_tract[4][0].data);
var c6 = varint_to_i32(colrange[1][0].data);
var C3 = ((_d2 = colrange[2]) == null ? void 0 : _d2[0]) ? varint_to_i32(colrange[2][0].data) : c6;
var r8 = varint_to_i32(rowrange[1][0].data);
var R3 = ((_e22 = rowrange[2]) == null ? void 0 : _e22[0]) ? varint_to_i32(rowrange[2][0].data) : r8;
return { s: { r: r8, c: c6 }, e: { r: R3, c: C3 } };
}).filter(function(x2) {
return x2 != null;
});
}
}
}
}
function parse_TST_TableInfoArchive(M4, root, opts) {
var pb = parse_shallow(root.data);
var out = { "!ref": "A1" };
if (opts == null ? void 0 : opts.dense)
out["!data"] = [];
var tableref = M4[parse_TSP_Reference(pb[2][0].data)];
var mtype = varint_to_i32(tableref[0].meta[1][0].data);
if (mtype != 6001)
throw new Error("6000 unexpected reference to ".concat(mtype));
parse_TST_TableModelArchive(M4, tableref[0], out, opts);
return out;
}
function parse_TN_SheetArchive(M4, root, opts) {
var _a7;
var pb = parse_shallow(root.data);
var out = {
name: ((_a7 = pb[1]) == null ? void 0 : _a7[0]) ? u8str(pb[1][0].data) : "",
sheets: []
};
var shapeoffs = mappa(pb[2], parse_TSP_Reference);
shapeoffs.forEach(function(off) {
M4[off].forEach(function(m4) {
var mtype = varint_to_i32(m4.meta[1][0].data);
if (mtype == 6e3)
out.sheets.push(parse_TST_TableInfoArchive(M4, m4, opts));
});
});
return out;
}
function parse_TN_DocumentArchive(M4, root, opts) {
var _a7;
var out = book_new();
out.Workbook = { WBProps: { date1904: true } };
var pb = parse_shallow(root.data);
if ((_a7 = pb[2]) == null ? void 0 : _a7[0])
throw new Error("Keynote presentations are not supported");
var sheetoffs = mappa(pb[1], parse_TSP_Reference);
sheetoffs.forEach(function(off) {
M4[off].forEach(function(m4) {
var mtype = varint_to_i32(m4.meta[1][0].data);
if (mtype == 2) {
var root2 = parse_TN_SheetArchive(M4, m4, opts);
root2.sheets.forEach(function(sheet, idx) {
book_append_sheet(out, sheet, idx == 0 ? root2.name : root2.name + "_" + idx, true);
});
}
});
});
if (out.SheetNames.length == 0)
throw new Error("Empty NUMBERS file");
out.bookType = "numbers";
return out;
}
function parse_numbers_iwa(cfb, opts) {
var _a7, _b, _c, _d, _e2, _f, _g;
var M4 = {}, indices = [];
cfb.FullPaths.forEach(function(p4) {
if (p4.match(/\.iwpv2/))
throw new Error("Unsupported password protection");
});
cfb.FileIndex.forEach(function(s6) {
if (!s6.name.match(/\.iwa$/))
return;
if (s6.content[0] != 0)
return;
var o9;
try {
o9 = decompress_iwa_file(s6.content);
} catch (e9) {
return console.log("?? " + s6.content.length + " " + (e9.message || e9));
}
var packets;
try {
packets = parse_iwa_file(o9);
} catch (e9) {
return console.log("## " + (e9.message || e9));
}
packets.forEach(function(packet) {
M4[packet.id] = packet.messages;
indices.push(packet.id);
});
});
if (!indices.length)
throw new Error("File has no messages");
if (((_c = (_b = (_a7 = M4 == null ? void 0 : M4[1]) == null ? void 0 : _a7[0].meta) == null ? void 0 : _b[1]) == null ? void 0 : _c[0].data) && varint_to_i32(M4[1][0].meta[1][0].data) == 1e4)
throw new Error("Pages documents are not supported");
var docroot = ((_g = (_f = (_e2 = (_d = M4 == null ? void 0 : M4[1]) == null ? void 0 : _d[0]) == null ? void 0 : _e2.meta) == null ? void 0 : _f[1]) == null ? void 0 : _g[0].data) && varint_to_i32(M4[1][0].meta[1][0].data) == 1 && M4[1][0];
if (!docroot)
indices.forEach(function(idx) {
M4[idx].forEach(function(iwam) {
var mtype = varint_to_i32(iwam.meta[1][0].data) >>> 0;
if (mtype == 1) {
if (!docroot)
docroot = iwam;
else
throw new Error("Document has multiple roots");
}
});
});
if (!docroot)
throw new Error("Cannot find Document root");
return parse_TN_DocumentArchive(M4, docroot, opts);
}
function fix_opts_func(defaults4) {
return function fix_opts(opts) {
for (var i7 = 0; i7 != defaults4.length; ++i7) {
var d4 = defaults4[i7];
if (opts[d4[0]] === void 0) opts[d4[0]] = d4[1];
if (d4[2] === "n") opts[d4[0]] = Number(opts[d4[0]]);
}
};
}
function fix_read_opts(opts) {
fix_opts_func([
["cellNF", false],
/* emit cell number format string as .z */
["cellHTML", true],
/* emit html string as .h */
["cellFormula", true],
/* emit formulae as .f */
["cellStyles", false],
/* emits style/theme as .s */
["cellText", true],
/* emit formatted text as .w */
["cellDates", false],
/* emit date cells with type `d` */
["sheetStubs", false],
/* emit empty cells */
["sheetRows", 0, "n"],
/* read n rows (0 = read all rows) */
["bookDeps", false],
/* parse calculation chains */
["bookSheets", false],
/* only try to get sheet names (no Sheets) */
["bookProps", false],
/* only try to get properties (no Sheets) */
["bookFiles", false],
/* include raw file structure (keys, files, cfb) */
["bookVBA", false],
/* include vba raw data (vbaraw) */
["password", ""],
/* password */
["WTF", false]
/* WTF mode (throws errors) */
])(opts);
}
function get_sheet_type(n7) {
if (RELS.WS.indexOf(n7) > -1) return "sheet";
if (RELS.CS && n7 == RELS.CS) return "chart";
if (RELS.DS && n7 == RELS.DS) return "dialog";
if (RELS.MS && n7 == RELS.MS) return "macro";
return n7 && n7.length ? n7 : "sheet";
}
function safe_parse_wbrels(wbrels, sheets) {
if (!wbrels) return 0;
try {
wbrels = sheets.map(function pwbr(w3) {
if (!w3.id) w3.id = w3.strRelID;
return [w3.name, wbrels["!id"][w3.id].Target, get_sheet_type(wbrels["!id"][w3.id].Type)];
});
} catch (e9) {
return null;
}
return !wbrels || wbrels.length === 0 ? null : wbrels;
}
function parse_sheet_legacy_drawing(sheet, type, zip, path6, idx, opts, wb, comments) {
if (!sheet || !sheet["!legdrawel"]) return;
var dfile = resolve_path(sheet["!legdrawel"].Target, path6);
var draw2 = getzipstr(zip, dfile, true);
if (draw2) parse_vml(utf8read(draw2), sheet, comments || []);
}
function safe_parse_sheet(zip, path6, relsPath, sheet, idx, sheetRels, sheets, stype, opts, wb, themes, styles2) {
try {
sheetRels[sheet] = parse_rels(getzipstr(zip, relsPath, true), path6);
var data = getzipdata(zip, path6);
var _ws;
switch (stype) {
case "sheet":
_ws = parse_ws(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2);
break;
case "chart":
_ws = parse_cs(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2);
if (!_ws || !_ws["!drawel"]) break;
var dfile = resolve_path(_ws["!drawel"].Target, path6);
var drelsp = get_rels_path(dfile);
var draw2 = parse_drawing(getzipstr(zip, dfile, true), parse_rels(getzipstr(zip, drelsp, true), dfile));
var chartp = resolve_path(draw2, dfile);
var crelsp = get_rels_path(chartp);
_ws = parse_chart(getzipstr(zip, chartp, true), chartp, opts, parse_rels(getzipstr(zip, crelsp, true), chartp), wb, _ws);
break;
case "macro":
_ws = parse_ms(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2);
break;
case "dialog":
_ws = parse_ds(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2);
break;
default:
throw new Error("Unrecognized sheet type " + stype);
}
sheets[sheet] = _ws;
var comments = [], tcomments = [];
if (sheetRels && sheetRels[sheet]) keys(sheetRels[sheet]).forEach(function(n7) {
var dfile2 = "";
if (sheetRels[sheet][n7].Type == RELS.CMNT) {
dfile2 = resolve_path(sheetRels[sheet][n7].Target, path6);
comments = parse_cmnt(getzipdata(zip, dfile2, true), dfile2, opts);
if (!comments || !comments.length) return;
sheet_insert_comments(_ws, comments, false);
}
if (sheetRels[sheet][n7].Type == RELS.TCMNT) {
dfile2 = resolve_path(sheetRels[sheet][n7].Target, path6);
tcomments = tcomments.concat(parse_tcmnt_xml(getzipdata(zip, dfile2, true), opts));
}
});
if (tcomments && tcomments.length) sheet_insert_comments(_ws, tcomments, true, opts.people || []);
parse_sheet_legacy_drawing(_ws, stype, zip, path6, idx, opts, wb, comments);
} catch (e9) {
if (opts.WTF) throw e9;
}
}
function strip_front_slash(x2) {
return x2.charAt(0) == "/" ? x2.slice(1) : x2;
}
function parse_zip(zip, opts) {
make_ssf();
opts = opts || {};
fix_read_opts(opts);
if (safegetzipfile(zip, "META-INF/manifest.xml")) return parse_ods(zip, opts);
if (safegetzipfile(zip, "objectdata.xml")) return parse_ods(zip, opts);
if (safegetzipfile(zip, "Index/Document.iwa")) {
if (typeof Uint8Array == "undefined") throw new Error("NUMBERS file parsing requires Uint8Array support");
if (typeof parse_numbers_iwa != "undefined") {
if (zip.FileIndex) return parse_numbers_iwa(zip, opts);
var _zip = CFB.utils.cfb_new();
zipentries(zip).forEach(function(e9) {
zip_add_file(_zip, e9, getzipbin(zip, e9));
});
return parse_numbers_iwa(_zip, opts);
}
throw new Error("Unsupported NUMBERS file");
}
if (!safegetzipfile(zip, "[Content_Types].xml")) {
if (safegetzipfile(zip, "index.xml.gz")) throw new Error("Unsupported NUMBERS 08 file");
if (safegetzipfile(zip, "index.xml")) throw new Error("Unsupported NUMBERS 09 file");
var index_zip = CFB.find(zip, "Index.zip");
if (index_zip) {
opts = dup(opts);
delete opts.type;
if (typeof index_zip.content == "string") opts.type = "binary";
if (typeof Bun !== "undefined" && Buffer.isBuffer(index_zip.content)) return readSync(new Uint8Array(index_zip.content), opts);
return readSync(index_zip.content, opts);
}
throw new Error("Unsupported ZIP file");
}
var entries = zipentries(zip);
var dir = parse_ct(getzipstr(zip, "[Content_Types].xml"));
var xlsb = false;
var sheets, binname;
if (dir.workbooks.length === 0) {
binname = "xl/workbook.xml";
if (getzipdata(zip, binname, true)) dir.workbooks.push(binname);
}
if (dir.workbooks.length === 0) {
binname = "xl/workbook.bin";
if (!getzipdata(zip, binname, true)) throw new Error("Could not find workbook");
dir.workbooks.push(binname);
xlsb = true;
}
if (dir.workbooks[0].slice(-3) == "bin") xlsb = true;
var themes = {};
var styles2 = {};
if (!opts.bookSheets && !opts.bookProps) {
strs = [];
if (dir.sst) try {
strs = parse_sst(getzipdata(zip, strip_front_slash(dir.sst)), dir.sst, opts);
} catch (e9) {
if (opts.WTF) throw e9;
}
if (opts.cellStyles && dir.themes.length) themes = parse_theme_xml(getzipstr(zip, dir.themes[0].replace(/^\//, ""), true) || "", opts);
if (dir.style) styles2 = parse_sty(getzipdata(zip, strip_front_slash(dir.style)), dir.style, themes, opts);
}
dir.links.map(function(link) {
try {
var rels = parse_rels(getzipstr(zip, get_rels_path(strip_front_slash(link))), link);
return parse_xlink(getzipdata(zip, strip_front_slash(link)), rels, link, opts);
} catch (e9) {
}
});
var wb = parse_wb(getzipdata(zip, strip_front_slash(dir.workbooks[0])), dir.workbooks[0], opts);
var props = {}, propdata = "";
if (dir.coreprops.length) {
propdata = getzipdata(zip, strip_front_slash(dir.coreprops[0]), true);
if (propdata) props = parse_core_props(propdata);
if (dir.extprops.length !== 0) {
propdata = getzipdata(zip, strip_front_slash(dir.extprops[0]), true);
if (propdata) parse_ext_props(propdata, props, opts);
}
}
var custprops = {};
if (!opts.bookSheets || opts.bookProps) {
if (dir.custprops.length !== 0) {
propdata = getzipstr(zip, strip_front_slash(dir.custprops[0]), true);
if (propdata) custprops = parse_cust_props(propdata, opts);
}
}
var out = {};
if (opts.bookSheets || opts.bookProps) {
if (wb.Sheets) sheets = wb.Sheets.map(function pluck(x2) {
return x2.name;
});
else if (props.Worksheets && props.SheetNames.length > 0) sheets = props.SheetNames;
if (opts.bookProps) {
out.Props = props;
out.Custprops = custprops;
}
if (opts.bookSheets && typeof sheets !== "undefined") out.SheetNames = sheets;
if (opts.bookSheets ? out.SheetNames : opts.bookProps) return out;
}
sheets = {};
var deps = {};
if (opts.bookDeps && dir.calcchain) deps = parse_cc(getzipdata(zip, strip_front_slash(dir.calcchain)), dir.calcchain, opts);
var i7 = 0;
var sheetRels = {};
var path6, relsPath;
{
var wbsheets = wb.Sheets;
props.Worksheets = wbsheets.length;
props.SheetNames = [];
for (var j3 = 0; j3 != wbsheets.length; ++j3) {
props.SheetNames[j3] = wbsheets[j3].name;
}
}
var wbext = xlsb ? "bin" : "xml";
var wbrelsi = dir.workbooks[0].lastIndexOf("/");
var wbrelsfile = (dir.workbooks[0].slice(0, wbrelsi + 1) + "_rels/" + dir.workbooks[0].slice(wbrelsi + 1) + ".rels").replace(/^\//, "");
if (!safegetzipfile(zip, wbrelsfile)) wbrelsfile = "xl/_rels/workbook." + wbext + ".rels";
var wbrels = parse_rels(getzipstr(zip, wbrelsfile, true), wbrelsfile.replace(/_rels.*/, "s5s"));
if ((dir.metadata || []).length >= 1) {
opts.xlmeta = parse_xlmeta(getzipdata(zip, strip_front_slash(dir.metadata[0])), dir.metadata[0], opts);
}
if ((dir.people || []).length >= 1) {
opts.people = parse_people_xml(getzipdata(zip, strip_front_slash(dir.people[0])), opts);
}
if (wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets);
var nmode = getzipdata(zip, "xl/worksheets/sheet.xml", true) ? 1 : 0;
wsloop: for (i7 = 0; i7 != props.Worksheets; ++i7) {
var stype = "sheet";
if (wbrels && wbrels[i7]) {
path6 = "xl/" + wbrels[i7][1].replace(/[\/]?xl\//, "");
if (!safegetzipfile(zip, path6)) path6 = wbrels[i7][1];
if (!safegetzipfile(zip, path6)) path6 = wbrelsfile.replace(/_rels\/[\S\s]*$/, "") + wbrels[i7][1];
stype = wbrels[i7][2];
} else {
path6 = "xl/worksheets/sheet" + (i7 + 1 - nmode) + "." + wbext;
path6 = path6.replace(/sheet0\./, "sheet.");
}
relsPath = path6.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels");
if (opts && opts.sheets != null) switch (typeof opts.sheets) {
case "number":
if (i7 != opts.sheets) continue wsloop;
break;
case "string":
if (props.SheetNames[i7].toLowerCase() != opts.sheets.toLowerCase()) continue wsloop;
break;
default:
if (Array.isArray && Array.isArray(opts.sheets)) {
var snjseen = false;
for (var snj = 0; snj != opts.sheets.length; ++snj) {
if (typeof opts.sheets[snj] == "number" && opts.sheets[snj] == i7) snjseen = 1;
if (typeof opts.sheets[snj] == "string" && opts.sheets[snj].toLowerCase() == props.SheetNames[i7].toLowerCase()) snjseen = 1;
}
if (!snjseen) continue wsloop;
}
}
safe_parse_sheet(zip, path6, relsPath, props.SheetNames[i7], i7, sheetRels, sheets, stype, opts, wb, themes, styles2);
}
out = {
Directory: dir,
Workbook: wb,
Props: props,
Custprops: custprops,
Deps: deps,
Sheets: sheets,
SheetNames: props.SheetNames,
Strings: strs,
Styles: styles2,
Themes: themes,
SSF: dup(table_fmt)
};
if (opts && opts.bookFiles) {
if (zip.files) {
out.keys = entries;
out.files = zip.files;
} else {
out.keys = [];
out.files = {};
zip.FullPaths.forEach(function(p4, idx) {
p4 = p4.replace(/^Root Entry[\/]/, "");
out.keys.push(p4);
out.files[p4] = zip.FileIndex[idx];
});
}
}
if (opts && opts.bookVBA) {
if (dir.vba.length > 0) out.vbaraw = getzipdata(zip, strip_front_slash(dir.vba[0]), true);
else if (dir.defaults && dir.defaults.bin === CT_VBA) out.vbaraw = getzipdata(zip, "xl/vbaProject.bin", true);
}
out.bookType = xlsb ? "xlsb" : "xlsx";
return out;
}
function parse_xlsxcfb(cfb, _opts) {
var opts = _opts || {};
var f4 = "Workbook", data = CFB.find(cfb, f4);
try {
f4 = "/!DataSpaces/Version";
data = CFB.find(cfb, f4);
if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
parse_DataSpaceVersionInfo(data.content);
f4 = "/!DataSpaces/DataSpaceMap";
data = CFB.find(cfb, f4);
if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
var dsm = parse_DataSpaceMap(data.content);
if (dsm.length !== 1 || dsm[0].comps.length !== 1 || dsm[0].comps[0].t !== 0 || dsm[0].name !== "StrongEncryptionDataSpace" || dsm[0].comps[0].v !== "EncryptedPackage")
throw new Error("ECMA-376 Encrypted file bad " + f4);
f4 = "/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace";
data = CFB.find(cfb, f4);
if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
var seds = parse_DataSpaceDefinition(data.content);
if (seds.length != 1 || seds[0] != "StrongEncryptionTransform")
throw new Error("ECMA-376 Encrypted file bad " + f4);
f4 = "/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary";
data = CFB.find(cfb, f4);
if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
parse_Primary(data.content);
} catch (e9) {
}
f4 = "/EncryptionInfo";
data = CFB.find(cfb, f4);
if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
var einfo = parse_EncryptionInfo(data.content);
f4 = "/EncryptedPackage";
data = CFB.find(cfb, f4);
if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4);
if (einfo[0] == 4 && typeof decrypt_agile !== "undefined") return decrypt_agile(einfo[1], data.content, opts.password || "", opts);
if (einfo[0] == 2 && typeof decrypt_std76 !== "undefined") return decrypt_std76(einfo[1], data.content, opts.password || "", opts);
throw new Error("File is password-protected");
}
function firstbyte(f4, o9) {
var x2 = "";
switch ((o9 || {}).type || "base64") {
case "buffer":
return [f4[0], f4[1], f4[2], f4[3], f4[4], f4[5], f4[6], f4[7]];
case "base64":
x2 = Base64_decode(f4.slice(0, 12));
break;
case "binary":
x2 = f4;
break;
case "array":
return [f4[0], f4[1], f4[2], f4[3], f4[4], f4[5], f4[6], f4[7]];
default:
throw new Error("Unrecognized type " + (o9 && o9.type || "undefined"));
}
return [x2.charCodeAt(0), x2.charCodeAt(1), x2.charCodeAt(2), x2.charCodeAt(3), x2.charCodeAt(4), x2.charCodeAt(5), x2.charCodeAt(6), x2.charCodeAt(7)];
}
function read_cfb(cfb, opts) {
if (CFB.find(cfb, "EncryptedPackage")) return parse_xlsxcfb(cfb, opts);
return parse_xlscfb(cfb, opts);
}
function read_zip(data, opts) {
var zip, d4 = data;
var o9 = opts || {};
if (!o9.type) o9.type = has_buf && Buffer.isBuffer(data) ? "buffer" : "base64";
zip = zip_read(d4, o9);
return parse_zip(zip, o9);
}
function read_plaintext(data, o9) {
var i7 = 0;
main: while (i7 < data.length) switch (data.charCodeAt(i7)) {
case 10:
case 13:
case 32:
++i7;
break;
case 60:
return parse_xlml(data.slice(i7), o9);
default:
break main;
}
return PRN.to_workbook(data, o9);
}
function read_plaintext_raw(data, o9) {
var str2 = "", bytes = firstbyte(data, o9);
switch (o9.type) {
case "base64":
str2 = Base64_decode(data);
break;
case "binary":
str2 = data;
break;
case "buffer":
str2 = data.toString("binary");
break;
case "array":
str2 = cc2str(data);
break;
default:
throw new Error("Unrecognized type " + o9.type);
}
if (bytes[0] == 239 && bytes[1] == 187 && bytes[2] == 191) str2 = utf8read(str2);
o9.type = "binary";
return read_plaintext(str2, o9);
}
function read_utf16(data, o9) {
var d4 = data;
if (o9.type == "base64") d4 = Base64_decode(d4);
if (typeof ArrayBuffer !== "undefined" && data instanceof ArrayBuffer) d4 = new Uint8Array(data);
d4 = typeof $cptable !== "undefined" ? $cptable.utils.decode(1200, d4.slice(2), "str") : has_buf && Buffer.isBuffer(data) ? data.slice(2).toString("utf16le") : typeof Uint8Array !== "undefined" && d4 instanceof Uint8Array ? typeof TextDecoder !== "undefined" ? new TextDecoder("utf-16le").decode(d4.slice(2)) : utf16lereadu(d4.slice(2)) : utf16leread(d4.slice(2));
o9.type = "binary";
return read_plaintext(d4, o9);
}
function bstrify(data) {
return !data.match(/[^\x00-\x7F]/) ? data : utf8write(data);
}
function read_prn(data, d4, o9, str2) {
if (str2) {
o9.type = "string";
return PRN.to_workbook(data, o9);
}
return PRN.to_workbook(d4, o9);
}
function readSync(data, opts) {
reset_cp();
var o9 = opts || {};
if (o9.codepage && typeof $cptable === "undefined") console.error("Codepage tables are not loaded. Non-ASCII characters may not give expected results");
if (typeof ArrayBuffer !== "undefined" && data instanceof ArrayBuffer) return readSync(new Uint8Array(data), (o9 = dup(o9), o9.type = "array", o9));
if (typeof Int8Array !== "undefined" && data instanceof Int8Array) return readSync(new Uint8Array(data.buffer, data.byteOffset, data.length), o9);
if (typeof Uint8Array !== "undefined" && data instanceof Uint8Array && !o9.type) o9.type = typeof Deno !== "undefined" ? "buffer" : "array";
var d4 = data, n7 = [0, 0, 0, 0], str2 = false;
if (o9.cellStyles) {
o9.cellNF = true;
o9.sheetStubs = true;
}
_ssfopts = {};
if (o9.dateNF) _ssfopts.dateNF = o9.dateNF;
if (!o9.type) o9.type = has_buf && Buffer.isBuffer(data) ? "buffer" : "base64";
if (o9.type == "file") {
o9.type = has_buf ? "buffer" : "binary";
d4 = read_binary(data);
if (typeof Uint8Array !== "undefined" && !has_buf) o9.type = "array";
}
if (o9.type == "string") {
str2 = true;
o9.type = "binary";
o9.codepage = 65001;
d4 = bstrify(data);
}
if (o9.type == "array" && typeof Uint8Array !== "undefined" && data instanceof Uint8Array && typeof ArrayBuffer !== "undefined") {
var ab = new ArrayBuffer(3), vu = new Uint8Array(ab);
vu.foo = "bar";
if (!vu.foo) {
o9 = dup(o9);
o9.type = "array";
return readSync(ab2a(d4), o9);
}
}
switch ((n7 = firstbyte(d4, o9))[0]) {
case 208:
if (n7[1] === 207 && n7[2] === 17 && n7[3] === 224 && n7[4] === 161 && n7[5] === 177 && n7[6] === 26 && n7[7] === 225) return read_cfb(CFB.read(d4, o9), o9);
break;
case 9:
if (n7[1] <= 8) return parse_xlscfb(d4, o9);
break;
case 60:
return parse_xlml(d4, o9);
case 73:
if (n7[1] === 73 && n7[2] === 42 && n7[3] === 0) throw new Error("TIFF Image File is not a spreadsheet");
if (n7[1] === 68) return read_wb_ID(d4, o9);
break;
case 84:
if (n7[1] === 65 && n7[2] === 66 && n7[3] === 76) return DIF.to_workbook(d4, o9);
break;
case 80:
return n7[1] === 75 && n7[2] < 9 && n7[3] < 9 ? read_zip(d4, o9) : read_prn(data, d4, o9, str2);
case 239:
return n7[3] === 60 ? parse_xlml(d4, o9) : read_prn(data, d4, o9, str2);
case 255:
if (n7[1] === 254) {
return read_utf16(d4, o9);
} else if (n7[1] === 0 && n7[2] === 2 && n7[3] === 0) return WK_.to_workbook(d4, o9);
break;
case 0:
if (n7[1] === 0) {
if (n7[2] >= 2 && n7[3] === 0) return WK_.to_workbook(d4, o9);
if (n7[2] === 0 && (n7[3] === 8 || n7[3] === 9)) return WK_.to_workbook(d4, o9);
}
break;
case 3:
case 131:
case 139:
case 140:
return DBF.to_workbook(d4, o9);
case 123:
if (n7[1] === 92 && n7[2] === 114 && n7[3] === 116) return rtf_to_workbook(d4, o9);
break;
case 10:
case 13:
case 32:
return read_plaintext_raw(d4, o9);
case 137:
if (n7[1] === 80 && n7[2] === 78 && n7[3] === 71) throw new Error("PNG Image File is not a spreadsheet");
break;
case 8:
if (n7[1] === 231) throw new Error("Unsupported Multiplan 1.x file!");
break;
case 12:
if (n7[1] === 236) throw new Error("Unsupported Multiplan 2.x file!");
if (n7[1] === 237) throw new Error("Unsupported Multiplan 3.x file!");
break;
}
if (DBF_SUPPORTED_VERSIONS.indexOf(n7[0]) > -1 && n7[2] <= 12 && n7[3] <= 31) return DBF.to_workbook(d4, o9);
return read_prn(data, d4, o9, str2);
}
function make_json_row(sheet, r8, R3, cols, header, hdr, o9) {
var rr = encode_row(R3);
var defval = o9.defval, raw = o9.raw || !Object.prototype.hasOwnProperty.call(o9, "raw");
var isempty = true, dense = sheet["!data"] != null;
var row = header === 1 ? [] : {};
if (header !== 1) {
if (Object.defineProperty) try {
Object.defineProperty(row, "__rowNum__", { value: R3, enumerable: false });
} catch (e9) {
row.__rowNum__ = R3;
}
else row.__rowNum__ = R3;
}
if (!dense || sheet["!data"][R3]) for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
var val2 = dense ? (sheet["!data"][R3] || [])[C3] : sheet[cols[C3] + rr];
if (val2 == null || val2.t === void 0) {
if (defval === void 0) continue;
if (hdr[C3] != null) {
row[hdr[C3]] = defval;
}
continue;
}
var v4 = val2.v;
switch (val2.t) {
case "z":
if (v4 == null) break;
continue;
case "e":
v4 = v4 == 0 ? null : void 0;
break;
case "s":
case "b":
case "n":
if (!val2.z || !fmt_is_date(val2.z)) break;
v4 = numdate(v4);
if (typeof v4 == "number") break;
/* falls through */
case "d":
if (!(o9 && (o9.UTC || o9.raw === false))) v4 = utc_to_local(new Date(v4));
break;
default:
throw new Error("unrecognized type " + val2.t);
}
if (hdr[C3] != null) {
if (v4 == null) {
if (val2.t == "e" && v4 === null) row[hdr[C3]] = null;
else if (defval !== void 0) row[hdr[C3]] = defval;
else if (raw && v4 === null) row[hdr[C3]] = null;
else continue;
} else {
row[hdr[C3]] = (val2.t === "n" && typeof o9.rawNumbers === "boolean" ? o9.rawNumbers : raw) ? v4 : format_cell(val2, v4, o9);
}
if (v4 != null) isempty = false;
}
}
return { row, isempty };
}
function sheet_to_json(sheet, opts) {
if (sheet == null || sheet["!ref"] == null) return [];
var val2 = { t: "n", v: 0 }, header = 0, offset = 1, hdr = [], v4 = 0, vv = "";
var r8 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
var o9 = opts || {};
var range2 = o9.range != null ? o9.range : sheet["!ref"];
if (o9.header === 1) header = 1;
else if (o9.header === "A") header = 2;
else if (Array.isArray(o9.header)) header = 3;
else if (o9.header == null) header = 0;
switch (typeof range2) {
case "string":
r8 = safe_decode_range(range2);
break;
case "number":
r8 = safe_decode_range(sheet["!ref"]);
r8.s.r = range2;
break;
default:
r8 = range2;
}
if (header > 0) offset = 0;
var rr = encode_row(r8.s.r);
var cols = [];
var out = [];
var outi = 0, counter = 0;
var dense = sheet["!data"] != null;
var R3 = r8.s.r, C3 = 0;
var header_cnt = {};
if (dense && !sheet["!data"][R3]) sheet["!data"][R3] = [];
var colinfo = o9.skipHidden && sheet["!cols"] || [];
var rowinfo = o9.skipHidden && sheet["!rows"] || [];
for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
if ((colinfo[C3] || {}).hidden) continue;
cols[C3] = encode_col(C3);
val2 = dense ? sheet["!data"][R3][C3] : sheet[cols[C3] + rr];
switch (header) {
case 1:
hdr[C3] = C3 - r8.s.c;
break;
case 2:
hdr[C3] = cols[C3];
break;
case 3:
hdr[C3] = o9.header[C3 - r8.s.c];
break;
default:
if (val2 == null) val2 = { w: "__EMPTY", t: "s" };
vv = v4 = format_cell(val2, null, o9);
counter = header_cnt[v4] || 0;
if (!counter) header_cnt[v4] = 1;
else {
do {
vv = v4 + "_" + counter++;
} while (header_cnt[vv]);
header_cnt[v4] = counter;
header_cnt[vv] = 1;
}
hdr[C3] = vv;
}
}
for (R3 = r8.s.r + offset; R3 <= r8.e.r; ++R3) {
if ((rowinfo[R3] || {}).hidden) continue;
var row = make_json_row(sheet, r8, R3, cols, header, hdr, o9);
if (row.isempty === false || (header === 1 ? o9.blankrows !== false : !!o9.blankrows)) out[outi++] = row.row;
}
out.length = outi;
return out;
}
function make_csv_row(sheet, r8, R3, cols, fs, rs, FS, w3, o9) {
var isempty = true;
var row = [], txt = "", rr = encode_row(R3);
var dense = sheet["!data"] != null;
var datarow = dense && sheet["!data"][R3] || [];
for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
if (!cols[C3]) continue;
var val2 = dense ? datarow[C3] : sheet[cols[C3] + rr];
if (val2 == null) txt = "";
else if (val2.v != null) {
isempty = false;
txt = "" + (o9.rawNumbers && val2.t == "n" ? val2.v : format_cell(val2, null, o9));
for (var i7 = 0, cc = 0; i7 !== txt.length; ++i7) if ((cc = txt.charCodeAt(i7)) === fs || cc === rs || cc === 34 || o9.forceQuotes) {
txt = '"' + txt.replace(qreg, '""') + '"';
break;
}
if (txt == "ID" && w3 == 0 && row.length == 0) txt = '"ID"';
} else if (val2.f != null && !val2.F) {
isempty = false;
txt = "=" + val2.f;
if (txt.indexOf(",") >= 0) txt = '"' + txt.replace(qreg, '""') + '"';
} else txt = "";
row.push(txt);
}
if (o9.strip) while (row[row.length - 1] === "") --row.length;
if (o9.blankrows === false && isempty) return null;
return row.join(FS);
}
function sheet_to_csv(sheet, opts) {
var out = [];
var o9 = opts == null ? {} : opts;
if (sheet == null || sheet["!ref"] == null) return "";
var r8 = safe_decode_range(sheet["!ref"]);
var FS = o9.FS !== void 0 ? o9.FS : ",", fs = FS.charCodeAt(0);
var RS = o9.RS !== void 0 ? o9.RS : "\n", rs = RS.charCodeAt(0);
var row = "", cols = [];
var colinfo = o9.skipHidden && sheet["!cols"] || [];
var rowinfo = o9.skipHidden && sheet["!rows"] || [];
for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) if (!(colinfo[C3] || {}).hidden) cols[C3] = encode_col(C3);
var w3 = 0;
for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
if ((rowinfo[R3] || {}).hidden) continue;
row = make_csv_row(sheet, r8, R3, cols, fs, rs, FS, w3, o9);
if (row == null) {
continue;
}
if (row || o9.blankrows !== false) out.push((w3++ ? RS : "") + row);
}
return out.join("");
}
function sheet_to_txt(sheet, opts) {
if (!opts) opts = {};
opts.FS = " ";
opts.RS = "\n";
var s6 = sheet_to_csv(sheet, opts);
if (typeof $cptable == "undefined" || opts.type == "string") return s6;
var o9 = $cptable.utils.encode(1200, s6, "str");
return String.fromCharCode(255) + String.fromCharCode(254) + o9;
}
function sheet_to_formulae(sheet, opts) {
var y4 = "", x2, val2 = "";
if (sheet == null || sheet["!ref"] == null) return [];
var r8 = safe_decode_range(sheet["!ref"]), rr = "", cols = [], C3;
var cmds = [];
var dense = sheet["!data"] != null;
for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) cols[C3] = encode_col(C3);
for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
rr = encode_row(R3);
for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
y4 = cols[C3] + rr;
x2 = dense ? (sheet["!data"][R3] || [])[C3] : sheet[y4];
val2 = "";
if (x2 === void 0) continue;
else if (x2.F != null) {
y4 = x2.F;
if (!x2.f) continue;
val2 = x2.f;
if (y4.indexOf(":") == -1) y4 = y4 + ":" + y4;
}
if (x2.f != null) val2 = x2.f;
else if (opts && opts.values === false) continue;
else if (x2.t == "z") continue;
else if (x2.t == "n" && x2.v != null) val2 = "" + x2.v;
else if (x2.t == "b") val2 = x2.v ? "TRUE" : "FALSE";
else if (x2.w !== void 0) val2 = "'" + x2.w;
else if (x2.v === void 0) continue;
else if (x2.t == "s") val2 = "'" + x2.v;
else val2 = "" + x2.v;
cmds[cmds.length] = y4 + "=" + val2;
}
}
return cmds;
}
function sheet_add_json(_ws, js, opts) {
var o9 = opts || {};
var dense = _ws ? _ws["!data"] != null : o9.dense;
if (DENSE != null && dense == null) dense = DENSE;
var offset = +!o9.skipHeader;
var ws = _ws || {};
if (!_ws && dense) ws["!data"] = [];
var _R = 0, _C = 0;
if (ws && o9.origin != null) {
if (typeof o9.origin == "number") _R = o9.origin;
else {
var _origin2 = typeof o9.origin == "string" ? decode_cell(o9.origin) : o9.origin;
_R = _origin2.r;
_C = _origin2.c;
}
}
var range2 = { s: { c: 0, r: 0 }, e: { c: _C, r: _R + js.length - 1 + offset } };
if (ws["!ref"]) {
var _range = safe_decode_range(ws["!ref"]);
range2.e.c = Math.max(range2.e.c, _range.e.c);
range2.e.r = Math.max(range2.e.r, _range.e.r);
if (_R == -1) {
_R = _range.e.r + 1;
range2.e.r = _R + js.length - 1 + offset;
}
} else {
if (_R == -1) {
_R = 0;
range2.e.r = js.length - 1 + offset;
}
}
var hdr = o9.header || [], C3 = 0;
var ROW = [];
js.forEach(function(JS, R3) {
if (dense && !ws["!data"][_R + R3 + offset]) ws["!data"][_R + R3 + offset] = [];
if (dense) ROW = ws["!data"][_R + R3 + offset];
keys(JS).forEach(function(k2) {
if ((C3 = hdr.indexOf(k2)) == -1) hdr[C3 = hdr.length] = k2;
var v4 = JS[k2];
var t6 = "z";
var z3 = "";
var ref = dense ? "" : encode_col(_C + C3) + encode_row(_R + R3 + offset);
var cell = dense ? ROW[_C + C3] : ws[ref];
if (v4 && typeof v4 === "object" && !(v4 instanceof Date)) {
if (dense) ROW[_C + C3] = v4;
else ws[ref] = v4;
} else {
if (typeof v4 == "number") t6 = "n";
else if (typeof v4 == "boolean") t6 = "b";
else if (typeof v4 == "string") t6 = "s";
else if (v4 instanceof Date) {
t6 = "d";
if (!o9.UTC) v4 = local_to_utc(v4);
if (!o9.cellDates) {
t6 = "n";
v4 = datenum(v4);
}
z3 = cell != null && cell.z && fmt_is_date(cell.z) ? cell.z : o9.dateNF || table_fmt[14];
} else if (v4 === null && o9.nullError) {
t6 = "e";
v4 = 0;
}
if (!cell) {
if (!dense) ws[ref] = cell = { t: t6, v: v4 };
else ROW[_C + C3] = cell = { t: t6, v: v4 };
} else {
cell.t = t6;
cell.v = v4;
delete cell.w;
delete cell.R;
if (z3) cell.z = z3;
}
if (z3) cell.z = z3;
}
});
});
range2.e.c = Math.max(range2.e.c, _C + hdr.length - 1);
var __R = encode_row(_R);
if (dense && !ws["!data"][_R]) ws["!data"][_R] = [];
if (offset) for (C3 = 0; C3 < hdr.length; ++C3) {
if (dense) ws["!data"][_R][C3 + _C] = { t: "s", v: hdr[C3] };
else ws[encode_col(C3 + _C) + __R] = { t: "s", v: hdr[C3] };
}
ws["!ref"] = encode_range(range2);
return ws;
}
function json_to_sheet(js, opts) {
return sheet_add_json(null, js, opts);
}
function ws_get_cell_stub(ws, R3, C3) {
if (typeof R3 == "string") {
if (ws["!data"] != null) {
var RC = decode_cell(R3);
if (!ws["!data"][RC.r]) ws["!data"][RC.r] = [];
return ws["!data"][RC.r][RC.c] || (ws["!data"][RC.r][RC.c] = { t: "z" });
}
return ws[R3] || (ws[R3] = { t: "z" });
}
if (typeof R3 != "number") return ws_get_cell_stub(ws, encode_cell(R3));
return ws_get_cell_stub(ws, encode_col(C3 || 0) + encode_row(R3));
}
function wb_sheet_idx(wb, sh) {
if (typeof sh == "number") {
if (sh >= 0 && wb.SheetNames.length > sh) return sh;
throw new Error("Cannot find sheet # " + sh);
} else if (typeof sh == "string") {
var idx = wb.SheetNames.indexOf(sh);
if (idx > -1) return idx;
throw new Error("Cannot find sheet name |" + sh + "|");
} else throw new Error("Cannot find sheet |" + sh + "|");
}
function book_new(ws, wsname) {
var wb = { SheetNames: [], Sheets: {} };
if (ws) book_append_sheet(wb, ws, wsname || "Sheet1");
return wb;
}
function book_append_sheet(wb, ws, name, roll) {
var i7 = 1;
if (!name) {
for (; i7 <= 65535; ++i7, name = void 0) if (wb.SheetNames.indexOf(name = "Sheet" + i7) == -1) break;
}
if (!name || wb.SheetNames.length >= 65535) throw new Error("Too many worksheets");
if (roll && wb.SheetNames.indexOf(name) >= 0 && name.length < 32) {
var m4 = name.match(/\d+$/);
i7 = m4 && +m4[0] || 0;
var root = m4 && name.slice(0, m4.index) || name;
for (++i7; i7 <= 65535; ++i7) if (wb.SheetNames.indexOf(name = root + i7) == -1) break;
}
check_ws_name(name);
if (wb.SheetNames.indexOf(name) >= 0) throw new Error("Worksheet with name |" + name + "| already exists!");
wb.SheetNames.push(name);
wb.Sheets[name] = ws;
return name;
}
function book_set_sheet_visibility(wb, sh, vis) {
if (!wb.Workbook) wb.Workbook = {};
if (!wb.Workbook.Sheets) wb.Workbook.Sheets = [];
var idx = wb_sheet_idx(wb, sh);
if (!wb.Workbook.Sheets[idx]) wb.Workbook.Sheets[idx] = {};
switch (vis) {
case 0:
case 1:
case 2:
break;
default:
throw new Error("Bad sheet visibility setting " + vis);
}
wb.Workbook.Sheets[idx].Hidden = vis;
}
function cell_set_number_format(cell, fmt) {
cell.z = fmt;
return cell;
}
function cell_set_hyperlink(cell, target, tooltip) {
if (!target) {
delete cell.l;
} else {
cell.l = { Target: target };
if (tooltip) cell.l.Tooltip = tooltip;
}
return cell;
}
function cell_set_internal_link(cell, range2, tooltip) {
return cell_set_hyperlink(cell, "#" + range2, tooltip);
}
function cell_add_comment(cell, text3, author) {
if (!cell.c) cell.c = [];
cell.c.push({ t: text3, a: author || "SheetJS" });
}
function sheet_set_array_formula(ws, range2, formula, dynamic) {
var rng = typeof range2 != "string" ? range2 : safe_decode_range(range2);
var rngstr = typeof range2 == "string" ? range2 : encode_range(range2);
for (var R3 = rng.s.r; R3 <= rng.e.r; ++R3) for (var C3 = rng.s.c; C3 <= rng.e.c; ++C3) {
var cell = ws_get_cell_stub(ws, R3, C3);
cell.t = "n";
cell.F = rngstr;
delete cell.v;
if (R3 == rng.s.r && C3 == rng.s.c) {
cell.f = formula;
if (dynamic) cell.D = true;
}
}
var wsr = decode_range(ws["!ref"]);
if (wsr.s.r > rng.s.r) wsr.s.r = rng.s.r;
if (wsr.s.c > rng.s.c) wsr.s.c = rng.s.c;
if (wsr.e.r < rng.e.r) wsr.e.r = rng.e.r;
if (wsr.e.c < rng.e.c) wsr.e.c = rng.e.c;
ws["!ref"] = encode_range(wsr);
return ws;
}
var XLSX, current_codepage, current_ansi, $cptable, VALID_ANSI, CS2CP, set_ansi, set_cp, debom, _getchar, _getansi, DENSE, DIF_XL, Base64_map, has_buf, Buffer_from, buf_utf16le, s2a, bconcat, chr0, chr1, p2_32, days, months, table_fmt, SSF_default_map, SSF_default_str, pct1, frac1, dec1, closeparen, phone, SSF_abstime, cfregex2, SSFImplicit, dateNFregex, bad_formats, CRC32, CFB, _fs, dnthresh, dnthresh1, dnthresh2, pdre1, pdre2, pdre3, FDRE1, FDRE2, FDISO, utc_append_works, lower_months, split_regex, xml_boundary, str_match_xml_ns, str_match_xml_ns_g, str_remove_xml_ns_g, str_match_xml_ig, XML_HEADER, attregexg, tagregex1, tagregex2, tagregex, nsregex, nsregex2, encodings, rencoding, unescapexml, decregex, htmlcharegex, xlml_fixstr, utf8corpus, utf8read, utf8write, htmldecode, vtvregex, vtmregex, wtregex, xlmlregex, XMLNS, XMLNS_main, ___toBuffer, __toBuffer, ___utf16le, __utf16le, ___hexlify, __hexlify, ___utf8, __utf8, ___lpstr, __lpstr, ___cpstr, __cpstr, ___lpwstr, __lpwstr, ___lpp4, __lpp4, ___8lpp4, __8lpp4, ___double, __double, is_buf, __readUInt8, __readUInt16LE, __readInt16LE, __readUInt32LE, __readInt32LE, __readInt32BE, __writeUInt32LE, __writeInt32LE, __writeUInt16LE, parse_BrtCommentText, parse_XLSBCodeName, parse_XLNameWideString, parse_RelID, parse_UncheckedRfX, VT_I2, VT_I4, VT_BOOL, VT_VARIANT, VT_UI4, VT_FILETIME, VT_BLOB, VT_CF, VT_VECTOR_VARIANT, VT_VECTOR_LPSTR, VT_STRING, VT_USTR, VT_CUSTOM, DocSummaryPIDDSI, SummaryPIDSI, CountryEnum, XLSFillPattern, _XLSIcv, XLSIcv, BErr, RBErr, XLSLblBuiltIn, ct2type, RELS, CT_ODS, CORE_PROPS, EXT_PROPS, custregex, XLMLDocPropsMap, evert_XLMLDPM, parse_Ref, FtTab, parse_BIFF2Format, parse_XLHeaderFooter, parse_BIFF5OT, parse_Blank, parse_Scl, parse_String, DBF_SUPPORTED_VERSIONS, DBF, SYLK, DIF, ETH, PRN, WK_, parse_rs, rs_to_html, sitregex, sirregex, sstr1, sstr2, crypto_CreateXorArray_Method1, crypto_DecryptData_Method1, crypto_MakeXorDecryptor, DEF_MDW, MAX_MDW, MIN_MDW, MDW, DEF_PPI, PPI, XLMLPatternTypeMap, cellXF_uint, cellXF_bool, parse_sty_xml, parse_BrtFill, parse_BrtBorder, XLSXThemeClrScheme, parse_BrtCommentAuthor, CT_VBA, rc_to_a1, crefregex, a1_to_rc, parse_PtgMemErr, parse_PtgMemNoMem, parse_PtgTbl, parse_PtgElfCol, parse_PtgElfColS, parse_PtgElfColSV, parse_PtgElfColV, parse_PtgElfRadical, parse_PtgElfRadicalLel, parse_PtgElfRadicalS, parse_PtgElfRw, parse_PtgElfRwV, PtgListRT, PtgTypes, PtgDupes, Ptg18, Ptg19, PtgBinOp, parse_XLSBArrayParsedFormula, parse_XLSBCellParsedFormula, parse_XLSBNameParsedFormula, parse_XLSBSharedParsedFormula, Cetab, Ftab, FtabArgc, strs, _ssfopts, mergecregex, hlinkregex, dimregex, colregex, afregex, marginregex, sheetprregex, sviewregex, parse_ws_xml_data, parse_BrtWsDim, parse_BrtMergeCell, BrtMarginKeys, WBPropsDef, WBViewDef, SheetDef, CalcPrDef, badchars, wbnsregex, attregexg2, attregex2, XLMLFormatMap, CONTINUE_RT, PSCLSID, XLSBRecordEnum, XLSRecordEnum, HTML_BEGIN, HTML_END, subarray, numbers_lut_new, qreg, utils, version3;
var init_xlsx = __esm({
"../pi-mono/node_modules/xlsx/xlsx.mjs"() {
init_process_shim();
XLSX = {};
XLSX.version = "0.20.3";
current_codepage = 1200;
current_ansi = 1252;
VALID_ANSI = [874, 932, 936, 949, 950, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1e4];
CS2CP = {
0: 1252,
/* ANSI */
1: 65001,
/* DEFAULT */
2: 65001,
/* SYMBOL */
77: 1e4,
/* MAC */
128: 932,
/* SHIFTJIS */
129: 949,
/* HANGUL */
130: 1361,
/* JOHAB */
134: 936,
/* GB2312 */
136: 950,
/* CHINESEBIG5 */
161: 1253,
/* GREEK */
162: 1254,
/* TURKISH */
163: 1258,
/* VIETNAMESE */
177: 1255,
/* HEBREW */
178: 1256,
/* ARABIC */
186: 1257,
/* BALTIC */
204: 1251,
/* RUSSIAN */
222: 874,
/* THAI */
238: 1250,
/* EASTEUROPE */
255: 1252,
/* OEM */
69: 6969
/* MISC */
};
set_ansi = function(cp) {
if (VALID_ANSI.indexOf(cp) == -1) return;
current_ansi = CS2CP[0] = cp;
};
set_cp = function(cp) {
current_codepage = cp;
set_ansi(cp);
};
debom = function(data) {
var c1 = data.charCodeAt(0), c22 = data.charCodeAt(1);
if (c1 == 255 && c22 == 254) return utf16leread(data.slice(2));
if (c1 == 254 && c22 == 255) return utf16beread(data.slice(2));
if (c1 == 65279) return data.slice(1);
return data;
};
_getchar = function _gc1(x2) {
return String.fromCharCode(x2);
};
_getansi = function _ga1(x2) {
return String.fromCharCode(x2);
};
DENSE = null;
DIF_XL = true;
Base64_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
has_buf = /* @__PURE__ */ (function() {
return typeof Buffer !== "undefined" && typeof process !== "undefined" && typeof process.versions !== "undefined" && !!process.versions.node;
})();
Buffer_from = /* @__PURE__ */ (function() {
if (typeof Buffer !== "undefined") {
var nbfs = !Buffer.from;
if (!nbfs) try {
Buffer.from("foo", "utf8");
} catch (e9) {
nbfs = true;
}
return nbfs ? function(buf, enc) {
return enc ? new Buffer(buf, enc) : new Buffer(buf);
} : Buffer.from.bind(Buffer);
}
return function() {
};
})();
buf_utf16le = /* @__PURE__ */ (function() {
if (typeof Buffer === "undefined") return false;
var x2 = Buffer_from([65, 0]);
if (!x2) return false;
var o9 = x2.toString("utf16le");
return o9.length == 1;
})();
s2a = function s2a2(s6) {
if (has_buf) return Buffer_from(s6, "binary");
return s6.split("").map(function(x2) {
return x2.charCodeAt(0) & 255;
});
};
bconcat = has_buf ? function(bufs) {
return Buffer.concat(bufs.map(function(buf) {
return Buffer.isBuffer(buf) ? buf : Buffer_from(buf);
}));
} : function(bufs) {
if (typeof Uint8Array !== "undefined") {
var i7 = 0, maxlen = 0;
for (i7 = 0; i7 < bufs.length; ++i7) maxlen += bufs[i7].length;
var o9 = new Uint8Array(maxlen);
var len = 0;
for (i7 = 0, maxlen = 0; i7 < bufs.length; maxlen += len, ++i7) {
len = bufs[i7].length;
if (bufs[i7] instanceof Uint8Array) o9.set(bufs[i7], maxlen);
else if (typeof bufs[i7] == "string") o9.set(new Uint8Array(s2a(bufs[i7])), maxlen);
else o9.set(new Uint8Array(bufs[i7]), maxlen);
}
return o9;
}
return [].concat.apply([], bufs.map(function(buf) {
return Array.isArray(buf) ? buf : [].slice.call(buf);
}));
};
chr0 = /\u0000/g;
chr1 = /[\u0001-\u0006]/g;
p2_32 = /* @__PURE__ */ Math.pow(2, 32);
days = [
["Sun", "Sunday"],
["Mon", "Monday"],
["Tue", "Tuesday"],
["Wed", "Wednesday"],
["Thu", "Thursday"],
["Fri", "Friday"],
["Sat", "Saturday"]
];
months = [
["J", "Jan", "January"],
["F", "Feb", "February"],
["M", "Mar", "March"],
["A", "Apr", "April"],
["M", "May", "May"],
["J", "Jun", "June"],
["J", "Jul", "July"],
["A", "Aug", "August"],
["S", "Sep", "September"],
["O", "Oct", "October"],
["N", "Nov", "November"],
["D", "Dec", "December"]
];
table_fmt = {
0: "General",
1: "0",
2: "0.00",
3: "#,##0",
4: "#,##0.00",
9: "0%",
10: "0.00%",
11: "0.00E+00",
12: "# ?/?",
13: "# ??/??",
14: "m/d/yy",
15: "d-mmm-yy",
16: "d-mmm",
17: "mmm-yy",
18: "h:mm AM/PM",
19: "h:mm:ss AM/PM",
20: "h:mm",
21: "h:mm:ss",
22: "m/d/yy h:mm",
37: "#,##0 ;(#,##0)",
38: "#,##0 ;[Red](#,##0)",
39: "#,##0.00;(#,##0.00)",
40: "#,##0.00;[Red](#,##0.00)",
45: "mm:ss",
46: "[h]:mm:ss",
47: "mmss.0",
48: "##0.0E+0",
49: "@",
56: '"\u4E0A\u5348/\u4E0B\u5348 "hh"\u6642"mm"\u5206"ss"\u79D2 "'
};
SSF_default_map = {
5: 37,
6: 38,
7: 39,
8: 40,
// 5 -> 37 ... 8 -> 40
23: 0,
24: 0,
25: 0,
26: 0,
// 23 -> 0 ... 26 -> 0
27: 14,
28: 14,
29: 14,
30: 14,
31: 14,
// 27 -> 14 ... 31 -> 14
50: 14,
51: 14,
52: 14,
53: 14,
54: 14,
// 50 -> 14 ... 58 -> 14
55: 14,
56: 14,
57: 14,
58: 14,
59: 1,
60: 2,
61: 3,
62: 4,
// 59 -> 1 ... 62 -> 4
67: 9,
68: 10,
// 67 -> 9 ... 68 -> 10
69: 12,
70: 13,
71: 14,
// 69 -> 12 ... 71 -> 14
72: 14,
73: 15,
74: 16,
75: 17,
// 72 -> 14 ... 75 -> 17
76: 20,
77: 21,
78: 22,
// 76 -> 20 ... 78 -> 22
79: 45,
80: 46,
81: 47,
// 79 -> 45 ... 81 -> 47
82: 0
// 82 -> 0 ... 65536 -> 0 (omitted)
};
SSF_default_str = {
// 5 -- Currency, 0 decimal, black negative
5: '"$"#,##0_);\\("$"#,##0\\)',
63: '"$"#,##0_);\\("$"#,##0\\)',
// 6 -- Currency, 0 decimal, red negative
6: '"$"#,##0_);[Red]\\("$"#,##0\\)',
64: '"$"#,##0_);[Red]\\("$"#,##0\\)',
// 7 -- Currency, 2 decimal, black negative
7: '"$"#,##0.00_);\\("$"#,##0.00\\)',
65: '"$"#,##0.00_);\\("$"#,##0.00\\)',
// 8 -- Currency, 2 decimal, red negative
8: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
66: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
// 41 -- Accounting, 0 decimal, No Symbol
41: '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',
// 42 -- Accounting, 0 decimal, $ Symbol
42: '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)',
// 43 -- Accounting, 2 decimal, No Symbol
43: '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',
// 44 -- Accounting, 2 decimal, $ Symbol
44: '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)'
};
pct1 = /%/g;
frac1 = /# (\?+)( ?)\/( ?)(\d+)/;
dec1 = /^#*0*\.([0#]+)/;
closeparen = /\)[^)]*[0#]/;
phone = /\(###\) ###\\?-####/;
SSF_abstime = /\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;
cfregex2 = /\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;
SSFImplicit = {
"5": '"$"#,##0_);\\("$"#,##0\\)',
"6": '"$"#,##0_);[Red]\\("$"#,##0\\)',
"7": '"$"#,##0.00_);\\("$"#,##0.00\\)',
"8": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
"23": "General",
"24": "General",
"25": "General",
"26": "General",
"27": "m/d/yy",
"28": "m/d/yy",
"29": "m/d/yy",
"30": "m/d/yy",
"31": "m/d/yy",
"32": "h:mm:ss",
"33": "h:mm:ss",
"34": "h:mm:ss",
"35": "h:mm:ss",
"36": "m/d/yy",
"41": '_(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)',
"42": '_("$"* #,##0_);_("$"* (#,##0);_("$"* "-"_);_(@_)',
"43": '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)',
"44": '_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)',
"50": "m/d/yy",
"51": "m/d/yy",
"52": "m/d/yy",
"53": "m/d/yy",
"54": "m/d/yy",
"55": "m/d/yy",
"56": "m/d/yy",
"57": "m/d/yy",
"58": "m/d/yy",
"59": "0",
"60": "0.00",
"61": "#,##0",
"62": "#,##0.00",
"63": '"$"#,##0_);\\("$"#,##0\\)',
"64": '"$"#,##0_);[Red]\\("$"#,##0\\)',
"65": '"$"#,##0.00_);\\("$"#,##0.00\\)',
"66": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
"67": "0%",
"68": "0.00%",
"69": "# ?/?",
"70": "# ??/??",
"71": "m/d/yy",
"72": "m/d/yy",
"73": "d-mmm-yy",
"74": "d-mmm",
"75": "mmm-yy",
"76": "h:mm",
"77": "h:mm:ss",
"78": "m/d/yy h:mm",
"79": "mm:ss",
"80": "[h]:mm:ss",
"81": "mmss.0"
};
dateNFregex = /[dD]+|[mM]+|[yYeE]+|[Hh]+|[Ss]+/g;
bad_formats = {
"d.m": "d\\.m"
// Issue #2571 Google Sheets writes invalid format 'd.m', correct format is 'd"."m' or 'd\\.m'
};
CRC32 = /* @__PURE__ */ (function() {
var CRC322 = {};
CRC322.version = "1.2.0";
function signed_crc_table() {
var c6 = 0, table = new Array(256);
for (var n7 = 0; n7 != 256; ++n7) {
c6 = n7;
c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1;
table[n7] = c6;
}
return typeof Int32Array !== "undefined" ? new Int32Array(table) : table;
}
var T0 = signed_crc_table();
function slice_by_16_tables(T10) {
var c6 = 0, v4 = 0, n7 = 0, table = typeof Int32Array !== "undefined" ? new Int32Array(4096) : new Array(4096);
for (n7 = 0; n7 != 256; ++n7) table[n7] = T10[n7];
for (n7 = 0; n7 != 256; ++n7) {
v4 = T10[n7];
for (c6 = 256 + n7; c6 < 4096; c6 += 256) v4 = table[c6] = v4 >>> 8 ^ T10[v4 & 255];
}
var out = [];
for (n7 = 1; n7 != 16; ++n7) out[n7 - 1] = typeof Int32Array !== "undefined" && typeof table.subarray == "function" ? table.subarray(n7 * 256, n7 * 256 + 256) : table.slice(n7 * 256, n7 * 256 + 256);
return out;
}
var TT = slice_by_16_tables(T0);
var T1 = TT[0], T22 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4];
var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9];
var Tb = TT[10], Tc2 = TT[11], Td = TT[12], Te2 = TT[13], Tf = TT[14];
function crc32_bstr(bstr, seed) {
var C3 = seed ^ -1;
for (var i7 = 0, L3 = bstr.length; i7 < L3; ) C3 = C3 >>> 8 ^ T0[(C3 ^ bstr.charCodeAt(i7++)) & 255];
return ~C3;
}
function crc32_buf(B3, seed) {
var C3 = seed ^ -1, L3 = B3.length - 15, i7 = 0;
for (; i7 < L3; ) C3 = Tf[B3[i7++] ^ C3 & 255] ^ Te2[B3[i7++] ^ C3 >> 8 & 255] ^ Td[B3[i7++] ^ C3 >> 16 & 255] ^ Tc2[B3[i7++] ^ C3 >>> 24] ^ Tb[B3[i7++]] ^ Ta[B3[i7++]] ^ T9[B3[i7++]] ^ T8[B3[i7++]] ^ T7[B3[i7++]] ^ T6[B3[i7++]] ^ T5[B3[i7++]] ^ T4[B3[i7++]] ^ T3[B3[i7++]] ^ T22[B3[i7++]] ^ T1[B3[i7++]] ^ T0[B3[i7++]];
L3 += 15;
while (i7 < L3) C3 = C3 >>> 8 ^ T0[(C3 ^ B3[i7++]) & 255];
return ~C3;
}
function crc32_str(str2, seed) {
var C3 = seed ^ -1;
for (var i7 = 0, L3 = str2.length, c6 = 0, d4 = 0; i7 < L3; ) {
c6 = str2.charCodeAt(i7++);
if (c6 < 128) {
C3 = C3 >>> 8 ^ T0[(C3 ^ c6) & 255];
} else if (c6 < 2048) {
C3 = C3 >>> 8 ^ T0[(C3 ^ (192 | c6 >> 6 & 31)) & 255];
C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 & 63)) & 255];
} else if (c6 >= 55296 && c6 < 57344) {
c6 = (c6 & 1023) + 64;
d4 = str2.charCodeAt(i7++) & 1023;
C3 = C3 >>> 8 ^ T0[(C3 ^ (240 | c6 >> 8 & 7)) & 255];
C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 >> 2 & 63)) & 255];
C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | d4 >> 6 & 15 | (c6 & 3) << 4)) & 255];
C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | d4 & 63)) & 255];
} else {
C3 = C3 >>> 8 ^ T0[(C3 ^ (224 | c6 >> 12 & 15)) & 255];
C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 >> 6 & 63)) & 255];
C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 & 63)) & 255];
}
}
return ~C3;
}
CRC322.table = T0;
CRC322.bstr = crc32_bstr;
CRC322.buf = crc32_buf;
CRC322.str = crc32_str;
return CRC322;
})();
CFB = /* @__PURE__ */ (function _CFB() {
var exports = (
/*::(*/
{}
);
exports.version = "1.2.2";
function namecmp(l5, r8) {
var L3 = l5.split("/"), R3 = r8.split("/");
for (var i8 = 0, c6 = 0, Z2 = Math.min(L3.length, R3.length); i8 < Z2; ++i8) {
if (c6 = L3[i8].length - R3[i8].length) return c6;
if (L3[i8] != R3[i8]) return L3[i8] < R3[i8] ? -1 : 1;
}
return L3.length - R3.length;
}
function dirname(p4) {
if (p4.charAt(p4.length - 1) == "/") return p4.slice(0, -1).indexOf("/") === -1 ? p4 : dirname(p4.slice(0, -1));
var c6 = p4.lastIndexOf("/");
return c6 === -1 ? p4 : p4.slice(0, c6 + 1);
}
function filename(p4) {
if (p4.charAt(p4.length - 1) == "/") return filename(p4.slice(0, -1));
var c6 = p4.lastIndexOf("/");
return c6 === -1 ? p4 : p4.slice(c6 + 1);
}
function write_dos_date(buf, date) {
if (typeof date === "string") date = new Date(date);
var hms = date.getHours();
hms = hms << 6 | date.getMinutes();
hms = hms << 5 | date.getSeconds() >>> 1;
buf.write_shift(2, hms);
var ymd = date.getFullYear() - 1980;
ymd = ymd << 4 | date.getMonth() + 1;
ymd = ymd << 5 | date.getDate();
buf.write_shift(2, ymd);
}
function parse_dos_date(buf) {
var hms = buf.read_shift(2) & 65535;
var ymd = buf.read_shift(2) & 65535;
var val2 = /* @__PURE__ */ new Date();
var d4 = ymd & 31;
ymd >>>= 5;
var m4 = ymd & 15;
ymd >>>= 4;
val2.setMilliseconds(0);
val2.setFullYear(ymd + 1980);
val2.setMonth(m4 - 1);
val2.setDate(d4);
var S5 = hms & 31;
hms >>>= 5;
var M4 = hms & 63;
hms >>>= 6;
val2.setHours(hms);
val2.setMinutes(M4);
val2.setSeconds(S5 << 1);
return val2;
}
function parse_extra_field(blob) {
prep_blob(blob, 0);
var o9 = (
/*::(*/
{}
);
var flags = 0;
while (blob.l <= blob.length - 4) {
var type = blob.read_shift(2);
var sz = blob.read_shift(2), tgt = blob.l + sz;
var p4 = {};
switch (type) {
/* UNIX-style Timestamps */
case 21589:
{
flags = blob.read_shift(1);
if (flags & 1) p4.mtime = blob.read_shift(4);
if (sz > 5) {
if (flags & 2) p4.atime = blob.read_shift(4);
if (flags & 4) p4.ctime = blob.read_shift(4);
}
if (p4.mtime) p4.mt = new Date(p4.mtime * 1e3);
}
break;
/* ZIP64 Extended Information Field */
case 1:
{
var sz1 = blob.read_shift(4), sz2 = blob.read_shift(4);
p4.usz = sz2 * Math.pow(2, 32) + sz1;
sz1 = blob.read_shift(4);
sz2 = blob.read_shift(4);
p4.csz = sz2 * Math.pow(2, 32) + sz1;
}
break;
}
blob.l = tgt;
o9[type] = p4;
}
return o9;
}
var fs;
function get_fs() {
return fs || (fs = _fs);
}
function parse3(file, options) {
if (file[0] == 80 && file[1] == 75) return parse_zip2(file, options);
if ((file[0] | 32) == 109 && (file[1] | 32) == 105) return parse_mad(file, options);
if (file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
var mver = 3;
var ssz = 512;
var nmfs = 0;
var difat_sec_cnt = 0;
var dir_start = 0;
var minifat_start = 0;
var difat_start = 0;
var fat_addrs = [];
var blob = (
/*::(*/
file.slice(0, 512)
);
prep_blob(blob, 0);
var mv = check_get_mver(blob);
mver = mv[0];
switch (mver) {
case 3:
ssz = 512;
break;
case 4:
ssz = 4096;
break;
case 0:
if (mv[1] == 0) return parse_zip2(file, options);
/* falls through */
default:
throw new Error("Major Version: Expected 3 or 4 saw " + mver);
}
if (ssz !== 512) {
blob = /*::(*/
file.slice(0, ssz);
prep_blob(
blob,
28
/* blob.l */
);
}
var header = file.slice(0, ssz);
check_shifts(blob, mver);
var dir_cnt = blob.read_shift(4, "i");
if (mver === 3 && dir_cnt !== 0) throw new Error("# Directory Sectors: Expected 0 saw " + dir_cnt);
blob.l += 4;
dir_start = blob.read_shift(4, "i");
blob.l += 4;
blob.chk("00100000", "Mini Stream Cutoff Size: ");
minifat_start = blob.read_shift(4, "i");
nmfs = blob.read_shift(4, "i");
difat_start = blob.read_shift(4, "i");
difat_sec_cnt = blob.read_shift(4, "i");
for (var q3 = -1, j3 = 0; j3 < 109; ++j3) {
q3 = blob.read_shift(4, "i");
if (q3 < 0) break;
fat_addrs[j3] = q3;
}
var sectors = sectorify(file, ssz);
sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);
var sector_list = make_sector_list(sectors, dir_start, fat_addrs, ssz);
if (dir_start < sector_list.length) sector_list[dir_start].name = "!Directory";
if (nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
sector_list[fat_addrs[0]].name = "!FAT";
sector_list.fat_addrs = fat_addrs;
sector_list.ssz = ssz;
var files = {}, Paths = [], FileIndex = [], FullPaths = [];
read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);
build_full_paths(FileIndex, FullPaths, Paths);
Paths.shift();
var o9 = {
FileIndex,
FullPaths
};
if (options && options.raw) o9.raw = { header, sectors };
return o9;
}
function check_get_mver(blob) {
if (blob[blob.l] == 80 && blob[blob.l + 1] == 75) return [0, 0];
blob.chk(HEADER_SIGNATURE, "Header Signature: ");
blob.l += 16;
var mver = blob.read_shift(2, "u");
return [blob.read_shift(2, "u"), mver];
}
function check_shifts(blob, mver) {
var shift = 9;
blob.l += 2;
switch (shift = blob.read_shift(2)) {
case 9:
if (mver != 3) throw new Error("Sector Shift: Expected 9 saw " + shift);
break;
case 12:
if (mver != 4) throw new Error("Sector Shift: Expected 12 saw " + shift);
break;
default:
throw new Error("Sector Shift: Expected 9 or 12 saw " + shift);
}
blob.chk("0600", "Mini Sector Shift: ");
blob.chk("000000000000", "Reserved: ");
}
function sectorify(file, ssz) {
var nsectors = Math.ceil(file.length / ssz) - 1;
var sectors = [];
for (var i8 = 1; i8 < nsectors; ++i8) sectors[i8 - 1] = file.slice(i8 * ssz, (i8 + 1) * ssz);
sectors[nsectors - 1] = file.slice(nsectors * ssz);
return sectors;
}
function build_full_paths(FI, FP, Paths) {
var i8 = 0, L3 = 0, R3 = 0, C3 = 0, j3 = 0, pl = Paths.length;
var dad = [], q3 = [];
for (; i8 < pl; ++i8) {
dad[i8] = q3[i8] = i8;
FP[i8] = Paths[i8];
}
for (; j3 < q3.length; ++j3) {
i8 = q3[j3];
L3 = FI[i8].L;
R3 = FI[i8].R;
C3 = FI[i8].C;
if (dad[i8] === i8) {
if (L3 !== -1 && dad[L3] !== L3) dad[i8] = dad[L3];
if (R3 !== -1 && dad[R3] !== R3) dad[i8] = dad[R3];
}
if (C3 !== -1) dad[C3] = i8;
if (L3 !== -1 && i8 != dad[i8]) {
dad[L3] = dad[i8];
if (q3.lastIndexOf(L3) < j3) q3.push(L3);
}
if (R3 !== -1 && i8 != dad[i8]) {
dad[R3] = dad[i8];
if (q3.lastIndexOf(R3) < j3) q3.push(R3);
}
}
for (i8 = 1; i8 < pl; ++i8) if (dad[i8] === i8) {
if (R3 !== -1 && dad[R3] !== R3) dad[i8] = dad[R3];
else if (L3 !== -1 && dad[L3] !== L3) dad[i8] = dad[L3];
}
for (i8 = 1; i8 < pl; ++i8) {
if (FI[i8].type === 0) continue;
j3 = i8;
if (j3 != dad[j3]) do {
j3 = dad[j3];
FP[i8] = FP[j3] + "/" + FP[i8];
} while (j3 !== 0 && -1 !== dad[j3] && j3 != dad[j3]);
dad[i8] = -1;
}
FP[0] += "/";
for (i8 = 1; i8 < pl; ++i8) {
if (FI[i8].type !== 2) FP[i8] += "/";
}
}
function get_mfat_entry(entry, payload, mini) {
var start = entry.start, size = entry.size;
var o9 = [];
var idx = start;
while (mini && size > 0 && idx >= 0) {
o9.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
size -= MSSZ;
idx = __readInt32LE(mini, idx * 4);
}
if (o9.length === 0) return new_buf(0);
return bconcat(o9).slice(0, entry.size);
}
function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) {
var q3 = ENDOFCHAIN;
if (idx === ENDOFCHAIN) {
if (cnt !== 0) throw new Error("DIFAT chain shorter than expected");
} else if (idx !== -1) {
var sector = sectors[idx], m4 = (ssz >>> 2) - 1;
if (!sector) return;
for (var i8 = 0; i8 < m4; ++i8) {
if ((q3 = __readInt32LE(sector, i8 * 4)) === ENDOFCHAIN) break;
fat_addrs.push(q3);
}
if (cnt >= 1) sleuth_fat(__readInt32LE(sector, ssz - 4), cnt - 1, sectors, ssz, fat_addrs);
}
}
function get_sector_list(sectors, start, fat_addrs, ssz, chkd) {
var buf = [], buf_chain = [];
if (!chkd) chkd = [];
var modulus = ssz - 1, j3 = 0, jj = 0;
for (j3 = start; j3 >= 0; ) {
chkd[j3] = true;
buf[buf.length] = j3;
buf_chain.push(sectors[j3]);
var addr = fat_addrs[Math.floor(j3 * 4 / ssz)];
jj = j3 * 4 & modulus;
if (ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j3 + " 4 " + ssz);
if (!sectors[addr]) break;
j3 = __readInt32LE(sectors[addr], jj);
}
return { nodes: buf, data: __toBuffer([buf_chain]) };
}
function make_sector_list(sectors, dir_start, fat_addrs, ssz) {
var sl = sectors.length, sector_list = [];
var chkd = [], buf = [], buf_chain = [];
var modulus = ssz - 1, i8 = 0, j3 = 0, k2 = 0, jj = 0;
for (i8 = 0; i8 < sl; ++i8) {
buf = [];
k2 = i8 + dir_start;
if (k2 >= sl) k2 -= sl;
if (chkd[k2]) continue;
buf_chain = [];
var seen = [];
for (j3 = k2; j3 >= 0; ) {
seen[j3] = true;
chkd[j3] = true;
buf[buf.length] = j3;
buf_chain.push(sectors[j3]);
var addr = fat_addrs[Math.floor(j3 * 4 / ssz)];
jj = j3 * 4 & modulus;
if (ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j3 + " 4 " + ssz);
if (!sectors[addr]) break;
j3 = __readInt32LE(sectors[addr], jj);
if (seen[j3]) break;
}
sector_list[k2] = { nodes: buf, data: __toBuffer([buf_chain]) };
}
return sector_list;
}
function read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, mini) {
var minifat_store = 0, pl = Paths.length ? 2 : 0;
var sector = sector_list[dir_start].data;
var i8 = 0, namelen = 0, name;
for (; i8 < sector.length; i8 += 128) {
var blob = (
/*::(*/
sector.slice(i8, i8 + 128)
);
prep_blob(blob, 64);
namelen = blob.read_shift(2);
name = __utf16le(blob, 0, namelen - pl);
Paths.push(name);
var o9 = {
name,
type: blob.read_shift(1),
color: blob.read_shift(1),
L: blob.read_shift(4, "i"),
R: blob.read_shift(4, "i"),
C: blob.read_shift(4, "i"),
clsid: blob.read_shift(16),
state: blob.read_shift(4, "i"),
start: 0,
size: 0
};
var ctime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
if (ctime !== 0) o9.ct = read_date(blob, blob.l - 8);
var mtime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
if (mtime !== 0) o9.mt = read_date(blob, blob.l - 8);
o9.start = blob.read_shift(4, "i");
o9.size = blob.read_shift(4, "i");
if (o9.size < 0 && o9.start < 0) {
o9.size = o9.type = 0;
o9.start = ENDOFCHAIN;
o9.name = "";
}
if (o9.type === 5) {
minifat_store = o9.start;
if (nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
} else if (o9.size >= 4096) {
o9.storage = "fat";
if (sector_list[o9.start] === void 0) sector_list[o9.start] = get_sector_list(sectors, o9.start, sector_list.fat_addrs, sector_list.ssz);
sector_list[o9.start].name = o9.name;
o9.content = sector_list[o9.start].data.slice(0, o9.size);
} else {
o9.storage = "minifat";
if (o9.size < 0) o9.size = 0;
else if (minifat_store !== ENDOFCHAIN && o9.start !== ENDOFCHAIN && sector_list[minifat_store]) {
o9.content = get_mfat_entry(o9, sector_list[minifat_store].data, (sector_list[mini] || {}).data);
}
}
if (o9.content) prep_blob(o9.content, 0);
files[name] = o9;
FileIndex.push(o9);
}
}
function read_date(blob, offset) {
return new Date((__readUInt32LE(blob, offset + 4) / 1e7 * Math.pow(2, 32) + __readUInt32LE(blob, offset) / 1e7 - 11644473600) * 1e3);
}
function read_file(filename2, options) {
get_fs();
return parse3(fs.readFileSync(filename2), options);
}
function read(blob, options) {
var type = options && options.type;
if (!type) {
if (has_buf && Buffer.isBuffer(blob)) type = "buffer";
}
switch (type || "base64") {
case "file":
return read_file(blob, options);
case "base64":
return parse3(s2a(Base64_decode(blob)), options);
case "binary":
return parse3(s2a(blob), options);
}
return parse3(
/*::typeof blob == 'string' ? new Buffer(blob, 'utf-8') : */
blob,
options
);
}
function init_cfb(cfb, opts) {
var o9 = opts || {}, root = o9.root || "Root Entry";
if (!cfb.FullPaths) cfb.FullPaths = [];
if (!cfb.FileIndex) cfb.FileIndex = [];
if (cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
if (cfb.FullPaths.length === 0) {
cfb.FullPaths[0] = root + "/";
cfb.FileIndex[0] = { name: root, type: 5 };
}
if (o9.CLSID) cfb.FileIndex[0].clsid = o9.CLSID;
seed_cfb(cfb);
}
function seed_cfb(cfb) {
var nm = "Sh33tJ5";
if (CFB.find(cfb, "/" + nm)) return;
var p4 = new_buf(4);
p4[0] = 55;
p4[1] = p4[3] = 50;
p4[2] = 54;
cfb.FileIndex.push({ name: nm, type: 2, content: p4, size: 4, L: 69, R: 69, C: 69 });
cfb.FullPaths.push(cfb.FullPaths[0] + nm);
rebuild_cfb(cfb);
}
function rebuild_cfb(cfb, f4) {
init_cfb(cfb);
var gc = false, s6 = false;
for (var i8 = cfb.FullPaths.length - 1; i8 >= 0; --i8) {
var _file = cfb.FileIndex[i8];
switch (_file.type) {
case 0:
if (s6) gc = true;
else {
cfb.FileIndex.pop();
cfb.FullPaths.pop();
}
break;
case 1:
case 2:
case 5:
s6 = true;
if (isNaN(_file.R * _file.L * _file.C)) gc = true;
if (_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
break;
default:
gc = true;
break;
}
}
if (!gc && !f4) return;
var now = new Date(1987, 1, 19), j3 = 0;
var fullPaths = Object.create ? /* @__PURE__ */ Object.create(null) : {};
var data = [];
for (i8 = 0; i8 < cfb.FullPaths.length; ++i8) {
fullPaths[cfb.FullPaths[i8]] = true;
if (cfb.FileIndex[i8].type === 0) continue;
data.push([cfb.FullPaths[i8], cfb.FileIndex[i8]]);
}
for (i8 = 0; i8 < data.length; ++i8) {
var dad = dirname(data[i8][0]);
s6 = fullPaths[dad];
while (!s6) {
while (dirname(dad) && !fullPaths[dirname(dad)]) dad = dirname(dad);
data.push([dad, {
name: filename(dad).replace("/", ""),
type: 1,
clsid: HEADER_CLSID,
ct: now,
mt: now,
content: null
}]);
fullPaths[dad] = true;
dad = dirname(data[i8][0]);
s6 = fullPaths[dad];
}
}
data.sort(function(x2, y4) {
return namecmp(x2[0], y4[0]);
});
cfb.FullPaths = [];
cfb.FileIndex = [];
for (i8 = 0; i8 < data.length; ++i8) {
cfb.FullPaths[i8] = data[i8][0];
cfb.FileIndex[i8] = data[i8][1];
}
for (i8 = 0; i8 < data.length; ++i8) {
var elt = cfb.FileIndex[i8];
var nm = cfb.FullPaths[i8];
elt.name = filename(nm).replace("/", "");
elt.L = elt.R = elt.C = -(elt.color = 1);
elt.size = elt.content ? elt.content.length : 0;
elt.start = 0;
elt.clsid = elt.clsid || HEADER_CLSID;
if (i8 === 0) {
elt.C = data.length > 1 ? 1 : -1;
elt.size = 0;
elt.type = 5;
} else if (nm.slice(-1) == "/") {
for (j3 = i8 + 1; j3 < data.length; ++j3) if (dirname(cfb.FullPaths[j3]) == nm) break;
elt.C = j3 >= data.length ? -1 : j3;
for (j3 = i8 + 1; j3 < data.length; ++j3) if (dirname(cfb.FullPaths[j3]) == dirname(nm)) break;
elt.R = j3 >= data.length ? -1 : j3;
elt.type = 1;
} else {
if (dirname(cfb.FullPaths[i8 + 1] || "") == dirname(nm)) elt.R = i8 + 1;
elt.type = 2;
}
}
}
function _write(cfb, options) {
var _opts = options || {};
if (_opts.fileType == "mad") return write_mad(cfb, _opts);
rebuild_cfb(cfb);
switch (_opts.fileType) {
case "zip":
return write_zip(cfb, _opts);
}
var L3 = (function(cfb2) {
var mini_size = 0, fat_size = 0;
for (var i9 = 0; i9 < cfb2.FileIndex.length; ++i9) {
var file2 = cfb2.FileIndex[i9];
if (!file2.content) continue;
var flen2 = file2.content.length;
if (flen2 > 0) {
if (flen2 < 4096) mini_size += flen2 + 63 >> 6;
else fat_size += flen2 + 511 >> 9;
}
}
var dir_cnt = cfb2.FullPaths.length + 3 >> 2;
var mini_cnt = mini_size + 7 >> 3;
var mfat_cnt = mini_size + 127 >> 7;
var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
var fat_cnt = fat_base + 127 >> 7;
var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt - 109) / 127);
while (fat_base + fat_cnt + difat_cnt + 127 >> 7 > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt - 109) / 127);
var L4 = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
cfb2.FileIndex[0].size = mini_size << 6;
L4[7] = (cfb2.FileIndex[0].start = L4[0] + L4[1] + L4[2] + L4[3] + L4[4] + L4[5]) + (L4[6] + 7 >> 3);
return L4;
})(cfb);
var o9 = new_buf(L3[7] << 9);
var i8 = 0, T3 = 0;
{
for (i8 = 0; i8 < 8; ++i8) o9.write_shift(1, HEADER_SIG[i8]);
for (i8 = 0; i8 < 8; ++i8) o9.write_shift(2, 0);
o9.write_shift(2, 62);
o9.write_shift(2, 3);
o9.write_shift(2, 65534);
o9.write_shift(2, 9);
o9.write_shift(2, 6);
for (i8 = 0; i8 < 3; ++i8) o9.write_shift(2, 0);
o9.write_shift(4, 0);
o9.write_shift(4, L3[2]);
o9.write_shift(4, L3[0] + L3[1] + L3[2] + L3[3] - 1);
o9.write_shift(4, 0);
o9.write_shift(4, 1 << 12);
o9.write_shift(4, L3[3] ? L3[0] + L3[1] + L3[2] - 1 : ENDOFCHAIN);
o9.write_shift(4, L3[3]);
o9.write_shift(-4, L3[1] ? L3[0] - 1 : ENDOFCHAIN);
o9.write_shift(4, L3[1]);
for (i8 = 0; i8 < 109; ++i8) o9.write_shift(-4, i8 < L3[2] ? L3[1] + i8 : -1);
}
if (L3[1]) {
for (T3 = 0; T3 < L3[1]; ++T3) {
for (; i8 < 236 + T3 * 127; ++i8) o9.write_shift(-4, i8 < L3[2] ? L3[1] + i8 : -1);
o9.write_shift(-4, T3 === L3[1] - 1 ? ENDOFCHAIN : T3 + 1);
}
}
var chainit = function(w3) {
for (T3 += w3; i8 < T3 - 1; ++i8) o9.write_shift(-4, i8 + 1);
if (w3) {
++i8;
o9.write_shift(-4, ENDOFCHAIN);
}
};
T3 = i8 = 0;
for (T3 += L3[1]; i8 < T3; ++i8) o9.write_shift(-4, consts.DIFSECT);
for (T3 += L3[2]; i8 < T3; ++i8) o9.write_shift(-4, consts.FATSECT);
chainit(L3[3]);
chainit(L3[4]);
var j3 = 0, flen = 0;
var file = cfb.FileIndex[0];
for (; j3 < cfb.FileIndex.length; ++j3) {
file = cfb.FileIndex[j3];
if (!file.content) continue;
flen = file.content.length;
if (flen < 4096) continue;
file.start = T3;
chainit(flen + 511 >> 9);
}
chainit(L3[6] + 7 >> 3);
while (o9.l & 511) o9.write_shift(-4, consts.ENDOFCHAIN);
T3 = i8 = 0;
for (j3 = 0; j3 < cfb.FileIndex.length; ++j3) {
file = cfb.FileIndex[j3];
if (!file.content) continue;
flen = file.content.length;
if (!flen || flen >= 4096) continue;
file.start = T3;
chainit(flen + 63 >> 6);
}
while (o9.l & 511) o9.write_shift(-4, consts.ENDOFCHAIN);
for (i8 = 0; i8 < L3[4] << 2; ++i8) {
var nm = cfb.FullPaths[i8];
if (!nm || nm.length === 0) {
for (j3 = 0; j3 < 17; ++j3) o9.write_shift(4, 0);
for (j3 = 0; j3 < 3; ++j3) o9.write_shift(4, -1);
for (j3 = 0; j3 < 12; ++j3) o9.write_shift(4, 0);
continue;
}
file = cfb.FileIndex[i8];
if (i8 === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
var _nm = i8 === 0 && _opts.root || file.name;
if (_nm.length > 31) {
console.error("Name " + _nm + " will be truncated to " + _nm.slice(0, 31));
_nm = _nm.slice(0, 31);
}
flen = 2 * (_nm.length + 1);
o9.write_shift(64, _nm, "utf16le");
o9.write_shift(2, flen);
o9.write_shift(1, file.type);
o9.write_shift(1, file.color);
o9.write_shift(-4, file.L);
o9.write_shift(-4, file.R);
o9.write_shift(-4, file.C);
if (!file.clsid) for (j3 = 0; j3 < 4; ++j3) o9.write_shift(4, 0);
else o9.write_shift(16, file.clsid, "hex");
o9.write_shift(4, file.state || 0);
o9.write_shift(4, 0);
o9.write_shift(4, 0);
o9.write_shift(4, 0);
o9.write_shift(4, 0);
o9.write_shift(4, file.start);
o9.write_shift(4, file.size);
o9.write_shift(4, 0);
}
for (i8 = 1; i8 < cfb.FileIndex.length; ++i8) {
file = cfb.FileIndex[i8];
if (file.size >= 4096) {
o9.l = file.start + 1 << 9;
if (has_buf && Buffer.isBuffer(file.content)) {
file.content.copy(o9, o9.l, 0, file.size);
o9.l += file.size + 511 & -512;
} else {
for (j3 = 0; j3 < file.size; ++j3) o9.write_shift(1, file.content[j3]);
for (; j3 & 511; ++j3) o9.write_shift(1, 0);
}
}
}
for (i8 = 1; i8 < cfb.FileIndex.length; ++i8) {
file = cfb.FileIndex[i8];
if (file.size > 0 && file.size < 4096) {
if (has_buf && Buffer.isBuffer(file.content)) {
file.content.copy(o9, o9.l, 0, file.size);
o9.l += file.size + 63 & -64;
} else {
for (j3 = 0; j3 < file.size; ++j3) o9.write_shift(1, file.content[j3]);
for (; j3 & 63; ++j3) o9.write_shift(1, 0);
}
}
}
if (has_buf) {
o9.l = o9.length;
} else {
while (o9.l < o9.length) o9.write_shift(1, 0);
}
return o9;
}
function find2(cfb, path6) {
var UCFullPaths = cfb.FullPaths.map(function(x2) {
return x2.toUpperCase();
});
var UCPaths = UCFullPaths.map(function(x2) {
var y4 = x2.split("/");
return y4[y4.length - (x2.slice(-1) == "/" ? 2 : 1)];
});
var k2 = false;
if (path6.charCodeAt(0) === 47) {
k2 = true;
path6 = UCFullPaths[0].slice(0, -1) + path6;
} else k2 = path6.indexOf("/") !== -1;
var UCPath = path6.toUpperCase();
var w3 = k2 === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
if (w3 !== -1) return cfb.FileIndex[w3];
var m4 = !UCPath.match(chr1);
UCPath = UCPath.replace(chr0, "");
if (m4) UCPath = UCPath.replace(chr1, "!");
for (w3 = 0; w3 < UCFullPaths.length; ++w3) {
if ((m4 ? UCFullPaths[w3].replace(chr1, "!") : UCFullPaths[w3]).replace(chr0, "") == UCPath) return cfb.FileIndex[w3];
if ((m4 ? UCPaths[w3].replace(chr1, "!") : UCPaths[w3]).replace(chr0, "") == UCPath) return cfb.FileIndex[w3];
}
return null;
}
var MSSZ = 64;
var ENDOFCHAIN = -2;
var HEADER_SIGNATURE = "d0cf11e0a1b11ae1";
var HEADER_SIG = [208, 207, 17, 224, 161, 177, 26, 225];
var HEADER_CLSID = "00000000000000000000000000000000";
var consts = {
/* 2.1 Compund File Sector Numbers and Types */
MAXREGSECT: -6,
DIFSECT: -4,
FATSECT: -3,
ENDOFCHAIN,
FREESECT: -1,
/* 2.2 Compound File Header */
HEADER_SIGNATURE,
HEADER_MINOR_VERSION: "3e00",
MAXREGSID: -6,
NOSTREAM: -1,
HEADER_CLSID,
/* 2.6.1 Compound File Directory Entry */
EntryTypes: ["unknown", "storage", "stream", "lockbytes", "property", "root"]
};
function write_file(cfb, filename2, options) {
get_fs();
var o9 = _write(cfb, options);
fs.writeFileSync(filename2, o9);
}
function a2s2(o9) {
var out = new Array(o9.length);
for (var i8 = 0; i8 < o9.length; ++i8) out[i8] = String.fromCharCode(o9[i8]);
return out.join("");
}
function write(cfb, options) {
var o9 = _write(cfb, options);
switch (options && options.type || "buffer") {
case "file":
get_fs();
fs.writeFileSync(options.filename, o9);
return o9;
case "binary":
return typeof o9 == "string" ? o9 : a2s2(o9);
case "base64":
return Base64_encode(typeof o9 == "string" ? o9 : a2s2(o9));
case "buffer":
if (has_buf) return Buffer.isBuffer(o9) ? o9 : Buffer_from(o9);
/* falls through */
case "array":
return typeof o9 == "string" ? s2a(o9) : o9;
}
return o9;
}
var _zlib;
function use_zlib(zlib) {
try {
var InflateRaw = zlib.InflateRaw;
var InflRaw = new InflateRaw();
InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
if (InflRaw.bytesRead) _zlib = zlib;
else throw new Error("zlib does not expose bytesRead");
} catch (e9) {
console.error("cannot use native zlib: " + (e9.message || e9));
}
}
function _inflateRawSync(payload, usz) {
if (!_zlib) return _inflate(payload, usz);
var InflateRaw = _zlib.InflateRaw;
var InflRaw = new InflateRaw();
var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
payload.l += InflRaw.bytesRead;
return out;
}
function _deflateRawSync(payload) {
return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
}
var CLEN_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
var LEN_LN = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
var DST_LN = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
function bit_swap_8(n7) {
var t6 = (n7 << 1 | n7 << 11) & 139536 | (n7 << 5 | n7 << 15) & 558144;
return (t6 >> 16 | t6 >> 8 | t6) & 255;
}
var use_typed_arrays = typeof Uint8Array !== "undefined";
var bitswap8 = use_typed_arrays ? new Uint8Array(1 << 8) : [];
for (var q2 = 0; q2 < 1 << 8; ++q2) bitswap8[q2] = bit_swap_8(q2);
function bit_swap_n(n7, b4) {
var rev = bitswap8[n7 & 255];
if (b4 <= 8) return rev >>> 8 - b4;
rev = rev << 8 | bitswap8[n7 >> 8 & 255];
if (b4 <= 16) return rev >>> 16 - b4;
rev = rev << 8 | bitswap8[n7 >> 16 & 255];
return rev >>> 24 - b4;
}
function read_bits_2(buf, bl) {
var w3 = bl & 7, h7 = bl >>> 3;
return (buf[h7] | (w3 <= 6 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 3;
}
function read_bits_3(buf, bl) {
var w3 = bl & 7, h7 = bl >>> 3;
return (buf[h7] | (w3 <= 5 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 7;
}
function read_bits_4(buf, bl) {
var w3 = bl & 7, h7 = bl >>> 3;
return (buf[h7] | (w3 <= 4 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 15;
}
function read_bits_5(buf, bl) {
var w3 = bl & 7, h7 = bl >>> 3;
return (buf[h7] | (w3 <= 3 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 31;
}
function read_bits_7(buf, bl) {
var w3 = bl & 7, h7 = bl >>> 3;
return (buf[h7] | (w3 <= 1 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 127;
}
function read_bits_n(buf, bl, n7) {
var w3 = bl & 7, h7 = bl >>> 3, f4 = (1 << n7) - 1;
var v4 = buf[h7] >>> w3;
if (n7 < 8 - w3) return v4 & f4;
v4 |= buf[h7 + 1] << 8 - w3;
if (n7 < 16 - w3) return v4 & f4;
v4 |= buf[h7 + 2] << 16 - w3;
if (n7 < 24 - w3) return v4 & f4;
v4 |= buf[h7 + 3] << 24 - w3;
return v4 & f4;
}
function write_bits_3(buf, bl, v4) {
var w3 = bl & 7, h7 = bl >>> 3;
if (w3 <= 5) buf[h7] |= (v4 & 7) << w3;
else {
buf[h7] |= v4 << w3 & 255;
buf[h7 + 1] = (v4 & 7) >> 8 - w3;
}
return bl + 3;
}
function write_bits_1(buf, bl, v4) {
var w3 = bl & 7, h7 = bl >>> 3;
v4 = (v4 & 1) << w3;
buf[h7] |= v4;
return bl + 1;
}
function write_bits_8(buf, bl, v4) {
var w3 = bl & 7, h7 = bl >>> 3;
v4 <<= w3;
buf[h7] |= v4 & 255;
v4 >>>= 8;
buf[h7 + 1] = v4;
return bl + 8;
}
function write_bits_16(buf, bl, v4) {
var w3 = bl & 7, h7 = bl >>> 3;
v4 <<= w3;
buf[h7] |= v4 & 255;
v4 >>>= 8;
buf[h7 + 1] = v4 & 255;
buf[h7 + 2] = v4 >>> 8;
return bl + 16;
}
function realloc(b4, sz) {
var L3 = b4.length, M4 = 2 * L3 > sz ? 2 * L3 : sz + 5, i8 = 0;
if (L3 >= sz) return b4;
if (has_buf) {
var o9 = new_unsafe_buf(M4);
if (b4.copy) b4.copy(o9);
else for (; i8 < b4.length; ++i8) o9[i8] = b4[i8];
return o9;
} else if (use_typed_arrays) {
var a3 = new Uint8Array(M4);
if (a3.set) a3.set(b4);
else for (; i8 < L3; ++i8) a3[i8] = b4[i8];
return a3;
}
b4.length = M4;
return b4;
}
function zero_fill_array(n7) {
var o9 = new Array(n7);
for (var i8 = 0; i8 < n7; ++i8) o9[i8] = 0;
return o9;
}
function build_tree(clens, cmap, MAX) {
var maxlen = 1, w3 = 0, i8 = 0, j3 = 0, ccode = 0, L3 = clens.length;
var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
for (i8 = 0; i8 < 32; ++i8) bl_count[i8] = 0;
for (i8 = L3; i8 < MAX; ++i8) clens[i8] = 0;
L3 = clens.length;
var ctree = use_typed_arrays ? new Uint16Array(L3) : zero_fill_array(L3);
for (i8 = 0; i8 < L3; ++i8) {
bl_count[w3 = clens[i8]]++;
if (maxlen < w3) maxlen = w3;
ctree[i8] = 0;
}
bl_count[0] = 0;
for (i8 = 1; i8 <= maxlen; ++i8) bl_count[i8 + 16] = ccode = ccode + bl_count[i8 - 1] << 1;
for (i8 = 0; i8 < L3; ++i8) {
ccode = clens[i8];
if (ccode != 0) ctree[i8] = bl_count[ccode + 16]++;
}
var cleni = 0;
for (i8 = 0; i8 < L3; ++i8) {
cleni = clens[i8];
if (cleni != 0) {
ccode = bit_swap_n(ctree[i8], maxlen) >> maxlen - cleni;
for (j3 = (1 << maxlen + 4 - cleni) - 1; j3 >= 0; --j3)
cmap[ccode | j3 << cleni] = cleni & 15 | i8 << 4;
}
}
return maxlen;
}
var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
if (!use_typed_arrays) {
for (var i7 = 0; i7 < 512; ++i7) fix_lmap[i7] = 0;
for (i7 = 0; i7 < 32; ++i7) fix_dmap[i7] = 0;
}
(function() {
var dlens = [];
var i8 = 0;
for (; i8 < 32; i8++) dlens.push(5);
build_tree(dlens, fix_dmap, 32);
var clens = [];
i8 = 0;
for (; i8 <= 143; i8++) clens.push(8);
for (; i8 <= 255; i8++) clens.push(9);
for (; i8 <= 279; i8++) clens.push(7);
for (; i8 <= 287; i8++) clens.push(8);
build_tree(clens, fix_lmap, 288);
})();
var _deflateRaw = /* @__PURE__ */ (function _deflateRawIIFE() {
var DST_LN_RE = use_typed_arrays ? new Uint8Array(32768) : [];
var j3 = 0, k2 = 0;
for (; j3 < DST_LN.length - 1; ++j3) {
for (; k2 < DST_LN[j3 + 1]; ++k2) DST_LN_RE[k2] = j3;
}
for (; k2 < 32768; ++k2) DST_LN_RE[k2] = 29;
var LEN_LN_RE = use_typed_arrays ? new Uint8Array(259) : [];
for (j3 = 0, k2 = 0; j3 < LEN_LN.length - 1; ++j3) {
for (; k2 < LEN_LN[j3 + 1]; ++k2) LEN_LN_RE[k2] = j3;
}
function write_stored(data, out) {
var boff = 0;
while (boff < data.length) {
var L3 = Math.min(65535, data.length - boff);
var h7 = boff + L3 == data.length;
out.write_shift(1, +h7);
out.write_shift(2, L3);
out.write_shift(2, ~L3 & 65535);
while (L3-- > 0) out[out.l++] = data[boff++];
}
return out.l;
}
function write_huff_fixed(data, out) {
var bl = 0;
var boff = 0;
var addrs = use_typed_arrays ? new Uint16Array(32768) : [];
while (boff < data.length) {
var L3 = (
/* data.length - boff; */
Math.min(65535, data.length - boff)
);
if (L3 < 10) {
bl = write_bits_3(out, bl, +!!(boff + L3 == data.length));
if (bl & 7) bl += 8 - (bl & 7);
out.l = bl / 8 | 0;
out.write_shift(2, L3);
out.write_shift(2, ~L3 & 65535);
while (L3-- > 0) out[out.l++] = data[boff++];
bl = out.l * 8;
continue;
}
bl = write_bits_3(out, bl, +!!(boff + L3 == data.length) + 2);
var hash = 0;
while (L3-- > 0) {
var d4 = data[boff];
hash = (hash << 5 ^ d4) & 32767;
var match2 = -1, mlen = 0;
if (match2 = addrs[hash]) {
match2 |= boff & ~32767;
if (match2 > boff) match2 -= 32768;
if (match2 < boff) while (data[match2 + mlen] == data[boff + mlen] && mlen < 250) ++mlen;
}
if (mlen > 2) {
d4 = LEN_LN_RE[mlen];
if (d4 <= 22) bl = write_bits_8(out, bl, bitswap8[d4 + 1] >> 1) - 1;
else {
write_bits_8(out, bl, 3);
bl += 5;
write_bits_8(out, bl, bitswap8[d4 - 23] >> 5);
bl += 3;
}
var len_eb = d4 < 8 ? 0 : d4 - 4 >> 2;
if (len_eb > 0) {
write_bits_16(out, bl, mlen - LEN_LN[d4]);
bl += len_eb;
}
d4 = DST_LN_RE[boff - match2];
bl = write_bits_8(out, bl, bitswap8[d4] >> 3);
bl -= 3;
var dst_eb = d4 < 4 ? 0 : d4 - 2 >> 1;
if (dst_eb > 0) {
write_bits_16(out, bl, boff - match2 - DST_LN[d4]);
bl += dst_eb;
}
for (var q3 = 0; q3 < mlen; ++q3) {
addrs[hash] = boff & 32767;
hash = (hash << 5 ^ data[boff]) & 32767;
++boff;
}
L3 -= mlen - 1;
} else {
if (d4 <= 143) d4 = d4 + 48;
else bl = write_bits_1(out, bl, 1);
bl = write_bits_8(out, bl, bitswap8[d4]);
addrs[hash] = boff & 32767;
++boff;
}
}
bl = write_bits_8(out, bl, 0) - 1;
}
out.l = (bl + 7) / 8 | 0;
return out.l;
}
return function _deflateRaw2(data, out) {
if (data.length < 8) return write_stored(data, out);
return write_huff_fixed(data, out);
};
})();
function _deflate(data) {
var buf = new_buf(50 + Math.floor(data.length * 1.1));
var off = _deflateRaw(data, buf);
return buf.slice(0, off);
}
var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128);
var dyn_len_1 = 1, dyn_len_2 = 1;
function dyn(data, boff) {
var _HLIT = read_bits_5(data, boff) + 257;
boff += 5;
var _HDIST = read_bits_5(data, boff) + 1;
boff += 5;
var _HCLEN = read_bits_4(data, boff) + 4;
boff += 4;
var w3 = 0;
var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
var ctree = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var maxlen = 1;
var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
var L3 = clens.length;
for (var i8 = 0; i8 < _HCLEN; ++i8) {
clens[CLEN_ORDER[i8]] = w3 = read_bits_3(data, boff);
if (maxlen < w3) maxlen = w3;
bl_count[w3]++;
boff += 3;
}
var ccode = 0;
bl_count[0] = 0;
for (i8 = 1; i8 <= maxlen; ++i8) next_code[i8] = ccode = ccode + bl_count[i8 - 1] << 1;
for (i8 = 0; i8 < L3; ++i8) if ((ccode = clens[i8]) != 0) ctree[i8] = next_code[ccode]++;
var cleni = 0;
for (i8 = 0; i8 < L3; ++i8) {
cleni = clens[i8];
if (cleni != 0) {
ccode = bitswap8[ctree[i8]] >> 8 - cleni;
for (var j3 = (1 << 7 - cleni) - 1; j3 >= 0; --j3) dyn_cmap[ccode | j3 << cleni] = cleni & 7 | i8 << 3;
}
}
var hcodes = [];
maxlen = 1;
for (; hcodes.length < _HLIT + _HDIST; ) {
ccode = dyn_cmap[read_bits_7(data, boff)];
boff += ccode & 7;
switch (ccode >>>= 3) {
case 16:
w3 = 3 + read_bits_2(data, boff);
boff += 2;
ccode = hcodes[hcodes.length - 1];
while (w3-- > 0) hcodes.push(ccode);
break;
case 17:
w3 = 3 + read_bits_3(data, boff);
boff += 3;
while (w3-- > 0) hcodes.push(0);
break;
case 18:
w3 = 11 + read_bits_7(data, boff);
boff += 7;
while (w3-- > 0) hcodes.push(0);
break;
default:
hcodes.push(ccode);
if (maxlen < ccode) maxlen = ccode;
break;
}
}
var h12 = hcodes.slice(0, _HLIT), h23 = hcodes.slice(_HLIT);
for (i8 = _HLIT; i8 < 286; ++i8) h12[i8] = 0;
for (i8 = _HDIST; i8 < 30; ++i8) h23[i8] = 0;
dyn_len_1 = build_tree(h12, dyn_lmap, 286);
dyn_len_2 = build_tree(h23, dyn_dmap, 30);
return boff;
}
function inflate(data, usz) {
if (data[0] == 3 && !(data[1] & 3)) {
return [new_raw_buf(usz), 2];
}
var boff = 0;
var header = 0;
var outbuf = new_unsafe_buf(usz ? usz : 1 << 18);
var woff = 0;
var OL = outbuf.length >>> 0;
var max_len_1 = 0, max_len_2 = 0;
while ((header & 1) == 0) {
header = read_bits_3(data, boff);
boff += 3;
if (header >>> 1 == 0) {
if (boff & 7) boff += 8 - (boff & 7);
var sz = data[boff >>> 3] | data[(boff >>> 3) + 1] << 8;
boff += 32;
if (sz > 0) {
if (!usz && OL < woff + sz) {
outbuf = realloc(outbuf, woff + sz);
OL = outbuf.length;
}
while (sz-- > 0) {
outbuf[woff++] = data[boff >>> 3];
boff += 8;
}
}
continue;
} else if (header >> 1 == 1) {
max_len_1 = 9;
max_len_2 = 5;
} else {
boff = dyn(data, boff);
max_len_1 = dyn_len_1;
max_len_2 = dyn_len_2;
}
for (; ; ) {
if (!usz && OL < woff + 32767) {
outbuf = realloc(outbuf, woff + 32767);
OL = outbuf.length;
}
var bits = read_bits_n(data, boff, max_len_1);
var code = header >>> 1 == 1 ? fix_lmap[bits] : dyn_lmap[bits];
boff += code & 15;
code >>>= 4;
if ((code >>> 8 & 255) === 0) outbuf[woff++] = code;
else if (code == 256) break;
else {
code -= 257;
var len_eb = code < 8 ? 0 : code - 4 >> 2;
if (len_eb > 5) len_eb = 0;
var tgt = woff + LEN_LN[code];
if (len_eb > 0) {
tgt += read_bits_n(data, boff, len_eb);
boff += len_eb;
}
bits = read_bits_n(data, boff, max_len_2);
code = header >>> 1 == 1 ? fix_dmap[bits] : dyn_dmap[bits];
boff += code & 15;
code >>>= 4;
var dst_eb = code < 4 ? 0 : code - 2 >> 1;
var dst = DST_LN[code];
if (dst_eb > 0) {
dst += read_bits_n(data, boff, dst_eb);
boff += dst_eb;
}
if (!usz && OL < tgt) {
outbuf = realloc(outbuf, tgt + 100);
OL = outbuf.length;
}
while (woff < tgt) {
outbuf[woff] = outbuf[woff - dst];
++woff;
}
}
}
}
if (usz) return [outbuf, boff + 7 >>> 3];
return [outbuf.slice(0, woff), boff + 7 >>> 3];
}
function _inflate(payload, usz) {
var data = payload.slice(payload.l || 0);
var out = inflate(data, usz);
payload.l += out[1];
return out[0];
}
function warn_or_throw(wrn, msg) {
if (wrn) {
if (typeof console !== "undefined") console.error(msg);
} else throw new Error(msg);
}
function parse_zip2(file, options) {
var blob = (
/*::(*/
file
);
prep_blob(blob, 0);
var FileIndex = [], FullPaths = [];
var o9 = {
FileIndex,
FullPaths
};
init_cfb(o9, { root: options.root });
var i8 = blob.length - 4;
while ((blob[i8] != 80 || blob[i8 + 1] != 75 || blob[i8 + 2] != 5 || blob[i8 + 3] != 6) && i8 >= 0) --i8;
blob.l = i8 + 4;
blob.l += 4;
var fcnt = blob.read_shift(2);
blob.l += 6;
var start_cd = blob.read_shift(4);
blob.l = start_cd;
for (i8 = 0; i8 < fcnt; ++i8) {
blob.l += 20;
var csz = blob.read_shift(4);
var usz = blob.read_shift(4);
var namelen = blob.read_shift(2);
var efsz = blob.read_shift(2);
var fcsz = blob.read_shift(2);
blob.l += 8;
var offset = blob.read_shift(4);
var EF = parse_extra_field(
/*::(*/
blob.slice(blob.l + namelen, blob.l + namelen + efsz)
/*:: :any)*/
);
blob.l += namelen + efsz + fcsz;
var L3 = blob.l;
blob.l = offset + 4;
if (EF && EF[1]) {
if ((EF[1] || {}).usz) usz = EF[1].usz;
if ((EF[1] || {}).csz) csz = EF[1].csz;
}
parse_local_file(blob, csz, usz, o9, EF);
blob.l = L3;
}
return o9;
}
function parse_local_file(blob, csz, usz, o9, EF) {
blob.l += 2;
var flags = blob.read_shift(2);
var meth = blob.read_shift(2);
var date = parse_dos_date(blob);
if (flags & 8257) throw new Error("Unsupported ZIP encryption");
var crc32 = blob.read_shift(4);
var _csz = blob.read_shift(4);
var _usz = blob.read_shift(4);
var namelen = blob.read_shift(2);
var efsz = blob.read_shift(2);
var name = "";
for (var i8 = 0; i8 < namelen; ++i8) name += String.fromCharCode(blob[blob.l++]);
if (efsz) {
var ef = parse_extra_field(
/*::(*/
blob.slice(blob.l, blob.l + efsz)
/*:: :any)*/
);
if ((ef[21589] || {}).mt) date = ef[21589].mt;
if ((ef[1] || {}).usz) _usz = ef[1].usz;
if ((ef[1] || {}).csz) _csz = ef[1].csz;
if (EF) {
if ((EF[21589] || {}).mt) date = EF[21589].mt;
if ((EF[1] || {}).usz) _usz = EF[1].usz;
if ((EF[1] || {}).csz) _csz = EF[1].csz;
}
}
blob.l += efsz;
var data = blob.slice(blob.l, blob.l + _csz);
switch (meth) {
case 8:
data = _inflateRawSync(blob, _usz);
break;
case 0:
blob.l += _csz;
break;
// TODO: scan for magic number
default:
throw new Error("Unsupported ZIP Compression method " + meth);
}
var wrn = false;
if (flags & 8) {
crc32 = blob.read_shift(4);
if (crc32 == 134695760) {
crc32 = blob.read_shift(4);
wrn = true;
}
_csz = blob.read_shift(4);
_usz = blob.read_shift(4);
}
if (_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
if (_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
cfb_add(o9, name, data, { unsafe: true, mt: date });
}
function write_zip(cfb, options) {
var _opts = options || {};
var out = [], cdirs = [];
var o9 = new_buf(1);
var method = _opts.compression ? 8 : 0, flags = 0;
var desc = false;
if (desc) flags |= 8;
var i8 = 0, j3 = 0;
var start_cd = 0, fcnt = 0;
var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
var crcs = [];
var sz_cd = 0;
for (i8 = 1; i8 < cfb.FullPaths.length; ++i8) {
fp = cfb.FullPaths[i8].slice(root.length);
fi = cfb.FileIndex[i8];
if (!fi.size || !fi.content || Array.isArray(fi.content) && fi.content.length == 0 || fp == "Sh33tJ5") continue;
var start = start_cd;
var namebuf = new_buf(fp.length);
for (j3 = 0; j3 < fp.length; ++j3) namebuf.write_shift(1, fp.charCodeAt(j3) & 127);
namebuf = namebuf.slice(0, namebuf.l);
crcs[fcnt] = typeof fi.content == "string" ? CRC32.bstr(fi.content, 0) : CRC32.buf(
/*::((*/
fi.content,
0
);
var outbuf = typeof fi.content == "string" ? s2a(fi.content) : fi.content;
if (method == 8) outbuf = _deflateRawSync(outbuf);
o9 = new_buf(30);
o9.write_shift(4, 67324752);
o9.write_shift(2, 20);
o9.write_shift(2, flags);
o9.write_shift(2, method);
if (fi.mt) write_dos_date(o9, fi.mt);
else o9.write_shift(4, 0);
o9.write_shift(-4, flags & 8 ? 0 : crcs[fcnt]);
o9.write_shift(4, flags & 8 ? 0 : outbuf.length);
o9.write_shift(4, flags & 8 ? 0 : (
/*::(*/
fi.content.length
));
o9.write_shift(2, namebuf.length);
o9.write_shift(2, 0);
start_cd += o9.length;
out.push(o9);
start_cd += namebuf.length;
out.push(namebuf);
start_cd += outbuf.length;
out.push(outbuf);
if (flags & 8) {
o9 = new_buf(12);
o9.write_shift(-4, crcs[fcnt]);
o9.write_shift(4, outbuf.length);
o9.write_shift(
4,
/*::(*/
fi.content.length
);
start_cd += o9.l;
out.push(o9);
}
o9 = new_buf(46);
o9.write_shift(4, 33639248);
o9.write_shift(2, 0);
o9.write_shift(2, 20);
o9.write_shift(2, flags);
o9.write_shift(2, method);
o9.write_shift(4, 0);
o9.write_shift(-4, crcs[fcnt]);
o9.write_shift(4, outbuf.length);
o9.write_shift(
4,
/*::(*/
fi.content.length
);
o9.write_shift(2, namebuf.length);
o9.write_shift(2, 0);
o9.write_shift(2, 0);
o9.write_shift(2, 0);
o9.write_shift(2, 0);
o9.write_shift(4, 0);
o9.write_shift(4, start);
sz_cd += o9.l;
cdirs.push(o9);
sz_cd += namebuf.length;
cdirs.push(namebuf);
++fcnt;
}
o9 = new_buf(22);
o9.write_shift(4, 101010256);
o9.write_shift(2, 0);
o9.write_shift(2, 0);
o9.write_shift(2, fcnt);
o9.write_shift(2, fcnt);
o9.write_shift(4, sz_cd);
o9.write_shift(4, start_cd);
o9.write_shift(2, 0);
return bconcat([bconcat(out), bconcat(cdirs), o9]);
}
var ContentTypeMap = {
"htm": "text/html",
"xml": "text/xml",
"gif": "image/gif",
"jpg": "image/jpeg",
"png": "image/png",
"mso": "application/x-mso",
"thmx": "application/vnd.ms-officetheme",
"sh33tj5": "application/octet-stream"
};
function get_content_type(fi, fp) {
if (fi.ctype) return fi.ctype;
var ext2 = fi.name || "", m4 = ext2.match(/\.([^\.]+)$/);
if (m4 && ContentTypeMap[m4[1]]) return ContentTypeMap[m4[1]];
if (fp) {
m4 = (ext2 = fp).match(/[\.\\]([^\.\\])+$/);
if (m4 && ContentTypeMap[m4[1]]) return ContentTypeMap[m4[1]];
}
return "application/octet-stream";
}
function write_base64_76(bstr) {
var data = Base64_encode(bstr);
var o9 = [];
for (var i8 = 0; i8 < data.length; i8 += 76) o9.push(data.slice(i8, i8 + 76));
return o9.join("\r\n") + "\r\n";
}
function write_quoted_printable(text3) {
var encoded = text3.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF=]/g, function(c6) {
var w3 = c6.charCodeAt(0).toString(16).toUpperCase();
return "=" + (w3.length == 1 ? "0" + w3 : w3);
});
encoded = encoded.replace(/ $/mg, "=20").replace(/\t$/mg, "=09");
if (encoded.charAt(0) == "\n") encoded = "=0D" + encoded.slice(1);
encoded = encoded.replace(/\r(?!\n)/mg, "=0D").replace(/\n\n/mg, "\n=0A").replace(/([^\r\n])\n/mg, "$1=0A");
var o9 = [], split = encoded.split("\r\n");
for (var si = 0; si < split.length; ++si) {
var str2 = split[si];
if (str2.length == 0) {
o9.push("");
continue;
}
for (var i8 = 0; i8 < str2.length; ) {
var end = 76;
var tmp = str2.slice(i8, i8 + end);
if (tmp.charAt(end - 1) == "=") end--;
else if (tmp.charAt(end - 2) == "=") end -= 2;
else if (tmp.charAt(end - 3) == "=") end -= 3;
tmp = str2.slice(i8, i8 + end);
i8 += end;
if (i8 < str2.length) tmp += "=";
o9.push(tmp);
}
}
return o9.join("\r\n");
}
function parse_quoted_printable(data) {
var o9 = [];
for (var di = 0; di < data.length; ++di) {
var line = data[di];
while (di <= data.length && line.charAt(line.length - 1) == "=") line = line.slice(0, line.length - 1) + data[++di];
o9.push(line);
}
for (var oi = 0; oi < o9.length; ++oi) o9[oi] = o9[oi].replace(/[=][0-9A-Fa-f]{2}/g, function($$) {
return String.fromCharCode(parseInt($$.slice(1), 16));
});
return s2a(o9.join("\r\n"));
}
function parse_mime(cfb, data, root) {
var fname = "", cte = "", ctype = "", fdata;
var di = 0;
for (; di < 10; ++di) {
var line = data[di];
if (!line || line.match(/^\s*$/)) break;
var m4 = line.match(/^([^:]*?):\s*([^\s].*)$/);
if (m4) switch (m4[1].toLowerCase()) {
case "content-location":
fname = m4[2].trim();
break;
case "content-type":
ctype = m4[2].trim();
break;
case "content-transfer-encoding":
cte = m4[2].trim();
break;
}
}
++di;
switch (cte.toLowerCase()) {
case "base64":
fdata = s2a(Base64_decode(data.slice(di).join("")));
break;
case "quoted-printable":
fdata = parse_quoted_printable(data.slice(di));
break;
default:
throw new Error("Unsupported Content-Transfer-Encoding " + cte);
}
var file = cfb_add(cfb, fname.slice(root.length), fdata, { unsafe: true });
if (ctype) file.ctype = ctype;
}
function parse_mad(file, options) {
if (a2s2(file.slice(0, 13)).toLowerCase() != "mime-version:") throw new Error("Unsupported MAD header");
var root = options && options.root || "";
var data = (has_buf && Buffer.isBuffer(file) ? file.toString("binary") : a2s2(file)).split("\r\n");
var di = 0, row = "";
for (di = 0; di < data.length; ++di) {
row = data[di];
if (!/^Content-Location:/i.test(row)) continue;
row = row.slice(row.indexOf("file"));
if (!root) root = row.slice(0, row.lastIndexOf("/") + 1);
if (row.slice(0, root.length) == root) continue;
while (root.length > 0) {
root = root.slice(0, root.length - 1);
root = root.slice(0, root.lastIndexOf("/") + 1);
if (row.slice(0, root.length) == root) break;
}
}
var mboundary = (data[1] || "").match(/boundary="(.*?)"/);
if (!mboundary) throw new Error("MAD cannot find boundary");
var boundary = "--" + (mboundary[1] || "");
var FileIndex = [], FullPaths = [];
var o9 = {
FileIndex,
FullPaths
};
init_cfb(o9);
var start_di, fcnt = 0;
for (di = 0; di < data.length; ++di) {
var line = data[di];
if (line !== boundary && line !== boundary + "--") continue;
if (fcnt++) parse_mime(o9, data.slice(start_di, di), root);
start_di = di;
}
return o9;
}
function write_mad(cfb, options) {
var opts = options || {};
var boundary = opts.boundary || "SheetJS";
boundary = "------=" + boundary;
var out = [
"MIME-Version: 1.0",
'Content-Type: multipart/related; boundary="' + boundary.slice(2) + '"',
"",
"",
""
];
var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
for (var i8 = 1; i8 < cfb.FullPaths.length; ++i8) {
fp = cfb.FullPaths[i8].slice(root.length);
fi = cfb.FileIndex[i8];
if (!fi.size || !fi.content || fp == "Sh33tJ5") continue;
fp = fp.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF]/g, function(c6) {
return "_x" + c6.charCodeAt(0).toString(16) + "_";
}).replace(/[\u0080-\uFFFF]/g, function(u5) {
return "_u" + u5.charCodeAt(0).toString(16) + "_";
});
var ca = fi.content;
var cstr = has_buf && Buffer.isBuffer(ca) ? ca.toString("binary") : a2s2(ca);
var dispcnt = 0, L3 = Math.min(1024, cstr.length), cc = 0;
for (var csl = 0; csl <= L3; ++csl) if ((cc = cstr.charCodeAt(csl)) >= 32 && cc < 128) ++dispcnt;
var qp = dispcnt >= L3 * 4 / 5;
out.push(boundary);
out.push("Content-Location: " + (opts.root || "file:///C:/SheetJS/") + fp);
out.push("Content-Transfer-Encoding: " + (qp ? "quoted-printable" : "base64"));
out.push("Content-Type: " + get_content_type(fi, fp));
out.push("");
out.push(qp ? write_quoted_printable(cstr) : write_base64_76(cstr));
}
out.push(boundary + "--\r\n");
return out.join("\r\n");
}
function cfb_new(opts) {
var o9 = {};
init_cfb(o9, opts);
return o9;
}
function cfb_add(cfb, name, content, opts) {
var unsafe = opts && opts.unsafe;
if (!unsafe) init_cfb(cfb);
var file = !unsafe && CFB.find(cfb, name);
if (!file) {
var fpath = cfb.FullPaths[0];
if (name.slice(0, fpath.length) == fpath) fpath = name;
else {
if (fpath.slice(-1) != "/") fpath += "/";
fpath = (fpath + name).replace("//", "/");
}
file = { name: filename(name), type: 2 };
cfb.FileIndex.push(file);
cfb.FullPaths.push(fpath);
if (!unsafe) CFB.utils.cfb_gc(cfb);
}
file.content = content;
file.size = content ? content.length : 0;
if (opts) {
if (opts.CLSID) file.clsid = opts.CLSID;
if (opts.mt) file.mt = opts.mt;
if (opts.ct) file.ct = opts.ct;
}
return file;
}
function cfb_del(cfb, name) {
init_cfb(cfb);
var file = CFB.find(cfb, name);
if (file) {
for (var j3 = 0; j3 < cfb.FileIndex.length; ++j3) if (cfb.FileIndex[j3] == file) {
cfb.FileIndex.splice(j3, 1);
cfb.FullPaths.splice(j3, 1);
return true;
}
}
return false;
}
function cfb_mov(cfb, old_name, new_name) {
init_cfb(cfb);
var file = CFB.find(cfb, old_name);
if (file) {
for (var j3 = 0; j3 < cfb.FileIndex.length; ++j3) if (cfb.FileIndex[j3] == file) {
cfb.FileIndex[j3].name = filename(new_name);
cfb.FullPaths[j3] = new_name;
return true;
}
}
return false;
}
function cfb_gc(cfb) {
rebuild_cfb(cfb, true);
}
exports.find = find2;
exports.read = read;
exports.parse = parse3;
exports.write = write;
exports.writeFile = write_file;
exports.utils = {
cfb_new,
cfb_add,
cfb_del,
cfb_mov,
cfb_gc,
ReadShift,
CheckField,
prep_blob,
bconcat,
use_zlib,
_deflateRaw: _deflate,
_inflateRaw: _inflate,
consts
};
return exports;
})();
dnthresh = /* @__PURE__ */ Date.UTC(1899, 11, 30, 0, 0, 0);
dnthresh1 = /* @__PURE__ */ Date.UTC(1899, 11, 31, 0, 0, 0);
dnthresh2 = /* @__PURE__ */ Date.UTC(1904, 0, 1, 0, 0, 0);
pdre1 = /^(\d+):(\d+)(:\d+)?(\.\d+)?$/;
pdre2 = /^(\d+)-(\d+)-(\d+)$/;
pdre3 = /^(\d+)-(\d+)-(\d+)[T ](\d+):(\d+)(:\d+)?(\.\d+)?$/;
FDRE1 = /^(0?\d|1[0-2])(?:|:([0-5]?\d)(?:|(\.\d+)(?:|:([0-5]?\d))|:([0-5]?\d)(|\.\d+)))\s+([ap])m?$/;
FDRE2 = /^([01]?\d|2[0-3])(?:|:([0-5]?\d)(?:|(\.\d+)(?:|:([0-5]?\d))|:([0-5]?\d)(|\.\d+)))$/;
FDISO = /^(\d+)-(\d+)-(\d+)[T ](\d+):(\d+)(:\d+)(\.\d+)?[Z]?$/;
utc_append_works = (/* @__PURE__ */ new Date("6/9/69 00:00 UTC")).valueOf() == -177984e5;
lower_months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
split_regex = /* @__PURE__ */ (function() {
var safe_split_regex = "abacaba".split(/(:?b)/i).length == 5;
return function split_regex2(str2, re2, def) {
if (safe_split_regex || typeof re2 == "string") return str2.split(re2);
var p4 = str2.split(re2), o9 = [p4[0]];
for (var i7 = 1; i7 < p4.length; ++i7) {
o9.push(def);
o9.push(p4[i7]);
}
return o9;
};
})();
xml_boundary = { " ": 1, " ": 1, "\r": 1, "\n": 1, ">": 1 };
str_match_xml_ns = /* @__PURE__ */ (function() {
var str_match_xml_ns_cache = {};
return function str_match_xml_ns2(str2, tag) {
var res = str_match_xml_ns_cache[tag];
if (!res) str_match_xml_ns_cache[tag] = res = [
new RegExp("<(?:\\w+:)?" + tag + "\\b[^<>]*>", "g"),
new RegExp("(?:\\w+:)?" + tag + ">", "g")
];
res[0].lastIndex = res[1].lastIndex = 0;
var m4 = res[0].exec(str2);
if (!m4) return null;
var si = m4.index;
var sf = res[0].lastIndex;
res[1].lastIndex = res[0].lastIndex;
m4 = res[1].exec(str2);
if (!m4) return null;
var ei = m4.index;
var ef = res[1].lastIndex;
return [str2.slice(si, ef), str2.slice(sf, ei)];
};
})();
str_match_xml_ns_g = /* @__PURE__ */ (function() {
var str_match_xml_ns_cache = {};
return function str_match_xml_ns2(str2, tag) {
var out = [];
var res = str_match_xml_ns_cache[tag];
if (!res) str_match_xml_ns_cache[tag] = res = [
new RegExp("<(?:\\w+:)?" + tag + "\\b[^<>]*>", "g"),
new RegExp("(?:\\w+:)?" + tag + ">", "g")
];
res[0].lastIndex = res[1].lastIndex = 0;
var m4;
while (m4 = res[0].exec(str2)) {
var si = m4.index;
res[1].lastIndex = res[0].lastIndex;
m4 = res[1].exec(str2);
if (!m4) return null;
var ef = res[1].lastIndex;
out.push(str2.slice(si, ef));
res[0].lastIndex = res[1].lastIndex;
}
return out.length == 0 ? null : out;
};
})();
str_remove_xml_ns_g = /* @__PURE__ */ (function() {
var str_remove_xml_ns_cache = {};
return function str_remove_xml_ns_g2(str2, tag) {
var out = [];
var res = str_remove_xml_ns_cache[tag];
if (!res) str_remove_xml_ns_cache[tag] = res = [
new RegExp("<(?:\\w+:)?" + tag + "\\b[^<>]*>", "g"),
new RegExp("(?:\\w+:)?" + tag + ">", "g")
];
res[0].lastIndex = res[1].lastIndex = 0;
var m4;
var si = 0, ef = 0;
while (m4 = res[0].exec(str2)) {
si = m4.index;
out.push(str2.slice(ef, si));
ef = si;
res[1].lastIndex = res[0].lastIndex;
m4 = res[1].exec(str2);
if (!m4) return null;
ef = res[1].lastIndex;
res[0].lastIndex = res[1].lastIndex;
}
out.push(str2.slice(ef));
return out.length == 0 ? "" : out.join("");
};
})();
str_match_xml_ig = /* @__PURE__ */ (function() {
var str_match_xml_ns_cache = {};
return function str_match_xml_ns2(str2, tag) {
var out = [];
var res = str_match_xml_ns_cache[tag];
if (!res) str_match_xml_ns_cache[tag] = res = [
new RegExp("<" + tag + "\\b[^<>]*>", "ig"),
new RegExp("" + tag + ">", "ig")
];
res[0].lastIndex = res[1].lastIndex = 0;
var m4;
while (m4 = res[0].exec(str2)) {
var si = m4.index;
res[1].lastIndex = res[0].lastIndex;
m4 = res[1].exec(str2);
if (!m4) return null;
var ef = res[1].lastIndex;
out.push(str2.slice(si, ef));
res[0].lastIndex = res[1].lastIndex;
}
return out.length == 0 ? null : out;
};
})();
XML_HEADER = '\r\n';
attregexg = /\s([^"\s?>\/]+)\s*=\s*((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g;
tagregex1 = /<[\/\?]?[a-zA-Z0-9:_-]+(?:\s+[^"\s?<>\/]+\s*=\s*(?:"[^"]*"|'[^']*'|[^'"<>\s=]+))*\s*[\/\?]?>/mg;
tagregex2 = /<[^<>]*>/g;
tagregex = /* @__PURE__ */ XML_HEADER.match(tagregex1) ? tagregex1 : tagregex2;
nsregex = /<\w*:/;
nsregex2 = /<(\/?)\w+:/;
encodings = {
""": '"',
"'": "'",
">": ">",
"<": "<",
"&": "&"
};
rencoding = /* @__PURE__ */ evert(encodings);
unescapexml = /* @__PURE__ */ (function() {
var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/ig, coderegex = /_x([\da-fA-F]{4})_/ig;
function raw_unescapexml(text3) {
var s6 = text3 + "", i7 = s6.indexOf(" -1 ? 16 : 10)) || $$;
}).replace(coderegex, function(m4, c6) {
return String.fromCharCode(parseInt(c6, 16));
});
var j3 = s6.indexOf("]]>");
return raw_unescapexml(s6.slice(0, i7)) + s6.slice(i7 + 9, j3) + raw_unescapexml(s6.slice(j3 + 3));
}
return function unescapexml2(text3, xlsx) {
var out = raw_unescapexml(text3);
return xlsx ? out.replace(/\r\n/g, "\n") : out;
};
})();
decregex = /[&<>'"]/g;
htmlcharegex = /[\u0000-\u001f]/g;
xlml_fixstr = /* @__PURE__ */ (function() {
var entregex = /(\d+);/g;
function entrepl($$, $1) {
return String.fromCharCode(parseInt($1, 10));
}
return function xlml_fixstr2(str2) {
return str2.replace(entregex, entrepl);
};
})();
utf8corpus = "foo bar baz\xE2\x98\x83\xF0\x9F\x8D\xA3";
utf8read = has_buf && (/* @__PURE__ */ utf8readc(utf8corpus) == /* @__PURE__ */ utf8reada(utf8corpus) && utf8readc || /* @__PURE__ */ utf8readb(utf8corpus) == /* @__PURE__ */ utf8reada(utf8corpus) && utf8readb) || utf8reada;
utf8write = has_buf ? function(data) {
return Buffer_from(data, "utf8").toString("binary");
} : function(orig) {
var out = [], i7 = 0, c6 = 0, d4 = 0;
while (i7 < orig.length) {
c6 = orig.charCodeAt(i7++);
switch (true) {
case c6 < 128:
out.push(String.fromCharCode(c6));
break;
case c6 < 2048:
out.push(String.fromCharCode(192 + (c6 >> 6)));
out.push(String.fromCharCode(128 + (c6 & 63)));
break;
case (c6 >= 55296 && c6 < 57344):
c6 -= 55296;
d4 = orig.charCodeAt(i7++) - 56320 + (c6 << 10);
out.push(String.fromCharCode(240 + (d4 >> 18 & 7)));
out.push(String.fromCharCode(144 + (d4 >> 12 & 63)));
out.push(String.fromCharCode(128 + (d4 >> 6 & 63)));
out.push(String.fromCharCode(128 + (d4 & 63)));
break;
default:
out.push(String.fromCharCode(224 + (c6 >> 12)));
out.push(String.fromCharCode(128 + (c6 >> 6 & 63)));
out.push(String.fromCharCode(128 + (c6 & 63)));
}
}
return out.join("");
};
htmldecode = /* @__PURE__ */ (function() {
var entities = [
["nbsp", " "],
["middot", "\xB7"],
["quot", '"'],
["apos", "'"],
["gt", ">"],
["lt", "<"],
["amp", "&"]
].map(function(x2) {
return [new RegExp("&" + x2[0] + ";", "ig"), x2[1]];
});
return function htmldecode2(str2) {
var o9 = str2.replace(/^[\t\n\r ]+/, "").replace(/(^|[^\t\n\r ])[\t\n\r ]+$/, "$1").replace(/>\s+/g, ">").replace(/\b\s+/g, "\n").replace(/<[^<>]*>/g, "");
for (var i7 = 0; i7 < entities.length; ++i7) o9 = o9.replace(entities[i7][0], entities[i7][1]);
return o9;
};
})();
vtvregex = /<\/?(?:vt:)?variant>/g;
vtmregex = /<(?:vt:)([^<"'>]*)>([\s\S]*);
wtregex = /(^\s|\s$|\n)/;
xlmlregex = /<([\/]?)([^\s?>:\/"]+)(?:\s+[^<>=?"'\s]+="[^"]*?")*\s*[\/]?>/mg;
XMLNS = {
CORE_PROPS: "http://schemas.openxmlformats.org/package/2006/metadata/core-properties",
CUST_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",
EXT_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",
CT: "http://schemas.openxmlformats.org/package/2006/content-types",
RELS: "http://schemas.openxmlformats.org/package/2006/relationships",
TCMNT: "http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments",
"dc": "http://purl.org/dc/elements/1.1/",
"dcterms": "http://purl.org/dc/terms/",
"dcmitype": "http://purl.org/dc/dcmitype/",
"mx": "http://schemas.microsoft.com/office/mac/excel/2008/main",
"r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
"sjs": "http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties",
"vt": "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes",
"xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsd": "http://www.w3.org/2001/XMLSchema"
};
XMLNS_main = [
"http://schemas.openxmlformats.org/spreadsheetml/2006/main",
"http://purl.oclc.org/ooxml/spreadsheetml/main",
"http://schemas.microsoft.com/office/excel/2006/main",
"http://schemas.microsoft.com/office/excel/2006/2"
];
___toBuffer = function(bufs) {
var x2 = [], w3 = 10240;
for (var i7 = 0; i7 < bufs[0].length; ++i7) if (bufs[0][i7]) for (var j3 = 0, L3 = bufs[0][i7].length; j3 < L3; j3 += w3) x2.push.apply(x2, bufs[0][i7].slice(j3, j3 + w3));
return x2;
};
__toBuffer = has_buf ? function(bufs) {
return bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0]) ? Buffer.concat(bufs[0].map(function(x2) {
return Buffer.isBuffer(x2) ? x2 : Buffer_from(x2);
})) : ___toBuffer(bufs);
} : ___toBuffer;
___utf16le = function(b4, s6, e9) {
var ss = [];
for (var i7 = s6; i7 < e9; i7 += 2) ss.push(String.fromCharCode(__readUInt16LE(b4, i7)));
return ss.join("").replace(chr0, "");
};
__utf16le = has_buf ? function(b4, s6, e9) {
if (!Buffer.isBuffer(b4) || !buf_utf16le) return ___utf16le(b4, s6, e9);
return b4.toString("utf16le", s6, e9).replace(chr0, "");
} : ___utf16le;
___hexlify = function(b4, s6, l5) {
var ss = [];
for (var i7 = s6; i7 < s6 + l5; ++i7) ss.push(("0" + b4[i7].toString(16)).slice(-2));
return ss.join("");
};
__hexlify = has_buf ? function(b4, s6, l5) {
return Buffer.isBuffer(b4) ? b4.toString("hex", s6, s6 + l5) : ___hexlify(b4, s6, l5);
} : ___hexlify;
___utf8 = function(b4, s6, e9) {
var ss = [];
for (var i7 = s6; i7 < e9; i7++) ss.push(String.fromCharCode(__readUInt8(b4, i7)));
return ss.join("");
};
__utf8 = has_buf ? function utf8_b(b4, s6, e9) {
return Buffer.isBuffer(b4) ? b4.toString("utf8", s6, e9) : ___utf8(b4, s6, e9);
} : ___utf8;
___lpstr = function(b4, i7) {
var len = __readUInt32LE(b4, i7);
return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len - 1) : "";
};
__lpstr = ___lpstr;
___cpstr = function(b4, i7) {
var len = __readUInt32LE(b4, i7);
return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len - 1) : "";
};
__cpstr = ___cpstr;
___lpwstr = function(b4, i7) {
var len = 2 * __readUInt32LE(b4, i7);
return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len - 1) : "";
};
__lpwstr = ___lpwstr;
___lpp4 = function lpp4_(b4, i7) {
var len = __readUInt32LE(b4, i7);
return len > 0 ? __utf16le(b4, i7 + 4, i7 + 4 + len) : "";
};
__lpp4 = ___lpp4;
___8lpp4 = function(b4, i7) {
var len = __readUInt32LE(b4, i7);
return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len) : "";
};
__8lpp4 = ___8lpp4;
___double = function(b4, idx) {
return read_double_le(b4, idx);
};
__double = ___double;
is_buf = function is_buf_a(a3) {
return Array.isArray(a3) || typeof Uint8Array !== "undefined" && a3 instanceof Uint8Array;
};
if (has_buf) {
__lpstr = function lpstr_b(b4, i7) {
if (!Buffer.isBuffer(b4)) return ___lpstr(b4, i7);
var len = b4.readUInt32LE(i7);
return len > 0 ? b4.toString("utf8", i7 + 4, i7 + 4 + len - 1) : "";
};
__cpstr = function cpstr_b(b4, i7) {
if (!Buffer.isBuffer(b4)) return ___cpstr(b4, i7);
var len = b4.readUInt32LE(i7);
return len > 0 ? b4.toString("utf8", i7 + 4, i7 + 4 + len - 1) : "";
};
__lpwstr = function lpwstr_b(b4, i7) {
if (!Buffer.isBuffer(b4) || !buf_utf16le) return ___lpwstr(b4, i7);
var len = 2 * b4.readUInt32LE(i7);
return b4.toString("utf16le", i7 + 4, i7 + 4 + len - 1);
};
__lpp4 = function lpp4_b(b4, i7) {
if (!Buffer.isBuffer(b4) || !buf_utf16le) return ___lpp4(b4, i7);
var len = b4.readUInt32LE(i7);
return b4.toString("utf16le", i7 + 4, i7 + 4 + len);
};
__8lpp4 = function lpp4_8b(b4, i7) {
if (!Buffer.isBuffer(b4)) return ___8lpp4(b4, i7);
var len = b4.readUInt32LE(i7);
return b4.toString("utf8", i7 + 4, i7 + 4 + len);
};
__double = function double_(b4, i7) {
if (Buffer.isBuffer(b4)) return b4.readDoubleLE(i7);
return ___double(b4, i7);
};
is_buf = function is_buf_b(a3) {
return Buffer.isBuffer(a3) || Array.isArray(a3) || typeof Uint8Array !== "undefined" && a3 instanceof Uint8Array;
};
}
if (typeof $cptable !== "undefined") cpdoit();
__readUInt8 = function(b4, idx) {
return b4[idx];
};
__readUInt16LE = function(b4, idx) {
return b4[idx + 1] * (1 << 8) + b4[idx];
};
__readInt16LE = function(b4, idx) {
var u5 = b4[idx + 1] * (1 << 8) + b4[idx];
return u5 < 32768 ? u5 : (65535 - u5 + 1) * -1;
};
__readUInt32LE = function(b4, idx) {
return b4[idx + 3] * (1 << 24) + (b4[idx + 2] << 16) + (b4[idx + 1] << 8) + b4[idx];
};
__readInt32LE = function(b4, idx) {
return b4[idx + 3] << 24 | b4[idx + 2] << 16 | b4[idx + 1] << 8 | b4[idx];
};
__readInt32BE = function(b4, idx) {
return b4[idx] << 24 | b4[idx + 1] << 16 | b4[idx + 2] << 8 | b4[idx + 3];
};
__writeUInt32LE = function(b4, val2, idx) {
b4[idx] = val2 & 255;
b4[idx + 1] = val2 >>> 8 & 255;
b4[idx + 2] = val2 >>> 16 & 255;
b4[idx + 3] = val2 >>> 24 & 255;
};
__writeInt32LE = function(b4, val2, idx) {
b4[idx] = val2 & 255;
b4[idx + 1] = val2 >> 8 & 255;
b4[idx + 2] = val2 >> 16 & 255;
b4[idx + 3] = val2 >> 24 & 255;
};
__writeUInt16LE = function(b4, val2, idx) {
b4[idx] = val2 & 255;
b4[idx + 1] = val2 >>> 8 & 255;
};
parse_BrtCommentText = parse_RichStr;
parse_XLSBCodeName = parse_XLWideString;
parse_XLNameWideString = parse_XLWideString;
parse_RelID = parse_XLNullableWideString;
parse_UncheckedRfX = parse_RfX;
VT_I2 = 2;
VT_I4 = 3;
VT_BOOL = 11;
VT_VARIANT = 12;
VT_UI4 = 19;
VT_FILETIME = 64;
VT_BLOB = 65;
VT_CF = 71;
VT_VECTOR_VARIANT = 4108;
VT_VECTOR_LPSTR = 4126;
VT_STRING = 80;
VT_USTR = 81;
VT_CUSTOM = [VT_STRING, VT_USTR];
DocSummaryPIDDSI = {
1: { n: "CodePage", t: VT_I2 },
2: { n: "Category", t: VT_STRING },
3: { n: "PresentationFormat", t: VT_STRING },
4: { n: "ByteCount", t: VT_I4 },
5: { n: "LineCount", t: VT_I4 },
6: { n: "ParagraphCount", t: VT_I4 },
7: { n: "SlideCount", t: VT_I4 },
8: { n: "NoteCount", t: VT_I4 },
9: { n: "HiddenCount", t: VT_I4 },
10: { n: "MultimediaClipCount", t: VT_I4 },
11: { n: "ScaleCrop", t: VT_BOOL },
12: {
n: "HeadingPairs",
t: VT_VECTOR_VARIANT
/* VT_VECTOR | VT_VARIANT */
},
13: {
n: "TitlesOfParts",
t: VT_VECTOR_LPSTR
/* VT_VECTOR | VT_LPSTR */
},
14: { n: "Manager", t: VT_STRING },
15: { n: "Company", t: VT_STRING },
16: { n: "LinksUpToDate", t: VT_BOOL },
17: { n: "CharacterCount", t: VT_I4 },
19: { n: "SharedDoc", t: VT_BOOL },
22: { n: "HyperlinksChanged", t: VT_BOOL },
23: { n: "AppVersion", t: VT_I4, p: "version" },
24: { n: "DigSig", t: VT_BLOB },
26: { n: "ContentType", t: VT_STRING },
27: { n: "ContentStatus", t: VT_STRING },
28: { n: "Language", t: VT_STRING },
29: { n: "Version", t: VT_STRING },
255: {},
/* [MS-OLEPS] 2.18 */
2147483648: { n: "Locale", t: VT_UI4 },
2147483651: { n: "Behavior", t: VT_UI4 },
1919054434: {}
};
SummaryPIDSI = {
1: { n: "CodePage", t: VT_I2 },
2: { n: "Title", t: VT_STRING },
3: { n: "Subject", t: VT_STRING },
4: { n: "Author", t: VT_STRING },
5: { n: "Keywords", t: VT_STRING },
6: { n: "Comments", t: VT_STRING },
7: { n: "Template", t: VT_STRING },
8: { n: "LastAuthor", t: VT_STRING },
9: { n: "RevNumber", t: VT_STRING },
10: { n: "EditTime", t: VT_FILETIME },
11: { n: "LastPrinted", t: VT_FILETIME },
12: { n: "CreatedDate", t: VT_FILETIME },
13: { n: "ModifiedDate", t: VT_FILETIME },
14: { n: "PageCount", t: VT_I4 },
15: { n: "WordCount", t: VT_I4 },
16: { n: "CharCount", t: VT_I4 },
17: { n: "Thumbnail", t: VT_CF },
18: { n: "Application", t: VT_STRING },
19: { n: "DocSecurity", t: VT_I4 },
255: {},
/* [MS-OLEPS] 2.18 */
2147483648: { n: "Locale", t: VT_UI4 },
2147483651: { n: "Behavior", t: VT_UI4 },
1919054434: {}
};
CountryEnum = {
1: "US",
// United States
2: "CA",
// Canada
3: "",
// Latin America (except Brazil)
7: "RU",
// Russia
20: "EG",
// Egypt
30: "GR",
// Greece
31: "NL",
// Netherlands
32: "BE",
// Belgium
33: "FR",
// France
34: "ES",
// Spain
36: "HU",
// Hungary
39: "IT",
// Italy
41: "CH",
// Switzerland
43: "AT",
// Austria
44: "GB",
// United Kingdom
45: "DK",
// Denmark
46: "SE",
// Sweden
47: "NO",
// Norway
48: "PL",
// Poland
49: "DE",
// Germany
52: "MX",
// Mexico
55: "BR",
// Brazil
61: "AU",
// Australia
64: "NZ",
// New Zealand
66: "TH",
// Thailand
81: "JP",
// Japan
82: "KR",
// Korea
84: "VN",
// Viet Nam
86: "CN",
// China
90: "TR",
// Turkey
105: "JS",
// Ramastan
213: "DZ",
// Algeria
216: "MA",
// Morocco
218: "LY",
// Libya
351: "PT",
// Portugal
354: "IS",
// Iceland
358: "FI",
// Finland
420: "CZ",
// Czech Republic
886: "TW",
// Taiwan
961: "LB",
// Lebanon
962: "JO",
// Jordan
963: "SY",
// Syria
964: "IQ",
// Iraq
965: "KW",
// Kuwait
966: "SA",
// Saudi Arabia
971: "AE",
// United Arab Emirates
972: "IL",
// Israel
974: "QA",
// Qatar
981: "IR",
// Iran
65535: "US"
// United States
};
XLSFillPattern = [
null,
"solid",
"mediumGray",
"darkGray",
"lightGray",
"darkHorizontal",
"darkVertical",
"darkDown",
"darkUp",
"darkGrid",
"darkTrellis",
"lightHorizontal",
"lightVertical",
"lightDown",
"lightUp",
"lightGrid",
"lightTrellis",
"gray125",
"gray0625"
];
_XLSIcv = /* @__PURE__ */ rgbify([
/* Color Constants */
0,
16777215,
16711680,
65280,
255,
16776960,
16711935,
65535,
/* Overridable Defaults */
0,
16777215,
16711680,
65280,
255,
16776960,
16711935,
65535,
8388608,
32768,
128,
8421376,
8388736,
32896,
12632256,
8421504,
10066431,
10040166,
16777164,
13434879,
6684774,
16744576,
26316,
13421823,
128,
16711935,
16776960,
65535,
8388736,
8388608,
32896,
255,
52479,
13434879,
13434828,
16777113,
10079487,
16751052,
13408767,
16764057,
3368703,
3394764,
10079232,
16763904,
16750848,
16737792,
6710937,
9868950,
13158,
3381606,
13056,
3355392,
10040064,
10040166,
3355545,
3355443,
/* Other entries to appease BIFF8/12 */
0,
/* 0x40 icvForeground ?? */
16777215,
/* 0x41 icvBackground ?? */
0,
/* 0x42 icvFrame ?? */
0,
/* 0x43 icv3D ?? */
0,
/* 0x44 icv3DText ?? */
0,
/* 0x45 icv3DHilite ?? */
0,
/* 0x46 icv3DShadow ?? */
0,
/* 0x47 icvHilite ?? */
0,
/* 0x48 icvCtlText ?? */
0,
/* 0x49 icvCtlScrl ?? */
0,
/* 0x4A icvCtlInv ?? */
0,
/* 0x4B icvCtlBody ?? */
0,
/* 0x4C icvCtlFrame ?? */
0,
/* 0x4D icvCtlFore ?? */
0,
/* 0x4E icvCtlBack ?? */
0,
/* 0x4F icvCtlNeutral */
0,
/* 0x50 icvInfoBk ?? */
0
/* 0x51 icvInfoText ?? */
]);
XLSIcv = /* @__PURE__ */ dup(_XLSIcv);
BErr = {
0: "#NULL!",
7: "#DIV/0!",
15: "#VALUE!",
23: "#REF!",
29: "#NAME?",
36: "#NUM!",
42: "#N/A",
43: "#GETTING_DATA",
255: "#WTF?"
};
RBErr = {
"#NULL!": 0,
"#DIV/0!": 7,
"#VALUE!": 15,
"#REF!": 23,
"#NAME?": 29,
"#NUM!": 36,
"#N/A": 42,
"#GETTING_DATA": 43,
"#WTF?": 255
};
XLSLblBuiltIn = [
"_xlnm.Consolidate_Area",
"_xlnm.Auto_Open",
"_xlnm.Auto_Close",
"_xlnm.Extract",
"_xlnm.Database",
"_xlnm.Criteria",
"_xlnm.Print_Area",
"_xlnm.Print_Titles",
"_xlnm.Recorder",
"_xlnm.Data_Form",
"_xlnm.Auto_Activate",
"_xlnm.Auto_Deactivate",
"_xlnm.Sheet_Title",
"_xlnm._FilterDatabase"
];
ct2type = {
/* Workbook */
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
"application/vnd.ms-excel.sheet.macroEnabled.main+xml": "workbooks",
"application/vnd.ms-excel.sheet.binary.macroEnabled.main": "workbooks",
"application/vnd.ms-excel.addin.macroEnabled.main+xml": "workbooks",
"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": "workbooks",
/* Worksheet */
"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": "sheets",
"application/vnd.ms-excel.worksheet": "sheets",
"application/vnd.ms-excel.binIndexWs": "TODO",
/* Binary Index */
/* Chartsheet */
"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": "charts",
"application/vnd.ms-excel.chartsheet": "charts",
/* Macrosheet */
"application/vnd.ms-excel.macrosheet+xml": "macros",
"application/vnd.ms-excel.macrosheet": "macros",
"application/vnd.ms-excel.intlmacrosheet": "TODO",
"application/vnd.ms-excel.binIndexMs": "TODO",
/* Binary Index */
/* Dialogsheet */
"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": "dialogs",
"application/vnd.ms-excel.dialogsheet": "dialogs",
/* Shared Strings */
"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml": "strs",
"application/vnd.ms-excel.sharedStrings": "strs",
/* Styles */
"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": "styles",
"application/vnd.ms-excel.styles": "styles",
/* File Properties */
"application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
"application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops",
"application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",
/* Custom Data Properties */
"application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty": "TODO",
/* Comments */
"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": "comments",
"application/vnd.ms-excel.comments": "comments",
"application/vnd.ms-excel.threadedcomments+xml": "threadedcomments",
"application/vnd.ms-excel.person+xml": "people",
/* Metadata (Stock/Geography and Dynamic Array) */
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "metadata",
"application/vnd.ms-excel.sheetMetadata": "metadata",
/* PivotTable */
"application/vnd.ms-excel.pivotTable": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO",
/* Chart Objects */
"application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO",
/* Chart Colors */
"application/vnd.ms-office.chartcolorstyle+xml": "TODO",
/* Chart Style */
"application/vnd.ms-office.chartstyle+xml": "TODO",
/* Chart Advanced */
"application/vnd.ms-office.chartex+xml": "TODO",
/* Calculation Chain */
"application/vnd.ms-excel.calcChain": "calcchains",
"application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",
/* Printer Settings */
"application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO",
/* ActiveX */
"application/vnd.ms-office.activeX": "TODO",
"application/vnd.ms-office.activeX+xml": "TODO",
/* Custom Toolbars */
"application/vnd.ms-excel.attachedToolbars": "TODO",
/* External Data Connections */
"application/vnd.ms-excel.connections": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO",
/* External Links */
"application/vnd.ms-excel.externalLink": "links",
"application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "links",
/* PivotCache */
"application/vnd.ms-excel.pivotCacheDefinition": "TODO",
"application/vnd.ms-excel.pivotCacheRecords": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO",
/* Query Table */
"application/vnd.ms-excel.queryTable": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO",
/* Shared Workbook */
"application/vnd.ms-excel.userNames": "TODO",
"application/vnd.ms-excel.revisionHeaders": "TODO",
"application/vnd.ms-excel.revisionLog": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO",
/* Single Cell Table */
"application/vnd.ms-excel.tableSingleCells": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO",
/* Slicer */
"application/vnd.ms-excel.slicer": "TODO",
"application/vnd.ms-excel.slicerCache": "TODO",
"application/vnd.ms-excel.slicer+xml": "TODO",
"application/vnd.ms-excel.slicerCache+xml": "TODO",
/* Sort Map */
"application/vnd.ms-excel.wsSortMap": "TODO",
/* Table */
"application/vnd.ms-excel.table": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO",
/* Themes */
"application/vnd.openxmlformats-officedocument.theme+xml": "themes",
/* Theme Override */
"application/vnd.openxmlformats-officedocument.themeOverride+xml": "TODO",
/* Timeline */
"application/vnd.ms-excel.Timeline+xml": "TODO",
/* verify */
"application/vnd.ms-excel.TimelineCache+xml": "TODO",
/* verify */
/* VBA */
"application/vnd.ms-office.vbaProject": "vba",
"application/vnd.ms-office.vbaProjectSignature": "TODO",
/* Volatile Dependencies */
"application/vnd.ms-office.volatileDependencies": "TODO",
"application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO",
/* Control Properties */
"application/vnd.ms-excel.controlproperties+xml": "TODO",
/* Data Model */
"application/vnd.openxmlformats-officedocument.model+data": "TODO",
/* Survey */
"application/vnd.ms-excel.Survey+xml": "TODO",
/* Drawing */
"application/vnd.openxmlformats-officedocument.drawing+xml": "drawings",
"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO",
"application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO",
"application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO",
"application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO",
"application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO",
/* VML */
"application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO",
"application/vnd.openxmlformats-package.relationships+xml": "rels",
"application/vnd.openxmlformats-officedocument.oleObject": "TODO",
/* Image */
"image/png": "TODO",
"sheet": "js"
};
RELS = {
WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
HLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
VML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
XPATH: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath",
XMISS: "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing",
XLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink",
CXML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
CXMLP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
CMNT: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
CORE_PROPS: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",
EXT_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties",
CUST_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties",
SST: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",
STY: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
THEME: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
CHART: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",
CHARTEX: "http://schemas.microsoft.com/office/2014/relationships/chartEx",
CS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet",
WS: [
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
"http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet"
],
DS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet",
MS: "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet",
IMG: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
DRAW: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",
XLMETA: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",
TCMNT: "http://schemas.microsoft.com/office/2017/10/relationships/threadedComment",
PEOPLE: "http://schemas.microsoft.com/office/2017/10/relationships/person",
CONN: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/connections",
VBA: "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
};
CT_ODS = "application/vnd.oasis.opendocument.spreadsheet";
CORE_PROPS = [
["cp:category", "Category"],
["cp:contentStatus", "ContentStatus"],
["cp:keywords", "Keywords"],
["cp:lastModifiedBy", "LastAuthor"],
["cp:lastPrinted", "LastPrinted"],
["cp:revision", "RevNumber"],
["cp:version", "Version"],
["dc:creator", "Author"],
["dc:description", "Comments"],
["dc:identifier", "Identifier"],
["dc:language", "Language"],
["dc:subject", "Subject"],
["dc:title", "Title"],
["dcterms:created", "CreatedDate", "date"],
["dcterms:modified", "ModifiedDate", "date"]
];
EXT_PROPS = [
["Application", "Application", "string"],
["AppVersion", "AppVersion", "string"],
["Company", "Company", "string"],
["DocSecurity", "DocSecurity", "string"],
["Manager", "Manager", "string"],
["HyperlinksChanged", "HyperlinksChanged", "bool"],
["SharedDoc", "SharedDoc", "bool"],
["LinksUpToDate", "LinksUpToDate", "bool"],
["ScaleCrop", "ScaleCrop", "bool"],
["HeadingPairs", "HeadingPairs", "raw"],
["TitlesOfParts", "TitlesOfParts", "raw"]
];
custregex = /<[^<>]+>[^<]*/g;
XLMLDocPropsMap = {
Title: "Title",
Subject: "Subject",
Author: "Author",
Keywords: "Keywords",
Comments: "Description",
LastAuthor: "LastAuthor",
RevNumber: "Revision",
Application: "AppName",
/* TotalTime: 'TotalTime', */
LastPrinted: "LastPrinted",
CreatedDate: "Created",
ModifiedDate: "LastSaved",
/* Pages */
/* Words */
/* Characters */
Category: "Category",
/* PresentationFormat */
Manager: "Manager",
Company: "Company",
/* Guid */
/* HyperlinkBase */
/* Bytes */
/* Lines */
/* Paragraphs */
/* CharactersWithSpaces */
AppVersion: "Version",
ContentStatus: "ContentStatus",
/* NOTE: missing from schema */
Identifier: "Identifier",
/* NOTE: missing from schema */
Language: "Language"
/* NOTE: missing from schema */
};
parse_Ref = parse_RefU;
FtTab = {
0: parse_FtSkip,
/* FtEnd */
4: parse_FtSkip,
/* FtMacro */
5: parse_FtSkip,
/* FtButton */
6: parse_FtSkip,
/* FtGmo */
7: parse_FtCf,
/* FtCf */
8: parse_FtSkip,
/* FtPioGrbit */
9: parse_FtSkip,
/* FtPictFmla */
10: parse_FtSkip,
/* FtCbls */
11: parse_FtSkip,
/* FtRbo */
12: parse_FtSkip,
/* FtSbs */
13: parse_FtNts,
/* FtNts */
14: parse_FtSkip,
/* FtSbsFmla */
15: parse_FtSkip,
/* FtGboData */
16: parse_FtSkip,
/* FtEdoData */
17: parse_FtSkip,
/* FtRboData */
18: parse_FtSkip,
/* FtCblsData */
19: parse_FtSkip,
/* FtLbsData */
20: parse_FtSkip,
/* FtCblsFmla */
21: parse_FtCmo
};
parse_BIFF2Format = parse_XLUnicodeString2;
parse_XLHeaderFooter = parse_OptXLUnicodeString;
parse_BIFF5OT = {
8: function(blob, length) {
var tgt = blob.l + length;
blob.l += 10;
var cf = blob.read_shift(2);
blob.l += 4;
blob.l += 2;
blob.l += 2;
blob.l += 2;
blob.l += 4;
var cchName = blob.read_shift(1);
blob.l += cchName;
blob.l = tgt;
return { fmt: cf };
}
};
parse_Blank = parse_XLSCell;
parse_Scl = parseuint16a;
parse_String = parse_XLUnicodeString;
DBF_SUPPORTED_VERSIONS = [2, 3, 48, 49, 131, 139, 140, 245];
DBF = /* @__PURE__ */ (function() {
var dbf_codepage_map = {
/* Code Pages Supported by Visual FoxPro */
1: 437,
2: 850,
3: 1252,
4: 1e4,
100: 852,
101: 866,
102: 865,
103: 861,
104: 895,
105: 620,
106: 737,
107: 857,
120: 950,
121: 949,
122: 936,
123: 932,
124: 874,
125: 1255,
126: 1256,
150: 10007,
151: 10029,
152: 10006,
200: 1250,
201: 1251,
202: 1254,
203: 1253,
/* shapefile DBF extension */
0: 20127,
8: 865,
9: 437,
10: 850,
11: 437,
13: 437,
14: 850,
15: 437,
16: 850,
17: 437,
18: 850,
19: 932,
20: 850,
21: 437,
22: 850,
23: 865,
24: 437,
25: 437,
26: 850,
27: 437,
28: 863,
29: 850,
31: 852,
34: 852,
35: 852,
36: 860,
37: 850,
38: 866,
55: 850,
64: 852,
77: 936,
78: 949,
79: 950,
80: 874,
87: 1252,
88: 1252,
89: 1252,
108: 863,
134: 737,
135: 852,
136: 857,
204: 1257,
255: 16969
};
var dbf_reverse_map = evert({
1: 437,
2: 850,
3: 1252,
4: 1e4,
100: 852,
101: 866,
102: 865,
103: 861,
104: 895,
105: 620,
106: 737,
107: 857,
120: 950,
121: 949,
122: 936,
123: 932,
124: 874,
125: 1255,
126: 1256,
150: 10007,
151: 10029,
152: 10006,
200: 1250,
201: 1251,
202: 1254,
203: 1253,
0: 20127
});
function dbf_to_aoa(buf, opts) {
var out = [];
var d4 = new_raw_buf(1);
switch (opts.type) {
case "base64":
d4 = s2a(Base64_decode(buf));
break;
case "binary":
d4 = s2a(buf);
break;
case "buffer":
case "array":
d4 = buf;
break;
}
prep_blob(d4, 0);
var ft = d4.read_shift(1);
var memo = !!(ft & 136);
var vfp = false, l7 = false;
switch (ft) {
case 2:
break;
// dBASE II
case 3:
break;
// dBASE III
case 48:
vfp = true;
memo = true;
break;
// VFP
case 49:
vfp = true;
memo = true;
break;
// VFP with autoincrement
// 0x43 dBASE IV SQL table files
// 0x63 dBASE IV SQL system files
case 131:
break;
// dBASE III with memo
case 139:
break;
// dBASE IV with memo
case 140:
l7 = true;
break;
// dBASE Level 7 with memo
// case 0xCB dBASE IV SQL table files with memo
case 245:
break;
// FoxPro 2.x with memo
// case 0xFB FoxBASE
default:
throw new Error("DBF Unsupported Version: " + ft.toString(16));
}
var nrow = 0, fpos = 521;
if (ft == 2) nrow = d4.read_shift(2);
d4.l += 3;
if (ft != 2) nrow = d4.read_shift(4);
if (nrow > 1048576) nrow = 1e6;
if (ft != 2) fpos = d4.read_shift(2);
var rlen = d4.read_shift(2);
var current_cp = opts.codepage || 1252;
if (ft != 2) {
d4.l += 16;
d4.read_shift(1);
if (d4[d4.l] !== 0) current_cp = dbf_codepage_map[d4[d4.l]];
d4.l += 1;
d4.l += 2;
}
if (l7) d4.l += 36;
var fields = [], field = {};
var hend = Math.min(d4.length, ft == 2 ? 521 : fpos - 10 - (vfp ? 264 : 0));
var ww = l7 ? 32 : 11;
while (d4.l < hend && d4[d4.l] != 13) {
field = {};
field.name = (typeof $cptable !== "undefined" ? $cptable.utils.decode(current_cp, d4.slice(d4.l, d4.l + ww)) : a2s(d4.slice(d4.l, d4.l + ww))).replace(/[\u0000\r\n][\S\s]*$/g, "");
d4.l += ww;
field.type = String.fromCharCode(d4.read_shift(1));
if (ft != 2 && !l7) field.offset = d4.read_shift(4);
field.len = d4.read_shift(1);
if (ft == 2) field.offset = d4.read_shift(2);
field.dec = d4.read_shift(1);
if (field.name.length) fields.push(field);
if (ft != 2) d4.l += l7 ? 13 : 14;
switch (field.type) {
case "B":
if ((!vfp || field.len != 8) && opts.WTF) console.log("Skipping " + field.name + ":" + field.type);
break;
case "G":
// General (FoxPro and dBASE L7)
case "P":
if (opts.WTF) console.log("Skipping " + field.name + ":" + field.type);
break;
case "+":
// Autoincrement (dBASE L7 only)
case "0":
// _NullFlags (VFP only)
case "@":
// Timestamp (dBASE L7 only)
case "C":
// Character (dBASE II)
case "D":
// Date (dBASE III)
case "F":
// Float (dBASE IV)
case "I":
// Long (VFP and dBASE L7)
case "L":
// Logical (dBASE II)
case "M":
// Memo (dBASE III)
case "N":
// Number (dBASE II)
case "O":
// Double (dBASE L7 only)
case "T":
// Datetime (VFP only)
case "Y":
break;
default:
throw new Error("Unknown Field Type: " + field.type);
}
}
if (d4[d4.l] !== 13) d4.l = fpos - 1;
if (d4.read_shift(1) !== 13) throw new Error("DBF Terminator not found " + d4.l + " " + d4[d4.l]);
d4.l = fpos;
var R3 = 0, C3 = 0;
out[0] = [];
for (C3 = 0; C3 != fields.length; ++C3) out[0][C3] = fields[C3].name;
while (nrow-- > 0) {
if (d4[d4.l] === 42) {
d4.l += rlen;
continue;
}
++d4.l;
out[++R3] = [];
C3 = 0;
for (C3 = 0; C3 != fields.length; ++C3) {
var dd = d4.slice(d4.l, d4.l + fields[C3].len);
d4.l += fields[C3].len;
prep_blob(dd, 0);
var s6 = typeof $cptable !== "undefined" ? $cptable.utils.decode(current_cp, dd) : a2s(dd);
switch (fields[C3].type) {
case "C":
if (s6.trim().length) out[R3][C3] = s6.replace(/([^\s])\s+$/, "$1");
break;
case "D":
if (s6.length === 8) {
out[R3][C3] = new Date(Date.UTC(+s6.slice(0, 4), +s6.slice(4, 6) - 1, +s6.slice(6, 8), 0, 0, 0, 0));
if (!(opts && opts.UTC)) {
out[R3][C3] = utc_to_local(out[R3][C3]);
}
} else out[R3][C3] = s6;
break;
case "F":
out[R3][C3] = parseFloat(s6.trim());
break;
case "+":
case "I":
out[R3][C3] = l7 ? dd.read_shift(-4, "i") ^ 2147483648 : dd.read_shift(4, "i");
break;
case "L":
switch (s6.trim().toUpperCase()) {
case "Y":
case "T":
out[R3][C3] = true;
break;
case "N":
case "F":
out[R3][C3] = false;
break;
case "":
case "\0":
case "?":
break;
default:
throw new Error("DBF Unrecognized L:|" + s6 + "|");
}
break;
case "M":
if (!memo) throw new Error("DBF Unexpected MEMO for type " + ft.toString(16));
out[R3][C3] = "##MEMO##" + (l7 ? parseInt(s6.trim(), 10) : dd.read_shift(4));
break;
case "N":
s6 = s6.replace(/\u0000/g, "").trim();
if (s6 && s6 != ".") out[R3][C3] = +s6 || 0;
break;
case "@":
out[R3][C3] = new Date(dd.read_shift(-8, "f") - 621356832e5);
break;
case "T":
{
var hi = dd.read_shift(4), lo = dd.read_shift(4);
if (hi == 0 && lo == 0) break;
out[R3][C3] = new Date((hi - 2440588) * 864e5 + lo);
if (!(opts && opts.UTC)) out[R3][C3] = utc_to_local(out[R3][C3]);
}
break;
case "Y":
out[R3][C3] = dd.read_shift(4, "i") / 1e4 + dd.read_shift(4, "i") / 1e4 * Math.pow(2, 32);
break;
case "O":
out[R3][C3] = -dd.read_shift(-8, "f");
break;
case "B":
if (vfp && fields[C3].len == 8) {
out[R3][C3] = dd.read_shift(8, "f");
break;
}
/* falls through */
case "G":
case "P":
dd.l += fields[C3].len;
break;
case "0":
if (fields[C3].name === "_NullFlags") break;
/* falls through */
default:
throw new Error("DBF Unsupported data type " + fields[C3].type);
}
}
}
if (ft != 2) {
if (d4.l < d4.length && d4[d4.l++] != 26) throw new Error("DBF EOF Marker missing " + (d4.l - 1) + " of " + d4.length + " " + d4[d4.l - 1].toString(16));
}
if (opts && opts.sheetRows) out = out.slice(0, opts.sheetRows);
opts.DBF = fields;
return out;
}
function dbf_to_sheet(buf, opts) {
var o9 = opts || {};
if (!o9.dateNF) o9.dateNF = "yyyymmdd";
var ws = aoa_to_sheet(dbf_to_aoa(buf, o9), o9);
ws["!cols"] = o9.DBF.map(function(field) {
return {
wch: field.len,
DBF: field
};
});
delete o9.DBF;
return ws;
}
function dbf_to_workbook(buf, opts) {
try {
var o9 = sheet_to_workbook(dbf_to_sheet(buf, opts), opts);
o9.bookType = "dbf";
return o9;
} catch (e9) {
if (opts && opts.WTF) throw e9;
}
return { SheetNames: [], Sheets: {} };
}
var _RLEN = { "B": 8, "C": 250, "L": 1, "D": 8, "?": 0, "": 0 };
function sheet_to_dbf(ws, opts) {
if (!ws["!ref"]) throw new Error("Cannot export empty sheet to DBF");
var o9 = opts || {};
var old_cp = current_codepage;
if (+o9.codepage >= 0) set_cp(+o9.codepage);
if (o9.type == "string") throw new Error("Cannot write DBF to JS string");
var ba = buf_array();
var aoa = sheet_to_json(ws, { header: 1, raw: true, cellDates: true });
var headers = aoa[0], data = aoa.slice(1), cols = ws["!cols"] || [];
var i7 = 0, j3 = 0, hcnt = 0, rlen = 1;
for (i7 = 0; i7 < headers.length; ++i7) {
if (((cols[i7] || {}).DBF || {}).name) {
headers[i7] = cols[i7].DBF.name;
++hcnt;
continue;
}
if (headers[i7] == null) continue;
++hcnt;
if (typeof headers[i7] === "number") headers[i7] = headers[i7].toString(10);
if (typeof headers[i7] !== "string") throw new Error("DBF Invalid column name " + headers[i7] + " |" + typeof headers[i7] + "|");
if (headers.indexOf(headers[i7]) !== i7) {
for (j3 = 0; j3 < 1024; ++j3)
if (headers.indexOf(headers[i7] + "_" + j3) == -1) {
headers[i7] += "_" + j3;
break;
}
}
}
var range2 = safe_decode_range(ws["!ref"]);
var coltypes = [];
var colwidths = [];
var coldecimals = [];
for (i7 = 0; i7 <= range2.e.c - range2.s.c; ++i7) {
var guess = "", _guess = "", maxlen = 0;
var col = [];
for (j3 = 0; j3 < data.length; ++j3) {
if (data[j3][i7] != null) col.push(data[j3][i7]);
}
if (col.length == 0 || headers[i7] == null) {
coltypes[i7] = "?";
continue;
}
for (j3 = 0; j3 < col.length; ++j3) {
switch (typeof col[j3]) {
/* TODO: check if L2 compat is desired */
case "number":
_guess = "B";
break;
case "string":
_guess = "C";
break;
case "boolean":
_guess = "L";
break;
case "object":
_guess = col[j3] instanceof Date ? "D" : "C";
break;
default:
_guess = "C";
}
maxlen = Math.max(maxlen, (typeof $cptable !== "undefined" && typeof col[j3] == "string" ? $cptable.utils.encode(current_ansi, col[j3]) : String(col[j3])).length);
guess = guess && guess != _guess ? "C" : _guess;
}
if (maxlen > 250) maxlen = 250;
_guess = ((cols[i7] || {}).DBF || {}).type;
if (_guess == "C") {
if (cols[i7].DBF.len > maxlen) maxlen = cols[i7].DBF.len;
}
if (guess == "B" && _guess == "N") {
guess = "N";
coldecimals[i7] = cols[i7].DBF.dec;
maxlen = cols[i7].DBF.len;
}
colwidths[i7] = guess == "C" || _guess == "N" ? maxlen : _RLEN[guess] || 0;
rlen += colwidths[i7];
coltypes[i7] = guess;
}
var h7 = ba.next(32);
h7.write_shift(4, 318902576);
h7.write_shift(4, data.length);
h7.write_shift(2, 296 + 32 * hcnt);
h7.write_shift(2, rlen);
for (i7 = 0; i7 < 4; ++i7) h7.write_shift(4, 0);
var cp = +dbf_reverse_map[
/*::String(*/
current_codepage
/*::)*/
] || 3;
h7.write_shift(4, 0 | cp << 8);
if (dbf_codepage_map[cp] != +o9.codepage) {
if (o9.codepage) console.error("DBF Unsupported codepage " + current_codepage + ", using 1252");
current_codepage = 1252;
}
for (i7 = 0, j3 = 0; i7 < headers.length; ++i7) {
if (headers[i7] == null) continue;
var hf = ba.next(32);
var _f = (headers[i7].slice(-10) + "\0\0\0\0\0\0\0\0\0\0\0").slice(0, 11);
hf.write_shift(1, _f, "sbcs");
hf.write_shift(1, coltypes[i7] == "?" ? "C" : coltypes[i7], "sbcs");
hf.write_shift(4, j3);
hf.write_shift(1, colwidths[i7] || _RLEN[coltypes[i7]] || 0);
hf.write_shift(1, coldecimals[i7] || 0);
hf.write_shift(1, 2);
hf.write_shift(4, 0);
hf.write_shift(1, 0);
hf.write_shift(4, 0);
hf.write_shift(4, 0);
j3 += colwidths[i7] || _RLEN[coltypes[i7]] || 0;
}
var hb = ba.next(264);
hb.write_shift(4, 13);
for (i7 = 0; i7 < 65; ++i7) hb.write_shift(4, 0);
for (i7 = 0; i7 < data.length; ++i7) {
var rout = ba.next(rlen);
rout.write_shift(1, 0);
for (j3 = 0; j3 < headers.length; ++j3) {
if (headers[j3] == null) continue;
switch (coltypes[j3]) {
case "L":
rout.write_shift(1, data[i7][j3] == null ? 63 : data[i7][j3] ? 84 : 70);
break;
case "B":
rout.write_shift(8, data[i7][j3] || 0, "f");
break;
case "N":
var _n = "0";
if (typeof data[i7][j3] == "number") _n = data[i7][j3].toFixed(coldecimals[j3] || 0);
if (_n.length > colwidths[j3]) _n = _n.slice(0, colwidths[j3]);
for (hcnt = 0; hcnt < colwidths[j3] - _n.length; ++hcnt) rout.write_shift(1, 32);
rout.write_shift(1, _n, "sbcs");
break;
case "D":
if (!data[i7][j3]) rout.write_shift(8, "00000000", "sbcs");
else {
rout.write_shift(4, ("0000" + data[i7][j3].getFullYear()).slice(-4), "sbcs");
rout.write_shift(2, ("00" + (data[i7][j3].getMonth() + 1)).slice(-2), "sbcs");
rout.write_shift(2, ("00" + data[i7][j3].getDate()).slice(-2), "sbcs");
}
break;
case "C":
var _l = rout.l;
var _s = String(data[i7][j3] != null ? data[i7][j3] : "").slice(0, colwidths[j3]);
rout.write_shift(1, _s, "cpstr");
_l += colwidths[j3] - rout.l;
for (hcnt = 0; hcnt < _l; ++hcnt) rout.write_shift(1, 32);
break;
}
}
}
current_codepage = old_cp;
ba.next(1).write_shift(1, 26);
return ba.end();
}
return {
to_workbook: dbf_to_workbook,
to_sheet: dbf_to_sheet,
from_sheet: sheet_to_dbf
};
})();
SYLK = /* @__PURE__ */ (function() {
var sylk_escapes = {
AA: "\xC0",
BA: "\xC1",
CA: "\xC2",
DA: 195,
HA: "\xC4",
JA: 197,
AE: "\xC8",
BE: "\xC9",
CE: "\xCA",
HE: "\xCB",
AI: "\xCC",
BI: "\xCD",
CI: "\xCE",
HI: "\xCF",
AO: "\xD2",
BO: "\xD3",
CO: "\xD4",
DO: 213,
HO: "\xD6",
AU: "\xD9",
BU: "\xDA",
CU: "\xDB",
HU: "\xDC",
Aa: "\xE0",
Ba: "\xE1",
Ca: "\xE2",
Da: 227,
Ha: "\xE4",
Ja: 229,
Ae: "\xE8",
Be: "\xE9",
Ce: "\xEA",
He: "\xEB",
Ai: "\xEC",
Bi: "\xED",
Ci: "\xEE",
Hi: "\xEF",
Ao: "\xF2",
Bo: "\xF3",
Co: "\xF4",
Do: 245,
Ho: "\xF6",
Au: "\xF9",
Bu: "\xFA",
Cu: "\xFB",
Hu: "\xFC",
KC: "\xC7",
Kc: "\xE7",
q: "\xE6",
z: "\u0153",
a: "\xC6",
j: "\u0152",
DN: 209,
Dn: 241,
Hy: 255,
S: 169,
c: 170,
R: 174,
"B ": 180,
0: 176,
1: 177,
2: 178,
3: 179,
5: 181,
6: 182,
7: 183,
Q: 185,
k: 186,
b: 208,
i: 216,
l: 222,
s: 240,
y: 248,
"!": 161,
'"': 162,
"#": 163,
"(": 164,
"%": 165,
"'": 167,
"H ": 168,
"+": 171,
";": 187,
"<": 188,
"=": 189,
">": 190,
"?": 191,
"{": 223
};
var sylk_char_regex = new RegExp("\x1BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g, "\\$1").replace("{", "\\{") + "|\\|)", "gm");
try {
sylk_char_regex = new RegExp("\x1BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g, "\\$1") + "|\\|)", "gm");
} catch (e9) {
}
var sylk_char_fn = function(_3, $1) {
var o9 = sylk_escapes[$1];
return typeof o9 == "number" ? _getansi(o9) : o9;
};
var decode_sylk_char = function($$, $1, $22) {
var newcc = $1.charCodeAt(0) - 32 << 4 | $22.charCodeAt(0) - 48;
return newcc == 59 ? $$ : _getansi(newcc);
};
sylk_escapes["|"] = 254;
var encode_sylk_str = function($$) {
return $$.replace(/\n/g, "\x1B :").replace(/\r/g, "\x1B =");
};
function sylk_to_aoa(d4, opts) {
switch (opts.type) {
case "base64":
return sylk_to_aoa_str(Base64_decode(d4), opts);
case "binary":
return sylk_to_aoa_str(d4, opts);
case "buffer":
return sylk_to_aoa_str(has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4), opts);
case "array":
return sylk_to_aoa_str(cc2str(d4), opts);
}
throw new Error("Unrecognized type " + opts.type);
}
function sylk_to_aoa_str(str2, opts) {
var records = str2.split(/[\n\r]+/), R3 = -1, C3 = -1, ri = 0, rj = 0, arr = [];
var formats = [];
var next_cell_format = null;
var sht = {}, rowinfo = [], colinfo = [], cw = [];
var Mval = 0, j3;
var wb = { Workbook: { WBProps: {}, Names: [] } };
if (+opts.codepage >= 0) set_cp(+opts.codepage);
for (; ri !== records.length; ++ri) {
Mval = 0;
var rstr = records[ri].trim().replace(/\x1B([\x20-\x2F])([\x30-\x3F])/g, decode_sylk_char).replace(sylk_char_regex, sylk_char_fn);
var record = rstr.replace(/;;/g, "\0").split(";").map(function(x2) {
return x2.replace(/\u0000/g, ";");
});
var RT = record[0], val2;
if (rstr.length > 0) switch (RT) {
case "ID":
break;
/* header */
case "E":
break;
/* EOF */
case "B":
break;
/* dimensions */
case "O":
for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) {
case "V":
{
var d1904 = parseInt(record[rj].slice(1), 10);
if (d1904 >= 1 && d1904 <= 4) wb.Workbook.WBProps.date1904 = true;
}
break;
}
break;
case "W":
break;
/* window */
case "P":
switch (record[1].charAt(0)) {
case "P":
formats.push(rstr.slice(3).replace(/;;/g, ";"));
break;
}
break;
case "NN":
{
var nn = { Sheet: 0 };
for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) {
case "N":
nn.Name = record[rj].slice(1);
break;
case "E":
nn.Ref = (opts && opts.sheet || "Sheet1") + "!" + rc_to_a1(record[rj].slice(1));
break;
}
wb.Workbook.Names.push(nn);
}
break;
// case 'NE': // ??
// case 'NU': // ??
case "C":
var C_seen_K = false, C_seen_X = false, C_seen_S = false, C_seen_E = false, _R = -1, _C = -1, formula = "", cell_t = "z";
var cmnt = "";
for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) {
case "A":
cmnt = record[rj].slice(1);
break;
// TODO: comment
case "X":
C3 = parseInt(record[rj].slice(1), 10) - 1;
C_seen_X = true;
break;
case "Y":
R3 = parseInt(record[rj].slice(1), 10) - 1;
if (!C_seen_X) C3 = 0;
for (j3 = arr.length; j3 <= R3; ++j3) arr[j3] = [];
break;
case "K":
val2 = record[rj].slice(1);
if (val2.charAt(0) === '"') {
val2 = val2.slice(1, val2.length - 1);
cell_t = "s";
} else if (val2 === "TRUE" || val2 === "FALSE") {
val2 = val2 === "TRUE";
cell_t = "b";
} else if (val2.charAt(0) == "#" && RBErr[val2] != null) {
cell_t = "e";
val2 = RBErr[val2];
} else if (!isNaN(fuzzynum(val2))) {
val2 = fuzzynum(val2);
cell_t = "n";
if (next_cell_format !== null && fmt_is_date(next_cell_format) && opts.cellDates) {
val2 = numdate(wb.Workbook.WBProps.date1904 ? val2 + 1462 : val2);
cell_t = typeof val2 == "number" ? "n" : "d";
}
}
if (typeof $cptable !== "undefined" && typeof val2 == "string" && (opts || {}).type != "string" && (opts || {}).codepage) val2 = $cptable.utils.decode(opts.codepage, val2);
C_seen_K = true;
break;
case "E":
C_seen_E = true;
formula = rc_to_a1(record[rj].slice(1), { r: R3, c: C3 });
break;
case "S":
C_seen_S = true;
break;
case "G":
break;
// unknown
case "R":
_R = parseInt(record[rj].slice(1), 10) - 1;
break;
case "C":
_C = parseInt(record[rj].slice(1), 10) - 1;
break;
// case 'P': // ??
// case 'D': // ??
default:
if (opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
}
if (C_seen_K) {
if (!arr[R3][C3]) arr[R3][C3] = { t: cell_t, v: val2 };
else {
arr[R3][C3].t = cell_t;
arr[R3][C3].v = val2;
}
if (next_cell_format) arr[R3][C3].z = next_cell_format;
if (opts.cellText !== false && next_cell_format) arr[R3][C3].w = SSF_format(arr[R3][C3].z, arr[R3][C3].v, { date1904: wb.Workbook.WBProps.date1904 });
next_cell_format = null;
}
if (C_seen_S) {
if (C_seen_E) throw new Error("SYLK shared formula cannot have own formula");
var shrbase = _R > -1 && arr[_R][_C];
if (!shrbase || !shrbase[1]) throw new Error("SYLK shared formula cannot find base");
formula = shift_formula_str(shrbase[1], { r: R3 - _R, c: C3 - _C });
}
if (formula) {
if (!arr[R3][C3]) arr[R3][C3] = { t: "n", f: formula };
else arr[R3][C3].f = formula;
}
if (cmnt) {
if (!arr[R3][C3]) arr[R3][C3] = { t: "z" };
arr[R3][C3].c = [{ a: "SheetJSYLK", t: cmnt }];
}
break;
case "F":
var F_seen = 0;
for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) {
case "X":
C3 = parseInt(record[rj].slice(1), 10) - 1;
++F_seen;
break;
case "Y":
R3 = parseInt(record[rj].slice(1), 10) - 1;
for (j3 = arr.length; j3 <= R3; ++j3) arr[j3] = [];
break;
case "M":
Mval = parseInt(record[rj].slice(1), 10) / 20;
break;
case "F":
break;
/* ??? */
case "G":
break;
/* hide grid */
case "P":
next_cell_format = formats[parseInt(record[rj].slice(1), 10)];
break;
case "S":
break;
/* cell style */
case "D":
break;
/* column */
case "N":
break;
/* font */
case "W":
cw = record[rj].slice(1).split(" ");
for (j3 = parseInt(cw[0], 10); j3 <= parseInt(cw[1], 10); ++j3) {
Mval = parseInt(cw[2], 10);
colinfo[j3 - 1] = Mval === 0 ? { hidden: true } : { wch: Mval };
}
break;
case "C":
C3 = parseInt(record[rj].slice(1), 10) - 1;
if (!colinfo[C3]) colinfo[C3] = {};
break;
case "R":
R3 = parseInt(record[rj].slice(1), 10) - 1;
if (!rowinfo[R3]) rowinfo[R3] = {};
if (Mval > 0) {
rowinfo[R3].hpt = Mval;
rowinfo[R3].hpx = pt2px(Mval);
} else if (Mval === 0) rowinfo[R3].hidden = true;
break;
// case 'K': // ??
// case 'E': // ??
default:
if (opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
}
if (F_seen < 1) next_cell_format = null;
break;
default:
if (opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
}
}
if (rowinfo.length > 0) sht["!rows"] = rowinfo;
if (colinfo.length > 0) sht["!cols"] = colinfo;
colinfo.forEach(function(col) {
process_col(col);
});
if (opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
return [arr, sht, wb];
}
function sylk_to_workbook(d4, opts) {
var aoasht = sylk_to_aoa(d4, opts);
var aoa = aoasht[0], ws = aoasht[1], wb = aoasht[2];
var _opts = dup(opts);
_opts.date1904 = (((wb || {}).Workbook || {}).WBProps || {}).date1904;
var o9 = aoa_to_sheet(aoa, _opts);
keys(ws).forEach(function(k2) {
o9[k2] = ws[k2];
});
var outwb = sheet_to_workbook(o9, opts);
keys(wb).forEach(function(k2) {
outwb[k2] = wb[k2];
});
outwb.bookType = "sylk";
return outwb;
}
function write_ws_cell_sylk(cell, ws, R3, C3, opts, date1904) {
var o9 = "C;Y" + (R3 + 1) + ";X" + (C3 + 1) + ";K";
switch (cell.t) {
case "n":
o9 += isFinite(cell.v) ? cell.v || 0 : BErr[isNaN(cell.v) ? 36 : 7];
if (cell.f && !cell.F) o9 += ";E" + a1_to_rc(cell.f, { r: R3, c: C3 });
break;
case "b":
o9 += cell.v ? "TRUE" : "FALSE";
break;
case "e":
o9 += cell.w || BErr[cell.v] || cell.v;
break;
case "d":
o9 += datenum(parseDate(cell.v, date1904), date1904);
break;
case "s":
o9 += '"' + (cell.v == null ? "" : String(cell.v)).replace(/"/g, "").replace(/;/g, ";;") + '"';
break;
}
return o9;
}
function write_ws_cmnt_sylk(cmnt, R3, C3) {
var o9 = "C;Y" + (R3 + 1) + ";X" + (C3 + 1) + ";A";
o9 += encode_sylk_str(cmnt.map(function(c6) {
return c6.t;
}).join(""));
return o9;
}
function write_ws_cols_sylk(out, cols) {
cols.forEach(function(col, i7) {
var rec = "F;W" + (i7 + 1) + " " + (i7 + 1) + " ";
if (col.hidden) rec += "0";
else {
if (typeof col.width == "number" && !col.wpx) col.wpx = width2px(col.width);
if (typeof col.wpx == "number" && !col.wch) col.wch = px2char(col.wpx);
if (typeof col.wch == "number") rec += Math.round(col.wch);
}
if (rec.charAt(rec.length - 1) != " ") out.push(rec);
});
}
function write_ws_rows_sylk(out, rows) {
rows.forEach(function(row, i7) {
var rec = "F;";
if (row.hidden) rec += "M0;";
else if (row.hpt) rec += "M" + 20 * row.hpt + ";";
else if (row.hpx) rec += "M" + 20 * px2pt(row.hpx) + ";";
if (rec.length > 2) out.push(rec + "R" + (i7 + 1));
});
}
function sheet_to_sylk(ws, opts, wb) {
if (!opts) opts = {};
opts._formats = ["General"];
var preamble = ["ID;PSheetJS;N;E"], o9 = [];
var r8 = safe_decode_range(ws["!ref"] || "A1"), cell;
var dense = ws["!data"] != null;
var RS = "\r\n";
var d1904 = (((wb || {}).Workbook || {}).WBProps || {}).date1904;
var _lastfmt = "General";
preamble.push("P;PGeneral");
var R3 = r8.s.r, C3 = r8.s.c, p4 = [];
if (ws["!ref"]) for (R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
if (dense && !ws["!data"][R3]) continue;
p4 = [];
for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
cell = dense ? ws["!data"][R3][C3] : ws[encode_col(C3) + encode_row(R3)];
if (!cell || !cell.c) continue;
p4.push(write_ws_cmnt_sylk(cell.c, R3, C3));
}
if (p4.length) o9.push(p4.join(RS));
}
if (ws["!ref"]) for (R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
if (dense && !ws["!data"][R3]) continue;
p4 = [];
for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
cell = dense ? ws["!data"][R3][C3] : ws[encode_col(C3) + encode_row(R3)];
if (!cell || cell.v == null && (!cell.f || cell.F)) continue;
if ((cell.z || (cell.t == "d" ? table_fmt[14] : "General")) != _lastfmt) {
var ifmt = opts._formats.indexOf(cell.z);
if (ifmt == -1) {
opts._formats.push(cell.z);
ifmt = opts._formats.length - 1;
preamble.push("P;P" + cell.z.replace(/;/g, ";;"));
}
p4.push("F;P" + ifmt + ";Y" + (R3 + 1) + ";X" + (C3 + 1));
}
p4.push(write_ws_cell_sylk(cell, ws, R3, C3, opts, d1904));
}
o9.push(p4.join(RS));
}
preamble.push("F;P0;DG0G8;M255");
if (ws["!cols"]) write_ws_cols_sylk(preamble, ws["!cols"]);
if (ws["!rows"]) write_ws_rows_sylk(preamble, ws["!rows"]);
if (ws["!ref"]) preamble.push("B;Y" + (r8.e.r - r8.s.r + 1) + ";X" + (r8.e.c - r8.s.c + 1) + ";D" + [r8.s.c, r8.s.r, r8.e.c, r8.e.r].join(" "));
preamble.push("O;L;D;B" + (d1904 ? ";V4" : "") + ";K47;G100 0.001");
delete opts._formats;
return preamble.join(RS) + RS + o9.join(RS) + RS + "E" + RS;
}
return {
to_workbook: sylk_to_workbook,
from_sheet: sheet_to_sylk
};
})();
DIF = /* @__PURE__ */ (function() {
function dif_to_aoa(d4, opts) {
switch (opts.type) {
case "base64":
return dif_to_aoa_str(Base64_decode(d4), opts);
case "binary":
return dif_to_aoa_str(d4, opts);
case "buffer":
return dif_to_aoa_str(has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4), opts);
case "array":
return dif_to_aoa_str(cc2str(d4), opts);
}
throw new Error("Unrecognized type " + opts.type);
}
function dif_to_aoa_str(str2, opts) {
var records = str2.split("\n"), R3 = -1, C3 = -1, ri = 0, arr = [];
for (; ri !== records.length; ++ri) {
if (records[ri].trim() === "BOT") {
arr[++R3] = [];
C3 = 0;
continue;
}
if (R3 < 0) continue;
var metadata = records[ri].trim().split(",");
var type = metadata[0], value = metadata[1];
++ri;
var data = records[ri] || "";
while ((data.match(/["]/g) || []).length & 1 && ri < records.length - 1) data += "\n" + records[++ri];
data = data.trim();
switch (+type) {
case -1:
if (data === "BOT") {
arr[++R3] = [];
C3 = 0;
continue;
} else if (data !== "EOD") throw new Error("Unrecognized DIF special command " + data);
break;
case 0:
if (data === "TRUE") arr[R3][C3] = true;
else if (data === "FALSE") arr[R3][C3] = false;
else if (!isNaN(fuzzynum(value))) arr[R3][C3] = fuzzynum(value);
else if (!isNaN(fuzzydate(value).getDate())) {
arr[R3][C3] = parseDate(value);
if (!(opts && opts.UTC)) {
arr[R3][C3] = utc_to_local(arr[R3][C3]);
}
} else arr[R3][C3] = value;
++C3;
break;
case 1:
data = data.slice(1, data.length - 1);
data = data.replace(/""/g, '"');
if (DIF_XL && data && data.match(/^=".*"$/)) data = data.slice(2, -1);
arr[R3][C3++] = data !== "" ? data : null;
break;
}
if (data === "EOD") break;
}
if (opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
return arr;
}
function dif_to_sheet(str2, opts) {
return aoa_to_sheet(dif_to_aoa(str2, opts), opts);
}
function dif_to_workbook(str2, opts) {
var o9 = sheet_to_workbook(dif_to_sheet(str2, opts), opts);
o9.bookType = "dif";
return o9;
}
function make_value(v4, s6) {
return "0," + String(v4) + "\r\n" + s6;
}
function make_value_str(s6) {
return '1,0\r\n"' + s6.replace(/"/g, '""') + '"';
}
function sheet_to_dif(ws) {
var _DIF_XL = DIF_XL;
if (!ws["!ref"]) throw new Error("Cannot export empty sheet to DIF");
var r8 = safe_decode_range(ws["!ref"]);
var dense = ws["!data"] != null;
var o9 = [
'TABLE\r\n0,1\r\n"sheetjs"\r\n',
"VECTORS\r\n0," + (r8.e.r - r8.s.r + 1) + '\r\n""\r\n',
"TUPLES\r\n0," + (r8.e.c - r8.s.c + 1) + '\r\n""\r\n',
'DATA\r\n0,0\r\n""\r\n'
];
for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
var row = dense ? ws["!data"][R3] : [];
var p4 = "-1,0\r\nBOT\r\n";
for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
var cell = dense ? row && row[C3] : ws[encode_cell({ r: R3, c: C3 })];
if (cell == null) {
p4 += '1,0\r\n""\r\n';
continue;
}
switch (cell.t) {
case "n":
if (_DIF_XL) {
if (cell.w != null) p4 += "0," + cell.w + "\r\nV";
else if (cell.v != null) p4 += make_value(cell.v, "V");
else if (cell.f != null && !cell.F) p4 += make_value_str("=" + cell.f);
else p4 += '1,0\r\n""';
} else {
if (cell.v == null) p4 += '1,0\r\n""';
else p4 += make_value(cell.v, "V");
}
break;
case "b":
p4 += cell.v ? make_value(1, "TRUE") : make_value(0, "FALSE");
break;
case "s":
p4 += make_value_str(!_DIF_XL || isNaN(+cell.v) ? cell.v : '="' + cell.v + '"');
break;
case "d":
if (!cell.w) cell.w = SSF_format(cell.z || table_fmt[14], datenum(parseDate(cell.v)));
if (_DIF_XL) p4 += make_value(cell.w, "V");
else p4 += make_value_str(cell.w);
break;
default:
p4 += '1,0\r\n""';
}
p4 += "\r\n";
}
o9.push(p4);
}
return o9.join("") + "-1,0\r\nEOD";
}
return {
to_workbook: dif_to_workbook,
to_sheet: dif_to_sheet,
from_sheet: sheet_to_dif
};
})();
ETH = /* @__PURE__ */ (function() {
function decode5(s6) {
return s6.replace(/\\b/g, "\\").replace(/\\c/g, ":").replace(/\\n/g, "\n");
}
function encode2(s6) {
return s6.replace(/\\/g, "\\b").replace(/:/g, "\\c").replace(/\n/g, "\\n");
}
function eth_to_aoa(str2, opts) {
var records = str2.split("\n"), R3 = -1, C3 = -1, ri = 0, arr = [];
for (; ri !== records.length; ++ri) {
var record = records[ri].trim().split(":");
if (record[0] !== "cell") continue;
var addr = decode_cell(record[1]);
if (arr.length <= addr.r) {
for (R3 = arr.length; R3 <= addr.r; ++R3) if (!arr[R3]) arr[R3] = [];
}
R3 = addr.r;
C3 = addr.c;
switch (record[2]) {
case "t":
arr[R3][C3] = decode5(record[3]);
break;
case "v":
arr[R3][C3] = +record[3];
break;
case "vtf":
var _f = record[record.length - 1];
/* falls through */
case "vtc":
switch (record[3]) {
case "nl":
arr[R3][C3] = +record[4] ? true : false;
break;
default:
arr[R3][C3] = record[record.length - 1].charAt(0) == "#" ? { t: "e", v: RBErr[record[record.length - 1]] } : +record[4];
break;
}
if (record[2] == "vtf") arr[R3][C3] = [arr[R3][C3], _f];
}
}
if (opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
return arr;
}
function eth_to_sheet(d4, opts) {
return aoa_to_sheet(eth_to_aoa(d4, opts), opts);
}
function eth_to_workbook(d4, opts) {
return sheet_to_workbook(eth_to_sheet(d4, opts), opts);
}
var header = [
"socialcalc:version:1.5",
"MIME-Version: 1.0",
"Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave"
].join("\n");
var sep2 = [
"--SocialCalcSpreadsheetControlSave",
"Content-type: text/plain; charset=UTF-8"
].join("\n") + "\n";
var meta = [
"# SocialCalc Spreadsheet Control Save",
"part:sheet"
].join("\n");
var end = "--SocialCalcSpreadsheetControlSave--";
function sheet_to_eth_data(ws) {
if (!ws || !ws["!ref"]) return "";
var o9 = [], oo = [], cell, coord = "";
var r8 = decode_range(ws["!ref"]);
var dense = ws["!data"] != null;
for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
coord = encode_cell({ r: R3, c: C3 });
cell = dense ? (ws["!data"][R3] || [])[C3] : ws[coord];
if (!cell || cell.v == null || cell.t === "z") continue;
oo = ["cell", coord, "t"];
switch (cell.t) {
case "s":
oo.push(encode2(cell.v));
break;
case "b":
oo[2] = "vt" + (cell.f ? "f" : "c");
oo[3] = "nl";
oo[4] = cell.v ? "1" : "0";
oo[5] = encode2(cell.f || (cell.v ? "TRUE" : "FALSE"));
break;
case "d":
var t6 = datenum(parseDate(cell.v));
oo[2] = "vtc";
oo[3] = "nd";
oo[4] = "" + t6;
oo[5] = cell.w || SSF_format(cell.z || table_fmt[14], t6);
break;
case "n":
if (isFinite(cell.v)) {
if (!cell.f) {
oo[2] = "v";
oo[3] = cell.v;
} else {
oo[2] = "vtf";
oo[3] = "n";
oo[4] = cell.v;
oo[5] = encode2(cell.f);
}
} else {
oo[2] = "vt" + (cell.f ? "f" : "c");
oo[3] = "e" + BErr[isNaN(cell.v) ? 36 : 7];
oo[4] = "0";
oo[5] = cell.f || oo[3].slice(1);
oo[6] = "e";
oo[7] = oo[3].slice(1);
}
break;
case "e":
continue;
}
o9.push(oo.join(":"));
}
}
o9.push("sheet:c:" + (r8.e.c - r8.s.c + 1) + ":r:" + (r8.e.r - r8.s.r + 1) + ":tvf:1");
o9.push("valueformat:1:text-wiki");
return o9.join("\n");
}
function sheet_to_eth(ws) {
return [header, sep2, meta, sep2, sheet_to_eth_data(ws), end].join("\n");
}
return {
to_workbook: eth_to_workbook,
to_sheet: eth_to_sheet,
from_sheet: sheet_to_eth
};
})();
PRN = /* @__PURE__ */ (function() {
function set_text_arr(data, arr, R3, C3, o9) {
if (o9.raw) arr[R3][C3] = data;
else if (data === "") {
} else if (data === "TRUE") arr[R3][C3] = true;
else if (data === "FALSE") arr[R3][C3] = false;
else if (!isNaN(fuzzynum(data))) arr[R3][C3] = fuzzynum(data);
else if (!isNaN(fuzzydate(data).getDate())) arr[R3][C3] = parseDate(data);
else if (data.charCodeAt(0) == 35 && RBErr[data] != null) arr[R3][C3] = { t: "e", v: RBErr[data], w: data };
else arr[R3][C3] = data;
}
function prn_to_aoa_str(f4, opts) {
var o9 = opts || {};
var arr = [];
if (!f4 || f4.length === 0) return arr;
var lines = f4.split(/[\r\n]/);
var L3 = lines.length - 1;
while (L3 >= 0 && lines[L3].length === 0) --L3;
var start = 10, idx = 0;
var R3 = 0;
for (; R3 <= L3; ++R3) {
idx = lines[R3].indexOf(" ");
if (idx == -1) idx = lines[R3].length;
else idx++;
start = Math.max(start, idx);
}
for (R3 = 0; R3 <= L3; ++R3) {
arr[R3] = [];
var C3 = 0;
set_text_arr(lines[R3].slice(0, start).trim(), arr, R3, C3, o9);
for (C3 = 1; C3 <= (lines[R3].length - start) / 10 + 1; ++C3)
set_text_arr(lines[R3].slice(start + (C3 - 1) * 10, start + C3 * 10).trim(), arr, R3, C3, o9);
}
if (o9.sheetRows) arr = arr.slice(0, o9.sheetRows);
return arr;
}
var guess_seps = {
44: ",",
9: " ",
59: ";",
124: "|"
};
var guess_sep_weights = {
44: 3,
9: 2,
59: 1,
124: 0
};
function guess_sep(str2) {
var cnt = {}, instr = false, end = 0, cc = 0;
for (; end < str2.length; ++end) {
if ((cc = str2.charCodeAt(end)) == 34) instr = !instr;
else if (!instr && cc in guess_seps) cnt[cc] = (cnt[cc] || 0) + 1;
}
cc = [];
for (end in cnt) if (Object.prototype.hasOwnProperty.call(cnt, end)) {
cc.push([cnt[end], end]);
}
if (!cc.length) {
cnt = guess_sep_weights;
for (end in cnt) if (Object.prototype.hasOwnProperty.call(cnt, end)) {
cc.push([cnt[end], end]);
}
}
cc.sort(function(a3, b4) {
return a3[0] - b4[0] || guess_sep_weights[a3[1]] - guess_sep_weights[b4[1]];
});
return guess_seps[cc.pop()[1]] || 44;
}
function dsv_to_sheet_str(str2, opts) {
var o9 = opts || {};
var sep2 = "";
if (DENSE != null && o9.dense == null) o9.dense = DENSE;
var ws = {};
if (o9.dense) ws["!data"] = [];
var range2 = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } };
if (str2.slice(0, 4) == "sep=") {
if (str2.charCodeAt(5) == 13 && str2.charCodeAt(6) == 10) {
sep2 = str2.charAt(4);
str2 = str2.slice(7);
} else if (str2.charCodeAt(5) == 13 || str2.charCodeAt(5) == 10) {
sep2 = str2.charAt(4);
str2 = str2.slice(6);
} else sep2 = guess_sep(str2.slice(0, 1024));
} else if (o9 && o9.FS) sep2 = o9.FS;
else sep2 = guess_sep(str2.slice(0, 1024));
var R3 = 0, C3 = 0, v4 = 0;
var start = 0, end = 0, sepcc = sep2.charCodeAt(0), instr = false, cc = 0, startcc = str2.charCodeAt(0);
var _re = o9.dateNF != null ? dateNF_regex(o9.dateNF) : null;
function finish_cell() {
var s6 = str2.slice(start, end);
if (s6.slice(-1) == "\r") s6 = s6.slice(0, -1);
var cell = {};
if (s6.charAt(0) == '"' && s6.charAt(s6.length - 1) == '"') s6 = s6.slice(1, -1).replace(/""/g, '"');
if (o9.cellText !== false) cell.w = s6;
if (s6.length === 0) cell.t = "z";
else if (o9.raw) {
cell.t = "s";
cell.v = s6;
} else if (s6.trim().length === 0) {
cell.t = "s";
cell.v = s6;
} else if (s6.charCodeAt(0) == 61) {
if (s6.charCodeAt(1) == 34 && s6.charCodeAt(s6.length - 1) == 34) {
cell.t = "s";
cell.v = s6.slice(2, -1).replace(/""/g, '"');
} else if (fuzzyfmla(s6)) {
cell.t = "s";
cell.f = s6.slice(1);
cell.v = s6;
} else {
cell.t = "s";
cell.v = s6;
}
} else if (s6 == "TRUE") {
cell.t = "b";
cell.v = true;
} else if (s6 == "FALSE") {
cell.t = "b";
cell.v = false;
} else if (!isNaN(v4 = fuzzynum(s6))) {
cell.t = "n";
cell.v = v4;
} else if (!isNaN((v4 = fuzzydate(s6)).getDate()) || _re && s6.match(_re)) {
cell.z = o9.dateNF || table_fmt[14];
if (_re && s6.match(_re)) {
var news = dateNF_fix(s6, o9.dateNF, s6.match(_re) || []);
v4 = parseDate(news);
if (o9 && o9.UTC === false) v4 = utc_to_local(v4);
} else if (o9 && o9.UTC === false) v4 = utc_to_local(v4);
else if (o9.cellText !== false && o9.dateNF) cell.w = SSF_format(cell.z, v4);
if (o9.cellDates) {
cell.t = "d";
cell.v = v4;
} else {
cell.t = "n";
cell.v = datenum(v4);
}
if (!o9.cellNF) delete cell.z;
} else if (s6.charCodeAt(0) == 35 && RBErr[s6] != null) {
cell.t = "e";
cell.w = s6;
cell.v = RBErr[s6];
} else {
cell.t = "s";
cell.v = s6;
}
if (cell.t == "z") {
} else if (o9.dense) {
if (!ws["!data"][R3]) ws["!data"][R3] = [];
ws["!data"][R3][C3] = cell;
} else ws[encode_cell({ c: C3, r: R3 })] = cell;
start = end + 1;
startcc = str2.charCodeAt(start);
if (range2.e.c < C3) range2.e.c = C3;
if (range2.e.r < R3) range2.e.r = R3;
if (cc == sepcc) ++C3;
else {
C3 = 0;
++R3;
if (o9.sheetRows && o9.sheetRows <= R3) return true;
}
}
outer: for (; end < str2.length; ++end) switch (cc = str2.charCodeAt(end)) {
case 34:
if (startcc === 34) instr = !instr;
break;
case 13:
if (instr) break;
if (str2.charCodeAt(end + 1) == 10) ++end;
/* falls through */
case sepcc:
case 10:
if (!instr && finish_cell()) break outer;
break;
default:
break;
}
if (end - start > 0) finish_cell();
ws["!ref"] = encode_range(range2);
return ws;
}
function prn_to_sheet_str(str2, opts) {
if (!(opts && opts.PRN)) return dsv_to_sheet_str(str2, opts);
if (opts.FS) return dsv_to_sheet_str(str2, opts);
if (str2.slice(0, 4) == "sep=") return dsv_to_sheet_str(str2, opts);
if (str2.indexOf(" ") >= 0 || str2.indexOf(",") >= 0 || str2.indexOf(";") >= 0) return dsv_to_sheet_str(str2, opts);
return aoa_to_sheet(prn_to_aoa_str(str2, opts), opts);
}
function prn_to_sheet(d4, opts) {
var str2 = "", bytes = opts.type == "string" ? [0, 0, 0, 0] : firstbyte(d4, opts);
switch (opts.type) {
case "base64":
str2 = Base64_decode(d4);
break;
case "binary":
str2 = d4;
break;
case "buffer":
if (opts.codepage == 65001) str2 = d4.toString("utf8");
else if (opts.codepage && typeof $cptable !== "undefined") str2 = $cptable.utils.decode(opts.codepage, d4);
else str2 = has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4);
break;
case "array":
str2 = cc2str(d4);
break;
case "string":
str2 = d4;
break;
default:
throw new Error("Unrecognized type " + opts.type);
}
if (bytes[0] == 239 && bytes[1] == 187 && bytes[2] == 191) str2 = utf8read(str2.slice(3));
else if (opts.type != "string" && opts.type != "buffer" && opts.codepage == 65001) str2 = utf8read(str2);
else if (opts.type == "binary" && typeof $cptable !== "undefined" && opts.codepage) str2 = $cptable.utils.decode(opts.codepage, $cptable.utils.encode(28591, str2));
if (str2.slice(0, 19) == "socialcalc:version:") return ETH.to_sheet(opts.type == "string" ? str2 : utf8read(str2), opts);
return prn_to_sheet_str(str2, opts);
}
function prn_to_workbook(d4, opts) {
return sheet_to_workbook(prn_to_sheet(d4, opts), opts);
}
function sheet_to_prn(ws) {
var o9 = [];
if (!ws["!ref"]) return "";
var r8 = safe_decode_range(ws["!ref"]), cell;
var dense = ws["!data"] != null;
for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) {
var oo = [];
for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) {
var coord = encode_cell({ r: R3, c: C3 });
cell = dense ? (ws["!data"][R3] || [])[C3] : ws[coord];
if (!cell || cell.v == null) {
oo.push(" ");
continue;
}
var w3 = (cell.w || (format_cell(cell), cell.w) || "").slice(0, 10);
while (w3.length < 10) w3 += " ";
oo.push(w3 + (C3 === 0 ? " " : ""));
}
o9.push(oo.join(""));
}
return o9.join("\n");
}
return {
to_workbook: prn_to_workbook,
to_sheet: prn_to_sheet,
from_sheet: sheet_to_prn
};
})();
WK_ = /* @__PURE__ */ (function() {
function lotushopper(data, cb, opts) {
if (!data) return;
prep_blob(data, data.l || 0);
var Enum3 = opts.Enum || WK1Enum;
while (data.l < data.length) {
var RT = data.read_shift(2);
var R3 = Enum3[RT] || Enum3[65535];
var length = data.read_shift(2);
var tgt = data.l + length;
var d4 = R3.f && R3.f(data, length, opts);
data.l = tgt;
if (cb(d4, R3, RT)) return;
}
}
function lotus_to_workbook(d4, opts) {
switch (opts.type) {
case "base64":
return lotus_to_workbook_buf(s2a(Base64_decode(d4)), opts);
case "binary":
return lotus_to_workbook_buf(s2a(d4), opts);
case "buffer":
case "array":
return lotus_to_workbook_buf(d4, opts);
}
throw "Unsupported type " + opts.type;
}
var LOTUS_DATE_FMTS = [
"mmmm",
"dd-mmm-yyyy",
"dd-mmm",
"mmm-yyyy",
"@",
// "text"?
"mm/dd",
"hh:mm:ss AM/PM",
// 7
"hh:mm AM/PM",
"mm/dd/yyyy",
"mm/dd",
"hh:mm:ss",
"hh:mm"
// 12
];
function lotus_to_workbook_buf(d4, opts) {
if (!d4) return d4;
var o9 = opts || {};
if (DENSE != null && o9.dense == null) o9.dense = DENSE;
var s6 = {}, n7 = "Sheet1", next_n = "", sidx = 0;
var sheets = {}, snames = [], realnames = [], sdata = [];
if (o9.dense) sdata = s6["!data"] = [];
var refguess = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
var sheetRows = o9.sheetRows || 0;
var lastcell = {};
if (d4[4] == 81 && d4[5] == 80 && d4[6] == 87) return qpw_to_workbook_buf(d4, opts);
if (d4[2] == 0) {
if (d4[3] == 8 || d4[3] == 9) {
if (d4.length >= 16 && d4[14] == 5 && d4[15] === 108) throw new Error("Unsupported Works 3 for Mac file");
}
}
if (d4[2] == 2) {
o9.Enum = WK1Enum;
lotushopper(d4, function(val2, R3, RT) {
switch (RT) {
case 0:
o9.vers = val2;
if (val2 >= 4096) o9.qpro = true;
break;
case 255:
o9.vers = val2;
o9.works = true;
break;
case 6:
refguess = val2;
break;
/* RANGE */
case 204:
if (val2) next_n = val2;
break;
/* SHEETNAMECS */
case 222:
next_n = val2;
break;
/* SHEETNAMELP */
case 15:
/* LABEL */
case 51:
if ((!o9.qpro && !o9.works || RT == 51) && val2[1].v.charCodeAt(0) < 48) val2[1].v = val2[1].v.slice(1);
if (o9.works || o9.works2) val2[1].v = val2[1].v.replace(/\r\n/g, "\n");
/* falls through */
case 13:
/* INTEGER */
case 14:
/* NUMBER */
case 16:
if ((val2[2] & 112) == 112 && (val2[2] & 15) > 1 && (val2[2] & 15) < 15) {
val2[1].z = o9.dateNF || LOTUS_DATE_FMTS[(val2[2] & 15) - 1] || table_fmt[14];
if (o9.cellDates) {
val2[1].v = numdate(val2[1].v);
val2[1].t = typeof val2[1].v == "number" ? "n" : "d";
}
}
if (o9.qpro) {
if (val2[3] > sidx) {
s6["!ref"] = encode_range(refguess);
sheets[n7] = s6;
snames.push(n7);
s6 = {};
if (o9.dense) sdata = s6["!data"] = [];
refguess = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
sidx = val2[3];
n7 = next_n || "Sheet" + (sidx + 1);
next_n = "";
}
}
var tmpcell = o9.dense ? (sdata[val2[0].r] || [])[val2[0].c] : s6[encode_cell(val2[0])];
if (tmpcell) {
tmpcell.t = val2[1].t;
tmpcell.v = val2[1].v;
if (val2[1].z != null) tmpcell.z = val2[1].z;
if (val2[1].f != null) tmpcell.f = val2[1].f;
lastcell = tmpcell;
break;
}
if (o9.dense) {
if (!sdata[val2[0].r]) sdata[val2[0].r] = [];
sdata[val2[0].r][val2[0].c] = val2[1];
} else s6[encode_cell(val2[0])] = val2[1];
lastcell = val2[1];
break;
case 21509:
o9.works2 = true;
break;
case 21506:
{
if (val2 == 5281) {
lastcell.z = "hh:mm:ss";
if (o9.cellDates && lastcell.t == "n") {
lastcell.v = numdate(lastcell.v);
lastcell.t = typeof lastcell.v == "number" ? "n" : "d";
}
}
}
break;
}
}, o9);
} else if (d4[2] == 26 || d4[2] == 14) {
o9.Enum = WK3Enum;
if (d4[2] == 14) {
o9.qpro = true;
d4.l = 0;
}
lotushopper(d4, function(val2, R3, RT) {
switch (RT) {
case 204:
n7 = val2;
break;
/* SHEETNAMECS */
case 22:
if (val2[1].v.charCodeAt(0) < 48) val2[1].v = val2[1].v.slice(1);
val2[1].v = val2[1].v.replace(/\x0F./g, function($$) {
return String.fromCharCode($$.charCodeAt(1) - 32);
}).replace(/\r\n/g, "\n");
/* falls through */
case 23:
/* NUMBER17 */
case 24:
/* NUMBER18 */
case 25:
/* FORMULA19 */
case 37:
/* NUMBER25 */
case 39:
/* NUMBER27 */
case 40:
if (val2[3] > sidx) {
s6["!ref"] = encode_range(refguess);
sheets[n7] = s6;
snames.push(n7);
s6 = {};
if (o9.dense) sdata = s6["!data"] = [];
refguess = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
sidx = val2[3];
n7 = "Sheet" + (sidx + 1);
}
if (sheetRows > 0 && val2[0].r >= sheetRows) break;
if (o9.dense) {
if (!sdata[val2[0].r]) sdata[val2[0].r] = [];
sdata[val2[0].r][val2[0].c] = val2[1];
} else s6[encode_cell(val2[0])] = val2[1];
if (refguess.e.c < val2[0].c) refguess.e.c = val2[0].c;
if (refguess.e.r < val2[0].r) refguess.e.r = val2[0].r;
break;
case 27:
if (val2[14e3]) realnames[val2[14e3][0]] = val2[14e3][1];
break;
case 1537:
realnames[val2[0]] = val2[1];
if (val2[0] == sidx) n7 = val2[1];
break;
default:
break;
}
}, o9);
} else throw new Error("Unrecognized LOTUS BOF " + d4[2]);
s6["!ref"] = encode_range(refguess);
sheets[next_n || n7] = s6;
snames.push(next_n || n7);
if (!realnames.length) return { SheetNames: snames, Sheets: sheets };
var osheets = {}, rnames = [];
for (var i7 = 0; i7 < realnames.length; ++i7) if (sheets[snames[i7]]) {
rnames.push(realnames[i7] || snames[i7]);
osheets[realnames[i7]] = sheets[realnames[i7]] || sheets[snames[i7]];
} else {
rnames.push(realnames[i7]);
osheets[realnames[i7]] = { "!ref": "A1" };
}
return { SheetNames: rnames, Sheets: osheets };
}
function sheet_to_wk1(ws, opts) {
var o9 = opts || {};
if (+o9.codepage >= 0) set_cp(+o9.codepage);
if (o9.type == "string") throw new Error("Cannot write WK1 to JS string");
var ba = buf_array();
if (!ws["!ref"]) throw new Error("Cannot export empty sheet to WK1");
var range2 = safe_decode_range(ws["!ref"]);
var dense = ws["!data"] != null;
var cols = [];
write_biff_rec(ba, 0, write_BOF_WK1(1030));
write_biff_rec(ba, 6, write_RANGE(range2));
var max_R = Math.min(range2.e.r, 8191);
for (var C3 = range2.s.c; C3 <= range2.e.c; ++C3) cols[C3] = encode_col(C3);
for (var R3 = range2.s.r; R3 <= max_R; ++R3) {
var rr = encode_row(R3);
for (C3 = range2.s.c; C3 <= range2.e.c; ++C3) {
var cell = dense ? (ws["!data"][R3] || [])[C3] : ws[cols[C3] + rr];
if (!cell || cell.t == "z") continue;
switch (cell.t) {
case "n":
if ((cell.v | 0) == cell.v && cell.v >= -32768 && cell.v <= 32767) write_biff_rec(ba, 13, write_INTEGER(R3, C3, cell));
else write_biff_rec(ba, 14, write_NUMBER(R3, C3, cell));
break;
case "d":
var dc = datenum(cell.v);
if ((dc | 0) == dc && dc >= -32768 && dc <= 32767) write_biff_rec(ba, 13, write_INTEGER(R3, C3, { t: "n", v: dc, z: cell.z || table_fmt[14] }));
else write_biff_rec(ba, 14, write_NUMBER(R3, C3, { t: "n", v: dc, z: cell.z || table_fmt[14] }));
break;
default:
var str2 = format_cell(cell);
write_biff_rec(ba, 15, write_LABEL(R3, C3, str2.slice(0, 239)));
}
}
}
write_biff_rec(ba, 1);
return ba.end();
}
function book_to_wk3(wb, opts) {
var o9 = opts || {};
if (+o9.codepage >= 0) set_cp(+o9.codepage);
if (o9.type == "string") throw new Error("Cannot write WK3 to JS string");
var ba = buf_array();
write_biff_rec(ba, 0, write_BOF_WK3(wb));
for (var i7 = 0, cnt = 0; i7 < wb.SheetNames.length; ++i7) if ((wb.Sheets[wb.SheetNames[i7]] || {})["!ref"]) write_biff_rec(ba, 27, write_XFORMAT_SHEETNAME(wb.SheetNames[i7], cnt++));
var wsidx = 0;
for (i7 = 0; i7 < wb.SheetNames.length; ++i7) {
var ws = wb.Sheets[wb.SheetNames[i7]];
if (!ws || !ws["!ref"]) continue;
var range2 = safe_decode_range(ws["!ref"]);
var dense = ws["!data"] != null;
var cols = [];
var max_R = Math.min(range2.e.r, 8191);
for (var R3 = range2.s.r; R3 <= max_R; ++R3) {
var rr = encode_row(R3);
for (var C3 = range2.s.c; C3 <= range2.e.c; ++C3) {
if (R3 === range2.s.r) cols[C3] = encode_col(C3);
var ref = cols[C3] + rr;
var cell = dense ? (ws["!data"][R3] || [])[C3] : ws[ref];
if (!cell || cell.t == "z") continue;
if (cell.t == "n") {
write_biff_rec(ba, 23, write_NUMBER_17(R3, C3, wsidx, cell.v));
} else {
var str2 = format_cell(cell);
write_biff_rec(ba, 22, write_LABEL_16(R3, C3, wsidx, str2.slice(0, 239)));
}
}
}
++wsidx;
}
write_biff_rec(ba, 1);
return ba.end();
}
function write_BOF_WK1(v4) {
var out = new_buf(2);
out.write_shift(2, v4);
return out;
}
function write_BOF_WK3(wb) {
var out = new_buf(26);
out.write_shift(2, 4096);
out.write_shift(2, 4);
out.write_shift(4, 0);
var rows = 0, cols = 0, wscnt = 0;
for (var i7 = 0; i7 < wb.SheetNames.length; ++i7) {
var name = wb.SheetNames[i7];
var ws = wb.Sheets[name];
if (!ws || !ws["!ref"]) continue;
++wscnt;
var range2 = decode_range(ws["!ref"]);
if (rows < range2.e.r) rows = range2.e.r;
if (cols < range2.e.c) cols = range2.e.c;
}
if (rows > 8191) rows = 8191;
out.write_shift(2, rows);
out.write_shift(1, wscnt);
out.write_shift(1, cols);
out.write_shift(2, 0);
out.write_shift(2, 0);
out.write_shift(1, 1);
out.write_shift(1, 2);
out.write_shift(4, 0);
out.write_shift(4, 0);
return out;
}
function parse_RANGE(blob, length, opts) {
var o9 = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } };
if (length == 8 && opts.qpro) {
o9.s.c = blob.read_shift(1);
blob.l++;
o9.s.r = blob.read_shift(2);
o9.e.c = blob.read_shift(1);
blob.l++;
o9.e.r = blob.read_shift(2);
return o9;
}
o9.s.c = blob.read_shift(2);
o9.s.r = blob.read_shift(2);
if (length == 12 && opts.qpro) blob.l += 2;
o9.e.c = blob.read_shift(2);
o9.e.r = blob.read_shift(2);
if (length == 12 && opts.qpro) blob.l += 2;
if (o9.s.c == 65535) o9.s.c = o9.e.c = o9.s.r = o9.e.r = 0;
return o9;
}
function write_RANGE(range2) {
var out = new_buf(8);
out.write_shift(2, range2.s.c);
out.write_shift(2, range2.s.r);
out.write_shift(2, range2.e.c);
out.write_shift(2, range2.e.r);
return out;
}
function parse_cell(blob, length, opts) {
var o9 = [{ c: 0, r: 0 }, { t: "n", v: 0 }, 0, 0];
if (opts.qpro && opts.vers != 20768) {
o9[0].c = blob.read_shift(1);
o9[3] = blob.read_shift(1);
o9[0].r = blob.read_shift(2);
blob.l += 2;
} else if (opts.works) {
o9[0].c = blob.read_shift(2);
o9[0].r = blob.read_shift(2);
o9[2] = blob.read_shift(2);
} else {
o9[2] = blob.read_shift(1);
o9[0].c = blob.read_shift(2);
o9[0].r = blob.read_shift(2);
}
return o9;
}
function get_wk1_fmt(cell) {
if (cell.z && fmt_is_date(cell.z)) {
return 240 | (LOTUS_DATE_FMTS.indexOf(cell.z) + 1 || 2);
}
return 255;
}
function parse_LABEL(blob, length, opts) {
var tgt = blob.l + length;
var o9 = parse_cell(blob, length, opts);
o9[1].t = "s";
if ((opts.vers & 65534) == 20768) {
blob.l++;
var len = blob.read_shift(1);
o9[1].v = blob.read_shift(len, "utf8");
return o9;
}
if (opts.qpro) blob.l++;
o9[1].v = blob.read_shift(tgt - blob.l, "cstr");
return o9;
}
function write_LABEL(R3, C3, s6) {
var o9 = new_buf(7 + s6.length);
o9.write_shift(1, 255);
o9.write_shift(2, C3);
o9.write_shift(2, R3);
o9.write_shift(1, 39);
for (var i7 = 0; i7 < o9.length; ++i7) {
var cc = s6.charCodeAt(i7);
o9.write_shift(1, cc >= 128 ? 95 : cc);
}
o9.write_shift(1, 0);
return o9;
}
function parse_STRING(blob, length, opts) {
var tgt = blob.l + length;
var o9 = parse_cell(blob, length, opts);
o9[1].t = "s";
if (opts.vers == 20768) {
var len = blob.read_shift(1);
o9[1].v = blob.read_shift(len, "utf8");
return o9;
}
o9[1].v = blob.read_shift(tgt - blob.l, "cstr");
return o9;
}
function parse_INTEGER(blob, length, opts) {
var o9 = parse_cell(blob, length, opts);
o9[1].v = blob.read_shift(2, "i");
return o9;
}
function write_INTEGER(R3, C3, cell) {
var o9 = new_buf(7);
o9.write_shift(1, get_wk1_fmt(cell));
o9.write_shift(2, C3);
o9.write_shift(2, R3);
o9.write_shift(2, cell.v, "i");
return o9;
}
function parse_NUMBER(blob, length, opts) {
var o9 = parse_cell(blob, length, opts);
o9[1].v = blob.read_shift(8, "f");
return o9;
}
function write_NUMBER(R3, C3, cell) {
var o9 = new_buf(13);
o9.write_shift(1, get_wk1_fmt(cell));
o9.write_shift(2, C3);
o9.write_shift(2, R3);
o9.write_shift(8, cell.v, "f");
return o9;
}
function parse_FORMULA(blob, length, opts) {
var tgt = blob.l + length;
var o9 = parse_cell(blob, length, opts);
o9[1].v = blob.read_shift(8, "f");
if (opts.qpro) blob.l = tgt;
else {
var flen = blob.read_shift(2);
wk1_fmla_to_csf(blob.slice(blob.l, blob.l + flen), o9);
blob.l += flen;
}
return o9;
}
function wk1_parse_rc(B3, V3, col) {
var rel2 = V3 & 32768;
V3 &= ~32768;
V3 = (rel2 ? B3 : 0) + (V3 >= 8192 ? V3 - 16384 : V3);
return (rel2 ? "" : "$") + (col ? encode_col(V3) : encode_row(V3));
}
var FuncTab = {
31: ["NA", 0],
// 0x20: ["ERR", 0],
33: ["ABS", 1],
34: ["TRUNC", 1],
35: ["SQRT", 1],
36: ["LOG", 1],
37: ["LN", 1],
38: ["PI", 0],
39: ["SIN", 1],
40: ["COS", 1],
41: ["TAN", 1],
42: ["ATAN2", 2],
43: ["ATAN", 1],
44: ["ASIN", 1],
45: ["ACOS", 1],
46: ["EXP", 1],
47: ["MOD", 2],
// 0x30
49: ["ISNA", 1],
50: ["ISERR", 1],
51: ["FALSE", 0],
52: ["TRUE", 0],
53: ["RAND", 0],
54: ["DATE", 3],
// 0x37 NOW
// 0x38 PMT
// 0x39 PV
// 0x3A FV
// 0x3B IF
// 0x3C DAY
// 0x3D MONTH
// 0x3E YEAR
63: ["ROUND", 2],
64: ["TIME", 3],
// 0x41 HOUR
// 0x42 MINUTE
// 0x43 SECOND
68: ["ISNUMBER", 1],
69: ["ISTEXT", 1],
70: ["LEN", 1],
71: ["VALUE", 1],
// 0x48: ["FIXED", ?? 1],
73: ["MID", 3],
74: ["CHAR", 1],
// 0x4B
// 0x4C FIND
// 0x4D DATEVALUE
// 0x4E TIMEVALUE
// 0x4F CELL
80: ["SUM", 69],
81: ["AVERAGEA", 69],
82: ["COUNTA", 69],
83: ["MINA", 69],
84: ["MAXA", 69],
// 0x55 VLOOKUP
// 0x56 NPV
// 0x57 VAR
// 0x58 STD
// 0x59 IRR
// 0x5A HLOOKUP
// 0x5B DSUM
// 0x5C DAVERAGE
// 0x5D DCOUNTA
// 0x5E DMIN
// 0x5F DMAX
// 0x60 DVARP
// 0x61 DSTDEVP
// 0x62 INDEX
// 0x63 COLS
// 0x64 ROWS
// 0x65 REPEAT
102: ["UPPER", 1],
103: ["LOWER", 1],
// 0x68 LEFT
// 0x69 RIGHT
// 0x6A REPLACE
107: ["PROPER", 1],
// 0x6C CELL
109: ["TRIM", 1],
// 0x6E CLEAN
111: ["T", 1]
// 0x70 V
};
var BinOpTab = [
"",
"",
"",
"",
"",
"",
"",
"",
// eslint-disable-line no-mixed-spaces-and-tabs
"",
"+",
"-",
"*",
"/",
"^",
"=",
"<>",
// eslint-disable-line no-mixed-spaces-and-tabs
"<=",
">=",
"<",
">",
"",
"",
"",
"",
// eslint-disable-line no-mixed-spaces-and-tabs
"&",
"",
"",
"",
"",
"",
"",
""
// eslint-disable-line no-mixed-spaces-and-tabs
];
function wk1_fmla_to_csf(blob, o9) {
prep_blob(blob, 0);
var out = [], argc = 0, R3 = "", C3 = "", argL = "", argR = "";
while (blob.l < blob.length) {
var cc = blob[blob.l++];
switch (cc) {
case 0:
out.push(blob.read_shift(8, "f"));
break;
case 1:
{
C3 = wk1_parse_rc(o9[0].c, blob.read_shift(2), true);
R3 = wk1_parse_rc(o9[0].r, blob.read_shift(2), false);
out.push(C3 + R3);
}
break;
case 2:
{
var c6 = wk1_parse_rc(o9[0].c, blob.read_shift(2), true);
var r8 = wk1_parse_rc(o9[0].r, blob.read_shift(2), false);
C3 = wk1_parse_rc(o9[0].c, blob.read_shift(2), true);
R3 = wk1_parse_rc(o9[0].r, blob.read_shift(2), false);
out.push(c6 + r8 + ":" + C3 + R3);
}
break;
case 3:
if (blob.l < blob.length) {
console.error("WK1 premature formula end");
return;
}
break;
case 4:
out.push("(" + out.pop() + ")");
break;
case 5:
out.push(blob.read_shift(2));
break;
case 6:
{
var Z2 = "";
while (cc = blob[blob.l++]) Z2 += String.fromCharCode(cc);
out.push('"' + Z2.replace(/"/g, '""') + '"');
}
break;
case 8:
out.push("-" + out.pop());
break;
case 23:
out.push("+" + out.pop());
break;
case 22:
out.push("NOT(" + out.pop() + ")");
break;
case 20:
case 21:
{
argR = out.pop();
argL = out.pop();
out.push(["AND", "OR"][cc - 20] + "(" + argL + "," + argR + ")");
}
break;
default:
if (cc < 32 && BinOpTab[cc]) {
argR = out.pop();
argL = out.pop();
out.push(argL + BinOpTab[cc] + argR);
} else if (FuncTab[cc]) {
argc = FuncTab[cc][1];
if (argc == 69) argc = blob[blob.l++];
if (argc > out.length) {
console.error("WK1 bad formula parse 0x" + cc.toString(16) + ":|" + out.join("|") + "|");
return;
}
var args = out.slice(-argc);
out.length -= argc;
out.push(FuncTab[cc][0] + "(" + args.join(",") + ")");
} else if (cc <= 7) return console.error("WK1 invalid opcode " + cc.toString(16));
else if (cc <= 24) return console.error("WK1 unsupported op " + cc.toString(16));
else if (cc <= 30) return console.error("WK1 invalid opcode " + cc.toString(16));
else if (cc <= 115) return console.error("WK1 unsupported function opcode " + cc.toString(16));
else return console.error("WK1 unrecognized opcode " + cc.toString(16));
}
}
if (out.length == 1) o9[1].f = "" + out[0];
else console.error("WK1 bad formula parse |" + out.join("|") + "|");
}
function parse_cell_3(blob) {
var o9 = [{ c: 0, r: 0 }, { t: "n", v: 0 }, 0];
o9[0].r = blob.read_shift(2);
o9[3] = blob[blob.l++];
o9[0].c = blob[blob.l++];
return o9;
}
function parse_LABEL_16(blob, length) {
var o9 = parse_cell_3(blob, length);
o9[1].t = "s";
o9[1].v = blob.read_shift(length - 4, "cstr");
return o9;
}
function write_LABEL_16(R3, C3, wsidx, s6) {
var o9 = new_buf(6 + s6.length);
o9.write_shift(2, R3);
o9.write_shift(1, wsidx);
o9.write_shift(1, C3);
o9.write_shift(1, 39);
for (var i7 = 0; i7 < s6.length; ++i7) {
var cc = s6.charCodeAt(i7);
o9.write_shift(1, cc >= 128 ? 95 : cc);
}
o9.write_shift(1, 0);
return o9;
}
function parse_NUMBER_18(blob, length) {
var o9 = parse_cell_3(blob, length);
o9[1].v = blob.read_shift(2);
var v4 = o9[1].v >> 1;
if (o9[1].v & 1) {
switch (v4 & 7) {
case 0:
v4 = (v4 >> 3) * 5e3;
break;
case 1:
v4 = (v4 >> 3) * 500;
break;
case 2:
v4 = (v4 >> 3) / 20;
break;
case 3:
v4 = (v4 >> 3) / 200;
break;
case 4:
v4 = (v4 >> 3) / 2e3;
break;
case 5:
v4 = (v4 >> 3) / 2e4;
break;
case 6:
v4 = (v4 >> 3) / 16;
break;
case 7:
v4 = (v4 >> 3) / 64;
break;
}
}
o9[1].v = v4;
return o9;
}
function parse_NUMBER_17(blob, length) {
var o9 = parse_cell_3(blob, length);
var v1 = blob.read_shift(4);
var v22 = blob.read_shift(4);
var e9 = blob.read_shift(2);
if (e9 == 65535) {
if (v1 === 0 && v22 === 3221225472) {
o9[1].t = "e";
o9[1].v = 15;
} else if (v1 === 0 && v22 === 3489660928) {
o9[1].t = "e";
o9[1].v = 42;
} else o9[1].v = 0;
return o9;
}
var s6 = e9 & 32768;
e9 = (e9 & 32767) - 16446;
o9[1].v = (1 - s6 * 2) * (v22 * Math.pow(2, e9 + 32) + v1 * Math.pow(2, e9));
return o9;
}
function write_NUMBER_17(R3, C3, wsidx, v4) {
var o9 = new_buf(14);
o9.write_shift(2, R3);
o9.write_shift(1, wsidx);
o9.write_shift(1, C3);
if (v4 == 0) {
o9.write_shift(4, 0);
o9.write_shift(4, 0);
o9.write_shift(2, 65535);
return o9;
}
var s6 = 0, e9 = 0, v1 = 0, v22 = 0;
if (v4 < 0) {
s6 = 1;
v4 = -v4;
}
e9 = Math.log2(v4) | 0;
v4 /= Math.pow(2, e9 - 31);
v22 = v4 >>> 0;
if ((v22 & 2147483648) == 0) {
v4 /= 2;
++e9;
v22 = v4 >>> 0;
}
v4 -= v22;
v22 |= 2147483648;
v22 >>>= 0;
v4 *= Math.pow(2, 32);
v1 = v4 >>> 0;
o9.write_shift(4, v1);
o9.write_shift(4, v22);
e9 += 16383 + (s6 ? 32768 : 0);
o9.write_shift(2, e9);
return o9;
}
function parse_FORMULA_19(blob, length) {
var o9 = parse_NUMBER_17(blob, 14);
blob.l += length - 14;
return o9;
}
function parse_NUMBER_25(blob, length) {
var o9 = parse_cell_3(blob, length);
var v1 = blob.read_shift(4);
o9[1].v = v1 >> 6;
return o9;
}
function parse_NUMBER_27(blob, length) {
var o9 = parse_cell_3(blob, length);
var v1 = blob.read_shift(8, "f");
o9[1].v = v1;
return o9;
}
function parse_FORMULA_28(blob, length) {
var o9 = parse_NUMBER_27(blob, 12);
blob.l += length - 12;
return o9;
}
function parse_SHEETNAMECS(blob, length) {
return blob[blob.l + length - 1] == 0 ? blob.read_shift(length, "cstr") : "";
}
function parse_SHEETNAMELP(blob, length) {
var len = blob[blob.l++];
if (len > length - 1) len = length - 1;
var o9 = "";
while (o9.length < len) o9 += String.fromCharCode(blob[blob.l++]);
return o9;
}
function parse_SHEETINFOQP(blob, length, opts) {
if (!opts.qpro || length < 21) return;
var id = blob.read_shift(1);
blob.l += 17;
blob.l += 1;
blob.l += 2;
var nm = blob.read_shift(length - 21, "cstr");
return [id, nm];
}
function parse_XFORMAT(blob, length) {
var o9 = {}, tgt = blob.l + length;
while (blob.l < tgt) {
var dt = blob.read_shift(2);
if (dt == 14e3) {
o9[dt] = [0, ""];
o9[dt][0] = blob.read_shift(2);
while (blob[blob.l]) {
o9[dt][1] += String.fromCharCode(blob[blob.l]);
blob.l++;
}
blob.l++;
}
}
return o9;
}
function write_XFORMAT_SHEETNAME(name, wsidx) {
var out = new_buf(5 + name.length);
out.write_shift(2, 14e3);
out.write_shift(2, wsidx);
for (var i7 = 0; i7 < name.length; ++i7) {
var cc = name.charCodeAt(i7);
out[out.l++] = cc > 127 ? 95 : cc;
}
out[out.l++] = 0;
return out;
}
var WK1Enum = {
0: { n: "BOF", f: parseuint16 },
1: { n: "EOF" },
2: { n: "CALCMODE" },
3: { n: "CALCORDER" },
4: { n: "SPLIT" },
5: { n: "SYNC" },
6: { n: "RANGE", f: parse_RANGE },
7: { n: "WINDOW1" },
8: { n: "COLW1" },
9: { n: "WINTWO" },
10: { n: "COLW2" },
11: { n: "NAME" },
12: { n: "BLANK" },
13: { n: "INTEGER", f: parse_INTEGER },
14: { n: "NUMBER", f: parse_NUMBER },
15: { n: "LABEL", f: parse_LABEL },
16: { n: "FORMULA", f: parse_FORMULA },
24: { n: "TABLE" },
25: { n: "ORANGE" },
26: { n: "PRANGE" },
27: { n: "SRANGE" },
28: { n: "FRANGE" },
29: { n: "KRANGE1" },
32: { n: "HRANGE" },
35: { n: "KRANGE2" },
36: { n: "PROTEC" },
37: { n: "FOOTER" },
38: { n: "HEADER" },
39: { n: "SETUP" },
40: { n: "MARGINS" },
41: { n: "LABELFMT" },
42: { n: "TITLES" },
43: { n: "SHEETJS" },
45: { n: "GRAPH" },
46: { n: "NGRAPH" },
47: { n: "CALCCOUNT" },
48: { n: "UNFORMATTED" },
49: { n: "CURSORW12" },
50: { n: "WINDOW" },
51: { n: "STRING", f: parse_STRING },
55: { n: "PASSWORD" },
56: { n: "LOCKED" },
60: { n: "QUERY" },
61: { n: "QUERYNAME" },
62: { n: "PRINT" },
63: { n: "PRINTNAME" },
64: { n: "GRAPH2" },
65: { n: "GRAPHNAME" },
66: { n: "ZOOM" },
67: { n: "SYMSPLIT" },
68: { n: "NSROWS" },
69: { n: "NSCOLS" },
70: { n: "RULER" },
71: { n: "NNAME" },
72: { n: "ACOMM" },
73: { n: "AMACRO" },
74: { n: "PARSE" },
// 0x0064
102: { n: "PRANGES??" },
103: { n: "RRANGES??" },
104: { n: "FNAME??" },
105: { n: "MRANGES??" },
// 0x0096
// 0x0099
// 0x009A
// 0x009B
// 0x009C
// 0x00C0
// 0x00C7
// 0x00C9
204: { n: "SHEETNAMECS", f: parse_SHEETNAMECS },
// 0x00CD
222: { n: "SHEETNAMELP", f: parse_SHEETNAMELP },
255: { n: "BOF", f: parseuint16 },
21506: { n: "WKSNF", f: parseuint16 },
65535: { n: "" }
};
var WK3Enum = {
0: { n: "BOF" },
1: { n: "EOF" },
2: { n: "PASSWORD" },
3: { n: "CALCSET" },
4: { n: "WINDOWSET" },
5: { n: "SHEETCELLPTR" },
6: { n: "SHEETLAYOUT" },
7: { n: "COLUMNWIDTH" },
8: { n: "HIDDENCOLUMN" },
9: { n: "USERRANGE" },
10: { n: "SYSTEMRANGE" },
11: { n: "ZEROFORCE" },
12: { n: "SORTKEYDIR" },
13: { n: "FILESEAL" },
14: { n: "DATAFILLNUMS" },
15: { n: "PRINTMAIN" },
16: { n: "PRINTSTRING" },
17: { n: "GRAPHMAIN" },
18: { n: "GRAPHSTRING" },
19: { n: "??" },
20: { n: "ERRCELL" },
21: { n: "NACELL" },
22: { n: "LABEL16", f: parse_LABEL_16 },
23: { n: "NUMBER17", f: parse_NUMBER_17 },
24: { n: "NUMBER18", f: parse_NUMBER_18 },
25: { n: "FORMULA19", f: parse_FORMULA_19 },
26: { n: "FORMULA1A" },
27: { n: "XFORMAT", f: parse_XFORMAT },
28: { n: "DTLABELMISC" },
29: { n: "DTLABELCELL" },
30: { n: "GRAPHWINDOW" },
31: { n: "CPA" },
32: { n: "LPLAUTO" },
33: { n: "QUERY" },
34: { n: "HIDDENSHEET" },
35: { n: "??" },
37: { n: "NUMBER25", f: parse_NUMBER_25 },
38: { n: "??" },
39: { n: "NUMBER27", f: parse_NUMBER_27 },
40: { n: "FORMULA28", f: parse_FORMULA_28 },
142: { n: "??" },
147: { n: "??" },
150: { n: "??" },
151: { n: "??" },
152: { n: "??" },
153: { n: "??" },
154: { n: "??" },
155: { n: "??" },
156: { n: "??" },
163: { n: "??" },
174: { n: "??" },
175: { n: "??" },
176: { n: "??" },
177: { n: "??" },
184: { n: "??" },
185: { n: "??" },
186: { n: "??" },
187: { n: "??" },
188: { n: "??" },
195: { n: "??" },
201: { n: "??" },
204: { n: "SHEETNAMECS", f: parse_SHEETNAMECS },
205: { n: "??" },
206: { n: "??" },
207: { n: "??" },
208: { n: "??" },
256: { n: "??" },
259: { n: "??" },
260: { n: "??" },
261: { n: "??" },
262: { n: "??" },
263: { n: "??" },
265: { n: "??" },
266: { n: "??" },
267: { n: "??" },
268: { n: "??" },
270: { n: "??" },
271: { n: "??" },
384: { n: "??" },
389: { n: "??" },
390: { n: "??" },
393: { n: "??" },
396: { n: "??" },
512: { n: "??" },
514: { n: "??" },
513: { n: "??" },
516: { n: "??" },
517: { n: "??" },
640: { n: "??" },
641: { n: "??" },
642: { n: "??" },
643: { n: "??" },
644: { n: "??" },
645: { n: "??" },
646: { n: "??" },
647: { n: "??" },
648: { n: "??" },
658: { n: "??" },
659: { n: "??" },
660: { n: "??" },
661: { n: "??" },
662: { n: "??" },
665: { n: "??" },
666: { n: "??" },
768: { n: "??" },
772: { n: "??" },
1537: { n: "SHEETINFOQP", f: parse_SHEETINFOQP },
1600: { n: "??" },
1602: { n: "??" },
1793: { n: "??" },
1794: { n: "??" },
1795: { n: "??" },
1796: { n: "??" },
1920: { n: "??" },
2048: { n: "??" },
2049: { n: "??" },
2052: { n: "??" },
2688: { n: "??" },
10998: { n: "??" },
12849: { n: "??" },
28233: { n: "??" },
28484: { n: "??" },
65535: { n: "" }
};
var QPWNFTable = {
5: "dd-mmm-yy",
6: "dd-mmm",
7: "mmm-yy",
8: "mm/dd/yy",
// Long Date Intl
10: "hh:mm:ss AM/PM",
11: "hh:mm AM/PM",
14: "dd-mmm-yyyy",
15: "mmm-yyyy",
/* It is suspected that the the low nybble specifies decimal places */
34: "0.00",
50: "0.00;[Red]0.00",
66: "0.00;(0.00)",
82: "0.00;[Red](0.00)",
162: '"$"#,##0.00;\\("$"#,##0.00\\)',
288: "0%",
304: "0E+00",
320: "# ?/?"
};
function parse_qpw_str(p4) {
var cch = p4.read_shift(2);
var flags = p4.read_shift(1);
if (flags != 0) throw "unsupported QPW string type " + flags.toString(16);
return p4.read_shift(cch, "sbcs-cont");
}
function qpw_to_workbook_buf(d4, opts) {
prep_blob(d4, 0);
var o9 = opts || {};
if (DENSE != null && o9.dense == null) o9.dense = DENSE;
var s6 = {};
if (o9.dense) s6["!data"] = [];
var SST = [], sname = "", formulae = [];
var range2 = { s: { r: -1, c: -1 }, e: { r: -1, c: -1 } };
var cnt = 0, type = 0, C3 = 0, R3 = 0;
var wb = { SheetNames: [], Sheets: {} };
var FMTS = [];
outer: while (d4.l < d4.length) {
var RT = d4.read_shift(2), length = d4.read_shift(2);
var p4 = d4.slice(d4.l, d4.l + length);
prep_blob(p4, 0);
switch (RT) {
case 1:
if (p4.read_shift(4) != 962023505) throw "Bad QPW9 BOF!";
break;
case 2:
break outer;
case 8:
break;
// TODO: this is tied to custom number formats
case 10:
{
var fcnt = p4.read_shift(4);
var step = (p4.length - p4.l) / fcnt | 0;
for (var ifmt = 0; ifmt < fcnt; ++ifmt) {
var end = p4.l + step;
var fmt = {};
p4.l += 2;
fmt.numFmtId = p4.read_shift(2);
if (QPWNFTable[fmt.numFmtId]) fmt.z = QPWNFTable[fmt.numFmtId];
p4.l = end;
FMTS.push(fmt);
}
}
break;
/* TODO: The behavior here should be consistent with Numbers: QP Notebook ~ .TN.SheetArchive, QP Sheet ~ .TST.TableModelArchive */
case 1025:
break;
case 1026:
break;
case 1031:
{
p4.l += 12;
while (p4.l < p4.length) {
cnt = p4.read_shift(2);
type = p4.read_shift(1);
SST.push(p4.read_shift(cnt, "cstr"));
}
}
break;
case 1032:
{
}
break;
case 1537:
{
var sidx = p4.read_shift(2);
s6 = {};
if (o9.dense) s6["!data"] = [];
range2.s.c = p4.read_shift(2);
range2.e.c = p4.read_shift(2);
range2.s.r = p4.read_shift(4);
range2.e.r = p4.read_shift(4);
p4.l += 4;
if (p4.l + 2 < p4.length) {
cnt = p4.read_shift(2);
type = p4.read_shift(1);
sname = cnt == 0 ? "" : p4.read_shift(cnt, "cstr");
}
if (!sname) sname = encode_col(sidx);
}
break;
case 1538:
{
if (range2.s.c > 255 || range2.s.r > 999999) break;
if (range2.e.c < range2.s.c) range2.e.c = range2.s.c;
if (range2.e.r < range2.s.r) range2.e.r = range2.s.r;
s6["!ref"] = encode_range(range2);
book_append_sheet(wb, s6, sname);
}
break;
case 2561:
{
C3 = p4.read_shift(2);
if (range2.e.c < C3) range2.e.c = C3;
if (range2.s.c > C3) range2.s.c = C3;
R3 = p4.read_shift(4);
if (range2.s.r > R3) range2.s.r = R3;
R3 = p4.read_shift(4);
if (range2.e.r < R3) range2.e.r = R3;
}
break;
case 3073:
{
R3 = p4.read_shift(4), cnt = p4.read_shift(4);
if (range2.s.r > R3) range2.s.r = R3;
if (range2.e.r < R3 + cnt - 1) range2.e.r = R3 + cnt - 1;
var CC = encode_col(C3);
while (p4.l < p4.length) {
var cell = { t: "z" };
var flags = p4.read_shift(1), fmtidx = -1;
if (flags & 128) fmtidx = p4.read_shift(2);
var mul = flags & 64 ? p4.read_shift(2) - 1 : 0;
switch (flags & 31) {
case 0:
break;
case 1:
break;
case 2:
cell = { t: "n", v: p4.read_shift(2) };
break;
case 3:
cell = { t: "n", v: p4.read_shift(2, "i") };
break;
case 4:
cell = { t: "n", v: parse_RkNumber(p4) };
break;
case 5:
cell = { t: "n", v: p4.read_shift(8, "f") };
break;
case 7:
cell = { t: "s", v: SST[type = p4.read_shift(4) - 1] };
break;
case 8:
cell = { t: "n", v: p4.read_shift(8, "f") };
p4.l += 2;
p4.l += 4;
if (isNaN(cell.v)) cell = { t: "e", v: 15 };
break;
default:
throw "Unrecognized QPW cell type " + (flags & 31);
}
if (fmtidx != -1 && (FMTS[fmtidx - 1] || {}).z) cell.z = FMTS[fmtidx - 1].z;
var delta = 0;
if (flags & 32) switch (flags & 31) {
case 2:
delta = p4.read_shift(2);
break;
case 3:
delta = p4.read_shift(2, "i");
break;
case 7:
delta = p4.read_shift(2);
break;
default:
throw "Unsupported delta for QPW cell type " + (flags & 31);
}
if (!(!o9.sheetStubs && cell.t == "z")) {
var newcell = dup(cell);
if (cell.t == "n" && cell.z && fmt_is_date(cell.z) && o9.cellDates) {
newcell.v = numdate(cell.v);
newcell.t = typeof newcell.v == "number" ? "n" : "d";
}
if (s6["!data"] != null) {
if (!s6["!data"][R3]) s6["!data"][R3] = [];
s6["!data"][R3][C3] = newcell;
} else s6[CC + encode_row(R3)] = newcell;
}
++R3;
--cnt;
while (mul-- > 0 && cnt >= 0) {
if (flags & 32) switch (flags & 31) {
case 2:
cell = { t: "n", v: cell.v + delta & 65535 };
break;
case 3:
cell = { t: "n", v: cell.v + delta & 65535 };
if (cell.v > 32767) cell.v -= 65536;
break;
case 7:
cell = { t: "s", v: SST[type = type + delta >>> 0] };
break;
default:
throw "Cannot apply delta for QPW cell type " + (flags & 31);
}
else switch (flags & 31) {
case 1:
cell = { t: "z" };
break;
case 2:
cell = { t: "n", v: p4.read_shift(2) };
break;
case 7:
cell = { t: "s", v: SST[type = p4.read_shift(4) - 1] };
break;
default:
throw "Cannot apply repeat for QPW cell type " + (flags & 31);
}
if (fmtidx != -1) ;
if (!(!o9.sheetStubs && cell.t == "z")) {
if (s6["!data"] != null) {
if (!s6["!data"][R3]) s6["!data"][R3] = [];
s6["!data"][R3][C3] = cell;
} else s6[CC + encode_row(R3)] = cell;
}
++R3;
--cnt;
}
}
}
break;
case 3074:
{
C3 = p4.read_shift(2);
R3 = p4.read_shift(4);
var str2 = parse_qpw_str(p4);
if (s6["!data"] != null) {
if (!s6["!data"][R3]) s6["!data"][R3] = [];
s6["!data"][R3][C3] = { t: "s", v: str2 };
} else s6[encode_col(C3) + encode_row(R3)] = { t: "s", v: str2 };
}
break;
default:
break;
}
d4.l += length;
}
return wb;
}
return {
sheet_to_wk1,
book_to_wk3,
to_workbook: lotus_to_workbook
};
})();
parse_rs = /* @__PURE__ */ (function() {
function parse_r(r8) {
var t6 = str_match_xml_ns(r8, "t");
if (!t6) return { t: "s", v: "" };
var o9 = { t: "s", v: unescapexml(t6[1]) };
var rpr = str_match_xml_ns(r8, "rPr");
if (rpr) o9.s = parse_rpr(rpr[1]);
return o9;
}
var rregex = /<(?:\w+:)?r>/g, rend = /<\/(?:\w+:)?r>/;
return function parse_rs2(rs) {
return rs.replace(rregex, "").split(rend).map(parse_r).filter(function(r8) {
return r8.v;
});
};
})();
rs_to_html = /* @__PURE__ */ (function parse_rs_factory() {
var nlregex = /(\r\n|\n)/g;
function parse_rpr2(font, intro, outro) {
var style = [];
if (font.u) style.push("text-decoration: underline;");
if (font.uval) style.push("text-underline-style:" + font.uval + ";");
if (font.sz) style.push("font-size:" + font.sz + "pt;");
if (font.outline) style.push("text-effect: outline;");
if (font.shadow) style.push("text-shadow: auto;");
intro.push('');
if (font.b) {
intro.push("");
outro.push("");
}
if (font.i) {
intro.push("");
outro.push("");
}
if (font.strike) {
intro.push("");
outro.push("");
}
var align = font.valign || "";
if (align == "superscript" || align == "super") align = "sup";
else if (align == "subscript") align = "sub";
if (align != "") {
intro.push("<" + align + ">");
outro.push("" + align + ">");
}
outro.push("");
return font;
}
function r_to_html(r8) {
var terms = [[], r8.v, []];
if (!r8.v) return "";
if (r8.s) parse_rpr2(r8.s, terms[0], terms[2]);
return terms[0].join("") + terms[1].replace(nlregex, "
") + terms[2].join("");
}
return function parse_rs2(rs) {
return rs.map(r_to_html).join("");
};
})();
sitregex = /<(?:\w+:)?t\b[^<>]*>([^<]*)<\/(?:\w+:)?t>/g;
sirregex = /<(?:\w+:)?r\b[^<>]*>/;
sstr1 = /<(?:\w+:)?(?:si|sstItem)>/g;
sstr2 = /<\/(?:\w+:)?(?:si|sstItem)>/;
crypto_CreateXorArray_Method1 = /* @__PURE__ */ (function() {
var PadArray = [187, 255, 255, 186, 255, 255, 185, 128, 0, 190, 15, 0, 191, 15, 0];
var InitialCode = [57840, 7439, 52380, 33984, 4364, 3600, 61902, 12606, 6258, 57657, 54287, 34041, 10252, 43370, 20163];
var XorMatrix = [44796, 19929, 39858, 10053, 20106, 40212, 10761, 31585, 63170, 64933, 60267, 50935, 40399, 11199, 17763, 35526, 1453, 2906, 5812, 11624, 23248, 885, 1770, 3540, 7080, 14160, 28320, 56640, 55369, 41139, 20807, 41614, 21821, 43642, 17621, 28485, 56970, 44341, 19019, 38038, 14605, 29210, 60195, 50791, 40175, 10751, 21502, 43004, 24537, 18387, 36774, 3949, 7898, 15796, 31592, 63184, 47201, 24803, 49606, 37805, 14203, 28406, 56812, 17824, 35648, 1697, 3394, 6788, 13576, 27152, 43601, 17539, 35078, 557, 1114, 2228, 4456, 30388, 60776, 51953, 34243, 7079, 14158, 28316, 14128, 28256, 56512, 43425, 17251, 34502, 7597, 13105, 26210, 52420, 35241, 883, 1766, 3532, 4129, 8258, 16516, 33032, 4657, 9314, 18628];
var Ror = function(Byte) {
return (Byte / 2 | Byte * 128) & 255;
};
var XorRor = function(byte1, byte2) {
return Ror(byte1 ^ byte2);
};
var CreateXorKey_Method1 = function(Password) {
var XorKey = InitialCode[Password.length - 1];
var CurrentElement = 104;
for (var i7 = Password.length - 1; i7 >= 0; --i7) {
var Char = Password[i7];
for (var j3 = 0; j3 != 7; ++j3) {
if (Char & 64) XorKey ^= XorMatrix[CurrentElement];
Char *= 2;
--CurrentElement;
}
}
return XorKey;
};
return function(password) {
var Password = _JS2ANSI(password);
var XorKey = CreateXorKey_Method1(Password);
var Index3 = Password.length;
var ObfuscationArray = new_raw_buf(16);
for (var i7 = 0; i7 != 16; ++i7) ObfuscationArray[i7] = 0;
var Temp, PasswordLastChar, PadIndex;
if ((Index3 & 1) === 1) {
Temp = XorKey >> 8;
ObfuscationArray[Index3] = XorRor(PadArray[0], Temp);
--Index3;
Temp = XorKey & 255;
PasswordLastChar = Password[Password.length - 1];
ObfuscationArray[Index3] = XorRor(PasswordLastChar, Temp);
}
while (Index3 > 0) {
--Index3;
Temp = XorKey >> 8;
ObfuscationArray[Index3] = XorRor(Password[Index3], Temp);
--Index3;
Temp = XorKey & 255;
ObfuscationArray[Index3] = XorRor(Password[Index3], Temp);
}
Index3 = 15;
PadIndex = 15 - Password.length;
while (PadIndex > 0) {
Temp = XorKey >> 8;
ObfuscationArray[Index3] = XorRor(PadArray[PadIndex], Temp);
--Index3;
--PadIndex;
Temp = XorKey & 255;
ObfuscationArray[Index3] = XorRor(Password[Index3], Temp);
--Index3;
--PadIndex;
}
return ObfuscationArray;
};
})();
crypto_DecryptData_Method1 = function(password, Data, XorArrayIndex, XorArray, O2) {
if (!O2) O2 = Data;
if (!XorArray) XorArray = crypto_CreateXorArray_Method1(password);
var Index3, Value;
for (Index3 = 0; Index3 != Data.length; ++Index3) {
Value = Data[Index3];
Value ^= XorArray[XorArrayIndex];
Value = (Value >> 5 | Value << 3) & 255;
O2[Index3] = Value;
++XorArrayIndex;
}
return [O2, XorArrayIndex, XorArray];
};
crypto_MakeXorDecryptor = function(password) {
var XorArrayIndex = 0, XorArray = crypto_CreateXorArray_Method1(password);
return function(Data) {
var O2 = crypto_DecryptData_Method1("", Data, XorArrayIndex, XorArray);
XorArrayIndex = O2[1];
return O2[0];
};
};
DEF_MDW = 6;
MAX_MDW = 15;
MIN_MDW = 1;
MDW = DEF_MDW;
DEF_PPI = 96;
PPI = DEF_PPI;
XLMLPatternTypeMap = {
"None": "none",
"Solid": "solid",
"Gray50": "mediumGray",
"Gray75": "darkGray",
"Gray25": "lightGray",
"HorzStripe": "darkHorizontal",
"VertStripe": "darkVertical",
"ReverseDiagStripe": "darkDown",
"DiagStripe": "darkUp",
"DiagCross": "darkGrid",
"ThickDiagCross": "darkTrellis",
"ThinHorzStripe": "lightHorizontal",
"ThinVertStripe": "lightVertical",
"ThinReverseDiagStripe": "lightDown",
"ThinHorzCross": "lightGrid"
};
cellXF_uint = ["numFmtId", "fillId", "fontId", "borderId", "xfId"];
cellXF_bool = ["applyAlignment", "applyBorder", "applyFill", "applyFont", "applyNumberFormat", "applyProtection", "pivotButton", "quotePrefix"];
parse_sty_xml = /* @__PURE__ */ (function make_pstyx() {
return function parse_sty_xml2(data, themes, opts) {
var styles2 = {};
if (!data) return styles2;
data = remove_doctype(str_remove_ng(data, ""));
var t6;
if (t6 = str_match_xml_ns(data, "numFmts")) parse_numFmts(t6[0], styles2, opts);
if (t6 = str_match_xml_ns(data, "fonts")) parse_fonts(t6[0], styles2, themes, opts);
if (t6 = str_match_xml_ns(data, "fills")) parse_fills(t6[0], styles2, themes, opts);
if (t6 = str_match_xml_ns(data, "borders")) parse_borders(t6[0], styles2, themes, opts);
if (t6 = str_match_xml_ns(data, "cellXfs")) parse_cellXfs(t6[0], styles2, opts);
return styles2;
};
})();
parse_BrtFill = parsenoop;
parse_BrtBorder = parsenoop;
XLSXThemeClrScheme = [
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
];
parse_BrtCommentAuthor = parse_XLWideString;
CT_VBA = "application/vnd.ms-office.vbaProject";
rc_to_a1 = /* @__PURE__ */ (function() {
var rcregex = /(^|[^A-Za-z_])R(\[?-?\d+\]|[1-9]\d*|)C(\[?-?\d+\]|[1-9]\d*|)(?![A-Za-z0-9_])/g;
var rcbase = { r: 0, c: 0 };
function rcfunc($$, $1, $22, $32) {
var cRel = false, rRel = false;
if ($22.length == 0) rRel = true;
else if ($22.charAt(0) == "[") {
rRel = true;
$22 = $22.slice(1, -1);
}
if ($32.length == 0) cRel = true;
else if ($32.charAt(0) == "[") {
cRel = true;
$32 = $32.slice(1, -1);
}
var R3 = $22.length > 0 ? parseInt($22, 10) | 0 : 0, C3 = $32.length > 0 ? parseInt($32, 10) | 0 : 0;
if (cRel) C3 += rcbase.c;
else --C3;
if (rRel) R3 += rcbase.r;
else --R3;
return $1 + (cRel ? "" : "$") + encode_col(C3) + (rRel ? "" : "$") + encode_row(R3);
}
return function rc_to_a12(fstr, base) {
rcbase = base;
return fstr.replace(rcregex, rcfunc);
};
})();
crefregex = /(^|[^._A-Z0-9])(\$?)([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])(\$?)(\d{1,7})(?![_.\(A-Za-z0-9])/g;
try {
crefregex = /(^|[^._A-Z0-9])([$]?)([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([$]?)(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})(?![_.\(A-Za-z0-9])/g;
} catch (e9) {
}
a1_to_rc = /* @__PURE__ */ (function() {
return function a1_to_rc2(fstr, base) {
return fstr.replace(crefregex, function($0, $1, $22, $32, $4, $5) {
var c6 = decode_col($32) - ($22 ? 0 : base.c);
var r8 = decode_row($5) - ($4 ? 0 : base.r);
var R3 = $4 == "$" ? r8 + 1 : r8 == 0 ? "" : "[" + r8 + "]";
var C3 = $22 == "$" ? c6 + 1 : c6 == 0 ? "" : "[" + c6 + "]";
return $1 + "R" + R3 + "C" + C3;
});
};
})();
parse_PtgMemErr = parsenoop;
parse_PtgMemNoMem = parsenoop;
parse_PtgTbl = parsenoop;
parse_PtgElfCol = parse_PtgElfLoc;
parse_PtgElfColS = parse_PtgElfNoop;
parse_PtgElfColSV = parse_PtgElfNoop;
parse_PtgElfColV = parse_PtgElfLoc;
parse_PtgElfRadical = parse_PtgElfLoc;
parse_PtgElfRadicalLel = parse_PtgElfLel;
parse_PtgElfRadicalS = parse_PtgElfNoop;
parse_PtgElfRw = parse_PtgElfLoc;
parse_PtgElfRwV = parse_PtgElfLoc;
PtgListRT = [
"Data",
"All",
"Headers",
"??",
"?Data2",
"??",
"?DataHeaders",
"??",
"Totals",
"??",
"??",
"??",
"?DataTotals",
"??",
"??",
"??",
"?Current"
];
PtgTypes = {
1: { n: "PtgExp", f: parse_PtgExp },
2: { n: "PtgTbl", f: parse_PtgTbl },
3: { n: "PtgAdd", f: parseread1 },
4: { n: "PtgSub", f: parseread1 },
5: { n: "PtgMul", f: parseread1 },
6: { n: "PtgDiv", f: parseread1 },
7: { n: "PtgPower", f: parseread1 },
8: { n: "PtgConcat", f: parseread1 },
9: { n: "PtgLt", f: parseread1 },
10: { n: "PtgLe", f: parseread1 },
11: { n: "PtgEq", f: parseread1 },
12: { n: "PtgGe", f: parseread1 },
13: { n: "PtgGt", f: parseread1 },
14: { n: "PtgNe", f: parseread1 },
15: { n: "PtgIsect", f: parseread1 },
16: { n: "PtgUnion", f: parseread1 },
17: { n: "PtgRange", f: parseread1 },
18: { n: "PtgUplus", f: parseread1 },
19: { n: "PtgUminus", f: parseread1 },
20: { n: "PtgPercent", f: parseread1 },
21: { n: "PtgParen", f: parseread1 },
22: { n: "PtgMissArg", f: parseread1 },
23: { n: "PtgStr", f: parse_PtgStr },
26: { n: "PtgSheet", f: parse_PtgSheet },
27: { n: "PtgEndSheet", f: parse_PtgEndSheet },
28: { n: "PtgErr", f: parse_PtgErr },
29: { n: "PtgBool", f: parse_PtgBool },
30: { n: "PtgInt", f: parse_PtgInt },
31: { n: "PtgNum", f: parse_PtgNum },
32: { n: "PtgArray", f: parse_PtgArray },
33: { n: "PtgFunc", f: parse_PtgFunc },
34: { n: "PtgFuncVar", f: parse_PtgFuncVar },
35: { n: "PtgName", f: parse_PtgName },
36: { n: "PtgRef", f: parse_PtgRef },
37: { n: "PtgArea", f: parse_PtgArea },
38: { n: "PtgMemArea", f: parse_PtgMemArea },
39: { n: "PtgMemErr", f: parse_PtgMemErr },
40: { n: "PtgMemNoMem", f: parse_PtgMemNoMem },
41: { n: "PtgMemFunc", f: parse_PtgMemFunc },
42: { n: "PtgRefErr", f: parse_PtgRefErr },
43: { n: "PtgAreaErr", f: parse_PtgAreaErr },
44: { n: "PtgRefN", f: parse_PtgRefN },
45: { n: "PtgAreaN", f: parse_PtgAreaN },
46: { n: "PtgMemAreaN", f: parse_PtgMemAreaN },
47: { n: "PtgMemNoMemN", f: parse_PtgMemNoMemN },
57: { n: "PtgNameX", f: parse_PtgNameX },
58: { n: "PtgRef3d", f: parse_PtgRef3d },
59: { n: "PtgArea3d", f: parse_PtgArea3d },
60: { n: "PtgRefErr3d", f: parse_PtgRefErr3d },
61: { n: "PtgAreaErr3d", f: parse_PtgAreaErr3d },
255: {}
};
PtgDupes = {
64: 32,
96: 32,
65: 33,
97: 33,
66: 34,
98: 34,
67: 35,
99: 35,
68: 36,
100: 36,
69: 37,
101: 37,
70: 38,
102: 38,
71: 39,
103: 39,
72: 40,
104: 40,
73: 41,
105: 41,
74: 42,
106: 42,
75: 43,
107: 43,
76: 44,
108: 44,
77: 45,
109: 45,
78: 46,
110: 46,
79: 47,
111: 47,
88: 34,
120: 34,
89: 57,
121: 57,
90: 58,
122: 58,
91: 59,
123: 59,
92: 60,
124: 60,
93: 61,
125: 61
};
Ptg18 = {
1: { n: "PtgElfLel", f: parse_PtgElfLel },
2: { n: "PtgElfRw", f: parse_PtgElfRw },
3: { n: "PtgElfCol", f: parse_PtgElfCol },
6: { n: "PtgElfRwV", f: parse_PtgElfRwV },
7: { n: "PtgElfColV", f: parse_PtgElfColV },
10: { n: "PtgElfRadical", f: parse_PtgElfRadical },
11: { n: "PtgElfRadicalS", f: parse_PtgElfRadicalS },
13: { n: "PtgElfColS", f: parse_PtgElfColS },
15: { n: "PtgElfColSV", f: parse_PtgElfColSV },
16: { n: "PtgElfRadicalLel", f: parse_PtgElfRadicalLel },
25: { n: "PtgList", f: parse_PtgList },
29: { n: "PtgSxName", f: parse_PtgSxName },
255: {}
};
Ptg19 = {
0: { n: "PtgAttrNoop", f: parse_PtgAttrNoop },
1: { n: "PtgAttrSemi", f: parse_PtgAttrSemi },
2: { n: "PtgAttrIf", f: parse_PtgAttrIf },
4: { n: "PtgAttrChoose", f: parse_PtgAttrChoose },
8: { n: "PtgAttrGoto", f: parse_PtgAttrGoto },
16: { n: "PtgAttrSum", f: parse_PtgAttrSum },
32: { n: "PtgAttrBaxcel", f: parse_PtgAttrBaxcel },
33: { n: "PtgAttrBaxcel", f: parse_PtgAttrBaxcel },
64: { n: "PtgAttrSpace", f: parse_PtgAttrSpace },
65: { n: "PtgAttrSpaceSemi", f: parse_PtgAttrSpaceSemi },
128: { n: "PtgAttrIfError", f: parse_PtgAttrIfError },
255: {}
};
PtgBinOp = {
PtgAdd: "+",
PtgConcat: "&",
PtgDiv: "/",
PtgEq: "=",
PtgGe: ">=",
PtgGt: ">",
PtgLe: "<=",
PtgLt: "<",
PtgMul: "*",
PtgNe: "<>",
PtgPower: "^",
PtgSub: "-"
};
parse_XLSBArrayParsedFormula = parse_XLSBParsedFormula;
parse_XLSBCellParsedFormula = parse_XLSBParsedFormula;
parse_XLSBNameParsedFormula = parse_XLSBParsedFormula;
parse_XLSBSharedParsedFormula = parse_XLSBParsedFormula;
Cetab = {
0: "BEEP",
1: "OPEN",
2: "OPEN.LINKS",
3: "CLOSE.ALL",
4: "SAVE",
5: "SAVE.AS",
6: "FILE.DELETE",
7: "PAGE.SETUP",
8: "PRINT",
9: "PRINTER.SETUP",
10: "QUIT",
11: "NEW.WINDOW",
12: "ARRANGE.ALL",
13: "WINDOW.SIZE",
14: "WINDOW.MOVE",
15: "FULL",
16: "CLOSE",
17: "RUN",
22: "SET.PRINT.AREA",
23: "SET.PRINT.TITLES",
24: "SET.PAGE.BREAK",
25: "REMOVE.PAGE.BREAK",
26: "FONT",
27: "DISPLAY",
28: "PROTECT.DOCUMENT",
29: "PRECISION",
30: "A1.R1C1",
31: "CALCULATE.NOW",
32: "CALCULATION",
34: "DATA.FIND",
35: "EXTRACT",
36: "DATA.DELETE",
37: "SET.DATABASE",
38: "SET.CRITERIA",
39: "SORT",
40: "DATA.SERIES",
41: "TABLE",
42: "FORMAT.NUMBER",
43: "ALIGNMENT",
44: "STYLE",
45: "BORDER",
46: "CELL.PROTECTION",
47: "COLUMN.WIDTH",
48: "UNDO",
49: "CUT",
50: "COPY",
51: "PASTE",
52: "CLEAR",
53: "PASTE.SPECIAL",
54: "EDIT.DELETE",
55: "INSERT",
56: "FILL.RIGHT",
57: "FILL.DOWN",
61: "DEFINE.NAME",
62: "CREATE.NAMES",
63: "FORMULA.GOTO",
64: "FORMULA.FIND",
65: "SELECT.LAST.CELL",
66: "SHOW.ACTIVE.CELL",
67: "GALLERY.AREA",
68: "GALLERY.BAR",
69: "GALLERY.COLUMN",
70: "GALLERY.LINE",
71: "GALLERY.PIE",
72: "GALLERY.SCATTER",
73: "COMBINATION",
74: "PREFERRED",
75: "ADD.OVERLAY",
76: "GRIDLINES",
77: "SET.PREFERRED",
78: "AXES",
79: "LEGEND",
80: "ATTACH.TEXT",
81: "ADD.ARROW",
82: "SELECT.CHART",
83: "SELECT.PLOT.AREA",
84: "PATTERNS",
85: "MAIN.CHART",
86: "OVERLAY",
87: "SCALE",
88: "FORMAT.LEGEND",
89: "FORMAT.TEXT",
90: "EDIT.REPEAT",
91: "PARSE",
92: "JUSTIFY",
93: "HIDE",
94: "UNHIDE",
95: "WORKSPACE",
96: "FORMULA",
97: "FORMULA.FILL",
98: "FORMULA.ARRAY",
99: "DATA.FIND.NEXT",
100: "DATA.FIND.PREV",
101: "FORMULA.FIND.NEXT",
102: "FORMULA.FIND.PREV",
103: "ACTIVATE",
104: "ACTIVATE.NEXT",
105: "ACTIVATE.PREV",
106: "UNLOCKED.NEXT",
107: "UNLOCKED.PREV",
108: "COPY.PICTURE",
109: "SELECT",
110: "DELETE.NAME",
111: "DELETE.FORMAT",
112: "VLINE",
113: "HLINE",
114: "VPAGE",
115: "HPAGE",
116: "VSCROLL",
117: "HSCROLL",
118: "ALERT",
119: "NEW",
120: "CANCEL.COPY",
121: "SHOW.CLIPBOARD",
122: "MESSAGE",
124: "PASTE.LINK",
125: "APP.ACTIVATE",
126: "DELETE.ARROW",
127: "ROW.HEIGHT",
128: "FORMAT.MOVE",
129: "FORMAT.SIZE",
130: "FORMULA.REPLACE",
131: "SEND.KEYS",
132: "SELECT.SPECIAL",
133: "APPLY.NAMES",
134: "REPLACE.FONT",
135: "FREEZE.PANES",
136: "SHOW.INFO",
137: "SPLIT",
138: "ON.WINDOW",
139: "ON.DATA",
140: "DISABLE.INPUT",
142: "OUTLINE",
143: "LIST.NAMES",
144: "FILE.CLOSE",
145: "SAVE.WORKBOOK",
146: "DATA.FORM",
147: "COPY.CHART",
148: "ON.TIME",
149: "WAIT",
150: "FORMAT.FONT",
151: "FILL.UP",
152: "FILL.LEFT",
153: "DELETE.OVERLAY",
155: "SHORT.MENUS",
159: "SET.UPDATE.STATUS",
161: "COLOR.PALETTE",
162: "DELETE.STYLE",
163: "WINDOW.RESTORE",
164: "WINDOW.MAXIMIZE",
166: "CHANGE.LINK",
167: "CALCULATE.DOCUMENT",
168: "ON.KEY",
169: "APP.RESTORE",
170: "APP.MOVE",
171: "APP.SIZE",
172: "APP.MINIMIZE",
173: "APP.MAXIMIZE",
174: "BRING.TO.FRONT",
175: "SEND.TO.BACK",
185: "MAIN.CHART.TYPE",
186: "OVERLAY.CHART.TYPE",
187: "SELECT.END",
188: "OPEN.MAIL",
189: "SEND.MAIL",
190: "STANDARD.FONT",
191: "CONSOLIDATE",
192: "SORT.SPECIAL",
193: "GALLERY.3D.AREA",
194: "GALLERY.3D.COLUMN",
195: "GALLERY.3D.LINE",
196: "GALLERY.3D.PIE",
197: "VIEW.3D",
198: "GOAL.SEEK",
199: "WORKGROUP",
200: "FILL.GROUP",
201: "UPDATE.LINK",
202: "PROMOTE",
203: "DEMOTE",
204: "SHOW.DETAIL",
206: "UNGROUP",
207: "OBJECT.PROPERTIES",
208: "SAVE.NEW.OBJECT",
209: "SHARE",
210: "SHARE.NAME",
211: "DUPLICATE",
212: "APPLY.STYLE",
213: "ASSIGN.TO.OBJECT",
214: "OBJECT.PROTECTION",
215: "HIDE.OBJECT",
216: "SET.EXTRACT",
217: "CREATE.PUBLISHER",
218: "SUBSCRIBE.TO",
219: "ATTRIBUTES",
220: "SHOW.TOOLBAR",
222: "PRINT.PREVIEW",
223: "EDIT.COLOR",
224: "SHOW.LEVELS",
225: "FORMAT.MAIN",
226: "FORMAT.OVERLAY",
227: "ON.RECALC",
228: "EDIT.SERIES",
229: "DEFINE.STYLE",
240: "LINE.PRINT",
243: "ENTER.DATA",
249: "GALLERY.RADAR",
250: "MERGE.STYLES",
251: "EDITION.OPTIONS",
252: "PASTE.PICTURE",
253: "PASTE.PICTURE.LINK",
254: "SPELLING",
256: "ZOOM",
259: "INSERT.OBJECT",
260: "WINDOW.MINIMIZE",
265: "SOUND.NOTE",
266: "SOUND.PLAY",
267: "FORMAT.SHAPE",
268: "EXTEND.POLYGON",
269: "FORMAT.AUTO",
272: "GALLERY.3D.BAR",
273: "GALLERY.3D.SURFACE",
274: "FILL.AUTO",
276: "CUSTOMIZE.TOOLBAR",
277: "ADD.TOOL",
278: "EDIT.OBJECT",
279: "ON.DOUBLECLICK",
280: "ON.ENTRY",
281: "WORKBOOK.ADD",
282: "WORKBOOK.MOVE",
283: "WORKBOOK.COPY",
284: "WORKBOOK.OPTIONS",
285: "SAVE.WORKSPACE",
288: "CHART.WIZARD",
289: "DELETE.TOOL",
290: "MOVE.TOOL",
291: "WORKBOOK.SELECT",
292: "WORKBOOK.ACTIVATE",
293: "ASSIGN.TO.TOOL",
295: "COPY.TOOL",
296: "RESET.TOOL",
297: "CONSTRAIN.NUMERIC",
298: "PASTE.TOOL",
302: "WORKBOOK.NEW",
305: "SCENARIO.CELLS",
306: "SCENARIO.DELETE",
307: "SCENARIO.ADD",
308: "SCENARIO.EDIT",
309: "SCENARIO.SHOW",
310: "SCENARIO.SHOW.NEXT",
311: "SCENARIO.SUMMARY",
312: "PIVOT.TABLE.WIZARD",
313: "PIVOT.FIELD.PROPERTIES",
314: "PIVOT.FIELD",
315: "PIVOT.ITEM",
316: "PIVOT.ADD.FIELDS",
318: "OPTIONS.CALCULATION",
319: "OPTIONS.EDIT",
320: "OPTIONS.VIEW",
321: "ADDIN.MANAGER",
322: "MENU.EDITOR",
323: "ATTACH.TOOLBARS",
324: "VBAActivate",
325: "OPTIONS.CHART",
328: "VBA.INSERT.FILE",
330: "VBA.PROCEDURE.DEFINITION",
336: "ROUTING.SLIP",
338: "ROUTE.DOCUMENT",
339: "MAIL.LOGON",
342: "INSERT.PICTURE",
343: "EDIT.TOOL",
344: "GALLERY.DOUGHNUT",
350: "CHART.TREND",
352: "PIVOT.ITEM.PROPERTIES",
354: "WORKBOOK.INSERT",
355: "OPTIONS.TRANSITION",
356: "OPTIONS.GENERAL",
370: "FILTER.ADVANCED",
373: "MAIL.ADD.MAILER",
374: "MAIL.DELETE.MAILER",
375: "MAIL.REPLY",
376: "MAIL.REPLY.ALL",
377: "MAIL.FORWARD",
378: "MAIL.NEXT.LETTER",
379: "DATA.LABEL",
380: "INSERT.TITLE",
381: "FONT.PROPERTIES",
382: "MACRO.OPTIONS",
383: "WORKBOOK.HIDE",
384: "WORKBOOK.UNHIDE",
385: "WORKBOOK.DELETE",
386: "WORKBOOK.NAME",
388: "GALLERY.CUSTOM",
390: "ADD.CHART.AUTOFORMAT",
391: "DELETE.CHART.AUTOFORMAT",
392: "CHART.ADD.DATA",
393: "AUTO.OUTLINE",
394: "TAB.ORDER",
395: "SHOW.DIALOG",
396: "SELECT.ALL",
397: "UNGROUP.SHEETS",
398: "SUBTOTAL.CREATE",
399: "SUBTOTAL.REMOVE",
400: "RENAME.OBJECT",
412: "WORKBOOK.SCROLL",
413: "WORKBOOK.NEXT",
414: "WORKBOOK.PREV",
415: "WORKBOOK.TAB.SPLIT",
416: "FULL.SCREEN",
417: "WORKBOOK.PROTECT",
420: "SCROLLBAR.PROPERTIES",
421: "PIVOT.SHOW.PAGES",
422: "TEXT.TO.COLUMNS",
423: "FORMAT.CHARTTYPE",
424: "LINK.FORMAT",
425: "TRACER.DISPLAY",
430: "TRACER.NAVIGATE",
431: "TRACER.CLEAR",
432: "TRACER.ERROR",
433: "PIVOT.FIELD.GROUP",
434: "PIVOT.FIELD.UNGROUP",
435: "CHECKBOX.PROPERTIES",
436: "LABEL.PROPERTIES",
437: "LISTBOX.PROPERTIES",
438: "EDITBOX.PROPERTIES",
439: "PIVOT.REFRESH",
440: "LINK.COMBO",
441: "OPEN.TEXT",
442: "HIDE.DIALOG",
443: "SET.DIALOG.FOCUS",
444: "ENABLE.OBJECT",
445: "PUSHBUTTON.PROPERTIES",
446: "SET.DIALOG.DEFAULT",
447: "FILTER",
448: "FILTER.SHOW.ALL",
449: "CLEAR.OUTLINE",
450: "FUNCTION.WIZARD",
451: "ADD.LIST.ITEM",
452: "SET.LIST.ITEM",
453: "REMOVE.LIST.ITEM",
454: "SELECT.LIST.ITEM",
455: "SET.CONTROL.VALUE",
456: "SAVE.COPY.AS",
458: "OPTIONS.LISTS.ADD",
459: "OPTIONS.LISTS.DELETE",
460: "SERIES.AXES",
461: "SERIES.X",
462: "SERIES.Y",
463: "ERRORBAR.X",
464: "ERRORBAR.Y",
465: "FORMAT.CHART",
466: "SERIES.ORDER",
467: "MAIL.LOGOFF",
468: "CLEAR.ROUTING.SLIP",
469: "APP.ACTIVATE.MICROSOFT",
470: "MAIL.EDIT.MAILER",
471: "ON.SHEET",
472: "STANDARD.WIDTH",
473: "SCENARIO.MERGE",
474: "SUMMARY.INFO",
475: "FIND.FILE",
476: "ACTIVE.CELL.FONT",
477: "ENABLE.TIPWIZARD",
478: "VBA.MAKE.ADDIN",
480: "INSERTDATATABLE",
481: "WORKGROUP.OPTIONS",
482: "MAIL.SEND.MAILER",
485: "AUTOCORRECT",
489: "POST.DOCUMENT",
491: "PICKLIST",
493: "VIEW.SHOW",
494: "VIEW.DEFINE",
495: "VIEW.DELETE",
509: "SHEET.BACKGROUND",
510: "INSERT.MAP.OBJECT",
511: "OPTIONS.MENONO",
517: "MSOCHECKS",
518: "NORMAL",
519: "LAYOUT",
520: "RM.PRINT.AREA",
521: "CLEAR.PRINT.AREA",
522: "ADD.PRINT.AREA",
523: "MOVE.BRK",
545: "HIDECURR.NOTE",
546: "HIDEALL.NOTES",
547: "DELETE.NOTE",
548: "TRAVERSE.NOTES",
549: "ACTIVATE.NOTES",
620: "PROTECT.REVISIONS",
621: "UNPROTECT.REVISIONS",
647: "OPTIONS.ME",
653: "WEB.PUBLISH",
667: "NEWWEBQUERY",
673: "PIVOT.TABLE.CHART",
753: "OPTIONS.SAVE",
755: "OPTIONS.SPELL",
808: "HIDEALL.INKANNOTS"
};
Ftab = {
0: "COUNT",
1: "IF",
2: "ISNA",
3: "ISERROR",
4: "SUM",
5: "AVERAGE",
6: "MIN",
7: "MAX",
8: "ROW",
9: "COLUMN",
10: "NA",
11: "NPV",
12: "STDEV",
13: "DOLLAR",
14: "FIXED",
15: "SIN",
16: "COS",
17: "TAN",
18: "ATAN",
19: "PI",
20: "SQRT",
21: "EXP",
22: "LN",
23: "LOG10",
24: "ABS",
25: "INT",
26: "SIGN",
27: "ROUND",
28: "LOOKUP",
29: "INDEX",
30: "REPT",
31: "MID",
32: "LEN",
33: "VALUE",
34: "TRUE",
35: "FALSE",
36: "AND",
37: "OR",
38: "NOT",
39: "MOD",
40: "DCOUNT",
41: "DSUM",
42: "DAVERAGE",
43: "DMIN",
44: "DMAX",
45: "DSTDEV",
46: "VAR",
47: "DVAR",
48: "TEXT",
49: "LINEST",
50: "TREND",
51: "LOGEST",
52: "GROWTH",
53: "GOTO",
54: "HALT",
55: "RETURN",
56: "PV",
57: "FV",
58: "NPER",
59: "PMT",
60: "RATE",
61: "MIRR",
62: "IRR",
63: "RAND",
64: "MATCH",
65: "DATE",
66: "TIME",
67: "DAY",
68: "MONTH",
69: "YEAR",
70: "WEEKDAY",
71: "HOUR",
72: "MINUTE",
73: "SECOND",
74: "NOW",
75: "AREAS",
76: "ROWS",
77: "COLUMNS",
78: "OFFSET",
79: "ABSREF",
80: "RELREF",
81: "ARGUMENT",
82: "SEARCH",
83: "TRANSPOSE",
84: "ERROR",
85: "STEP",
86: "TYPE",
87: "ECHO",
88: "SET.NAME",
89: "CALLER",
90: "DEREF",
91: "WINDOWS",
92: "SERIES",
93: "DOCUMENTS",
94: "ACTIVE.CELL",
95: "SELECTION",
96: "RESULT",
97: "ATAN2",
98: "ASIN",
99: "ACOS",
100: "CHOOSE",
101: "HLOOKUP",
102: "VLOOKUP",
103: "LINKS",
104: "INPUT",
105: "ISREF",
106: "GET.FORMULA",
107: "GET.NAME",
108: "SET.VALUE",
109: "LOG",
110: "EXEC",
111: "CHAR",
112: "LOWER",
113: "UPPER",
114: "PROPER",
115: "LEFT",
116: "RIGHT",
117: "EXACT",
118: "TRIM",
119: "REPLACE",
120: "SUBSTITUTE",
121: "CODE",
122: "NAMES",
123: "DIRECTORY",
124: "FIND",
125: "CELL",
126: "ISERR",
127: "ISTEXT",
128: "ISNUMBER",
129: "ISBLANK",
130: "T",
131: "N",
132: "FOPEN",
133: "FCLOSE",
134: "FSIZE",
135: "FREADLN",
136: "FREAD",
137: "FWRITELN",
138: "FWRITE",
139: "FPOS",
140: "DATEVALUE",
141: "TIMEVALUE",
142: "SLN",
143: "SYD",
144: "DDB",
145: "GET.DEF",
146: "REFTEXT",
147: "TEXTREF",
148: "INDIRECT",
149: "REGISTER",
150: "CALL",
151: "ADD.BAR",
152: "ADD.MENU",
153: "ADD.COMMAND",
154: "ENABLE.COMMAND",
155: "CHECK.COMMAND",
156: "RENAME.COMMAND",
157: "SHOW.BAR",
158: "DELETE.MENU",
159: "DELETE.COMMAND",
160: "GET.CHART.ITEM",
161: "DIALOG.BOX",
162: "CLEAN",
163: "MDETERM",
164: "MINVERSE",
165: "MMULT",
166: "FILES",
167: "IPMT",
168: "PPMT",
169: "COUNTA",
170: "CANCEL.KEY",
171: "FOR",
172: "WHILE",
173: "BREAK",
174: "NEXT",
175: "INITIATE",
176: "REQUEST",
177: "POKE",
178: "EXECUTE",
179: "TERMINATE",
180: "RESTART",
181: "HELP",
182: "GET.BAR",
183: "PRODUCT",
184: "FACT",
185: "GET.CELL",
186: "GET.WORKSPACE",
187: "GET.WINDOW",
188: "GET.DOCUMENT",
189: "DPRODUCT",
190: "ISNONTEXT",
191: "GET.NOTE",
192: "NOTE",
193: "STDEVP",
194: "VARP",
195: "DSTDEVP",
196: "DVARP",
197: "TRUNC",
198: "ISLOGICAL",
199: "DCOUNTA",
200: "DELETE.BAR",
201: "UNREGISTER",
204: "USDOLLAR",
205: "FINDB",
206: "SEARCHB",
207: "REPLACEB",
208: "LEFTB",
209: "RIGHTB",
210: "MIDB",
211: "LENB",
212: "ROUNDUP",
213: "ROUNDDOWN",
214: "ASC",
215: "DBCS",
216: "RANK",
219: "ADDRESS",
220: "DAYS360",
221: "TODAY",
222: "VDB",
223: "ELSE",
224: "ELSE.IF",
225: "END.IF",
226: "FOR.CELL",
227: "MEDIAN",
228: "SUMPRODUCT",
229: "SINH",
230: "COSH",
231: "TANH",
232: "ASINH",
233: "ACOSH",
234: "ATANH",
235: "DGET",
236: "CREATE.OBJECT",
237: "VOLATILE",
238: "LAST.ERROR",
239: "CUSTOM.UNDO",
240: "CUSTOM.REPEAT",
241: "FORMULA.CONVERT",
242: "GET.LINK.INFO",
243: "TEXT.BOX",
244: "INFO",
245: "GROUP",
246: "GET.OBJECT",
247: "DB",
248: "PAUSE",
251: "RESUME",
252: "FREQUENCY",
253: "ADD.TOOLBAR",
254: "DELETE.TOOLBAR",
255: "User",
256: "RESET.TOOLBAR",
257: "EVALUATE",
258: "GET.TOOLBAR",
259: "GET.TOOL",
260: "SPELLING.CHECK",
261: "ERROR.TYPE",
262: "APP.TITLE",
263: "WINDOW.TITLE",
264: "SAVE.TOOLBAR",
265: "ENABLE.TOOL",
266: "PRESS.TOOL",
267: "REGISTER.ID",
268: "GET.WORKBOOK",
269: "AVEDEV",
270: "BETADIST",
271: "GAMMALN",
272: "BETAINV",
273: "BINOMDIST",
274: "CHIDIST",
275: "CHIINV",
276: "COMBIN",
277: "CONFIDENCE",
278: "CRITBINOM",
279: "EVEN",
280: "EXPONDIST",
281: "FDIST",
282: "FINV",
283: "FISHER",
284: "FISHERINV",
285: "FLOOR",
286: "GAMMADIST",
287: "GAMMAINV",
288: "CEILING",
289: "HYPGEOMDIST",
290: "LOGNORMDIST",
291: "LOGINV",
292: "NEGBINOMDIST",
293: "NORMDIST",
294: "NORMSDIST",
295: "NORMINV",
296: "NORMSINV",
297: "STANDARDIZE",
298: "ODD",
299: "PERMUT",
300: "POISSON",
301: "TDIST",
302: "WEIBULL",
303: "SUMXMY2",
304: "SUMX2MY2",
305: "SUMX2PY2",
306: "CHITEST",
307: "CORREL",
308: "COVAR",
309: "FORECAST",
310: "FTEST",
311: "INTERCEPT",
312: "PEARSON",
313: "RSQ",
314: "STEYX",
315: "SLOPE",
316: "TTEST",
317: "PROB",
318: "DEVSQ",
319: "GEOMEAN",
320: "HARMEAN",
321: "SUMSQ",
322: "KURT",
323: "SKEW",
324: "ZTEST",
325: "LARGE",
326: "SMALL",
327: "QUARTILE",
328: "PERCENTILE",
329: "PERCENTRANK",
330: "MODE",
331: "TRIMMEAN",
332: "TINV",
334: "MOVIE.COMMAND",
335: "GET.MOVIE",
336: "CONCATENATE",
337: "POWER",
338: "PIVOT.ADD.DATA",
339: "GET.PIVOT.TABLE",
340: "GET.PIVOT.FIELD",
341: "GET.PIVOT.ITEM",
342: "RADIANS",
343: "DEGREES",
344: "SUBTOTAL",
345: "SUMIF",
346: "COUNTIF",
347: "COUNTBLANK",
348: "SCENARIO.GET",
349: "OPTIONS.LISTS.GET",
350: "ISPMT",
351: "DATEDIF",
352: "DATESTRING",
353: "NUMBERSTRING",
354: "ROMAN",
355: "OPEN.DIALOG",
356: "SAVE.DIALOG",
357: "VIEW.GET",
358: "GETPIVOTDATA",
359: "HYPERLINK",
360: "PHONETIC",
361: "AVERAGEA",
362: "MAXA",
363: "MINA",
364: "STDEVPA",
365: "VARPA",
366: "STDEVA",
367: "VARA",
368: "BAHTTEXT",
369: "THAIDAYOFWEEK",
370: "THAIDIGIT",
371: "THAIMONTHOFYEAR",
372: "THAINUMSOUND",
373: "THAINUMSTRING",
374: "THAISTRINGLENGTH",
375: "ISTHAIDIGIT",
376: "ROUNDBAHTDOWN",
377: "ROUNDBAHTUP",
378: "THAIYEAR",
379: "RTD",
380: "CUBEVALUE",
381: "CUBEMEMBER",
382: "CUBEMEMBERPROPERTY",
383: "CUBERANKEDMEMBER",
384: "HEX2BIN",
385: "HEX2DEC",
386: "HEX2OCT",
387: "DEC2BIN",
388: "DEC2HEX",
389: "DEC2OCT",
390: "OCT2BIN",
391: "OCT2HEX",
392: "OCT2DEC",
393: "BIN2DEC",
394: "BIN2OCT",
395: "BIN2HEX",
396: "IMSUB",
397: "IMDIV",
398: "IMPOWER",
399: "IMABS",
400: "IMSQRT",
401: "IMLN",
402: "IMLOG2",
403: "IMLOG10",
404: "IMSIN",
405: "IMCOS",
406: "IMEXP",
407: "IMARGUMENT",
408: "IMCONJUGATE",
409: "IMAGINARY",
410: "IMREAL",
411: "COMPLEX",
412: "IMSUM",
413: "IMPRODUCT",
414: "SERIESSUM",
415: "FACTDOUBLE",
416: "SQRTPI",
417: "QUOTIENT",
418: "DELTA",
419: "GESTEP",
420: "ISEVEN",
421: "ISODD",
422: "MROUND",
423: "ERF",
424: "ERFC",
425: "BESSELJ",
426: "BESSELK",
427: "BESSELY",
428: "BESSELI",
429: "XIRR",
430: "XNPV",
431: "PRICEMAT",
432: "YIELDMAT",
433: "INTRATE",
434: "RECEIVED",
435: "DISC",
436: "PRICEDISC",
437: "YIELDDISC",
438: "TBILLEQ",
439: "TBILLPRICE",
440: "TBILLYIELD",
441: "PRICE",
442: "YIELD",
443: "DOLLARDE",
444: "DOLLARFR",
445: "NOMINAL",
446: "EFFECT",
447: "CUMPRINC",
448: "CUMIPMT",
449: "EDATE",
450: "EOMONTH",
451: "YEARFRAC",
452: "COUPDAYBS",
453: "COUPDAYS",
454: "COUPDAYSNC",
455: "COUPNCD",
456: "COUPNUM",
457: "COUPPCD",
458: "DURATION",
459: "MDURATION",
460: "ODDLPRICE",
461: "ODDLYIELD",
462: "ODDFPRICE",
463: "ODDFYIELD",
464: "RANDBETWEEN",
465: "WEEKNUM",
466: "AMORDEGRC",
467: "AMORLINC",
468: "CONVERT",
724: "SHEETJS",
469: "ACCRINT",
470: "ACCRINTM",
471: "WORKDAY",
472: "NETWORKDAYS",
473: "GCD",
474: "MULTINOMIAL",
475: "LCM",
476: "FVSCHEDULE",
477: "CUBEKPIMEMBER",
478: "CUBESET",
479: "CUBESETCOUNT",
480: "IFERROR",
481: "COUNTIFS",
482: "SUMIFS",
483: "AVERAGEIF",
484: "AVERAGEIFS"
};
FtabArgc = {
2: 1,
3: 1,
10: 0,
15: 1,
16: 1,
17: 1,
18: 1,
19: 0,
20: 1,
21: 1,
22: 1,
23: 1,
24: 1,
25: 1,
26: 1,
27: 2,
30: 2,
31: 3,
32: 1,
33: 1,
34: 0,
35: 0,
38: 1,
39: 2,
40: 3,
41: 3,
42: 3,
43: 3,
44: 3,
45: 3,
47: 3,
48: 2,
53: 1,
61: 3,
63: 0,
65: 3,
66: 3,
67: 1,
68: 1,
69: 1,
70: 1,
71: 1,
72: 1,
73: 1,
74: 0,
75: 1,
76: 1,
77: 1,
79: 2,
80: 2,
83: 1,
85: 0,
86: 1,
89: 0,
90: 1,
94: 0,
95: 0,
97: 2,
98: 1,
99: 1,
101: 3,
102: 3,
105: 1,
106: 1,
108: 2,
111: 1,
112: 1,
113: 1,
114: 1,
117: 2,
118: 1,
119: 4,
121: 1,
126: 1,
127: 1,
128: 1,
129: 1,
130: 1,
131: 1,
133: 1,
134: 1,
135: 1,
136: 2,
137: 2,
138: 2,
140: 1,
141: 1,
142: 3,
143: 4,
144: 4,
161: 1,
162: 1,
163: 1,
164: 1,
165: 2,
172: 1,
175: 2,
176: 2,
177: 3,
178: 2,
179: 1,
184: 1,
186: 1,
189: 3,
190: 1,
195: 3,
196: 3,
197: 1,
198: 1,
199: 3,
201: 1,
207: 4,
210: 3,
211: 1,
212: 2,
213: 2,
214: 1,
215: 1,
225: 0,
229: 1,
230: 1,
231: 1,
232: 1,
233: 1,
234: 1,
235: 3,
244: 1,
247: 4,
252: 2,
257: 1,
261: 1,
271: 1,
273: 4,
274: 2,
275: 2,
276: 2,
277: 3,
278: 3,
279: 1,
280: 3,
281: 3,
282: 3,
283: 1,
284: 1,
285: 2,
286: 4,
287: 3,
288: 2,
289: 4,
290: 3,
291: 3,
292: 3,
293: 4,
294: 1,
295: 3,
296: 1,
297: 3,
298: 1,
299: 2,
300: 3,
301: 3,
302: 4,
303: 2,
304: 2,
305: 2,
306: 2,
307: 2,
308: 2,
309: 3,
310: 2,
311: 2,
312: 2,
313: 2,
314: 2,
315: 2,
316: 4,
325: 2,
326: 2,
327: 2,
328: 2,
331: 2,
332: 2,
337: 2,
342: 1,
343: 1,
346: 2,
347: 1,
350: 4,
351: 3,
352: 1,
353: 2,
360: 1,
368: 1,
369: 1,
370: 1,
371: 1,
372: 1,
373: 1,
374: 1,
375: 1,
376: 1,
377: 1,
378: 1,
382: 3,
385: 1,
392: 1,
393: 1,
396: 2,
397: 2,
398: 2,
399: 1,
400: 1,
401: 1,
402: 1,
403: 1,
404: 1,
405: 1,
406: 1,
407: 1,
408: 1,
409: 1,
410: 1,
414: 4,
415: 1,
416: 1,
417: 2,
420: 1,
421: 1,
422: 2,
424: 1,
425: 2,
426: 2,
427: 2,
428: 2,
430: 3,
438: 3,
439: 3,
440: 3,
443: 2,
444: 2,
445: 2,
446: 2,
447: 6,
448: 6,
449: 2,
450: 2,
464: 2,
468: 3,
476: 2,
479: 1,
480: 2,
65535: 0
};
strs = {};
_ssfopts = {};
mergecregex = /<(?:\w+:)?mergeCell ref=["'][A-Z0-9:]+['"]\s*[\/]?>/g;
hlinkregex = /<(?:\w+:)?hyperlink [^<>]*>/mg;
dimregex = /"(\w*:\w*)"/;
colregex = /<(?:\w+:)?col\b[^<>]*[\/]?>/g;
afregex = /<(?:\w+:)?autoFilter[^>]*/g;
marginregex = /<(?:\w+:)?pageMargins[^<>]*\/>/g;
sheetprregex = /<(?:\w+:)?sheetPr\b[^<>]*?\/>/;
sviewregex = /<(?:\w:)?sheetView(?:[^<>a-z][^<>]*)?\/?>/g;
parse_ws_xml_data = /* @__PURE__ */ (function() {
var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/;
var rregex = /r=["']([^"']*)["']/;
var refregex = /ref=["']([^"']*)["']/;
return function parse_ws_xml_data2(sdata, s6, opts, guess, themes, styles2, wb) {
var ri = 0, x2 = "", cells = [], cref = [], idx = 0, i7 = 0, cc = 0, d4 = "", p4;
var tag, tagr = 0, tagc = 0;
var sstr, ftag;
var fmtid = 0, fillid = 0;
var do_format = Array.isArray(styles2.CellXf), cf;
var arrayf = [];
var sharedf = [];
var dense = s6["!data"] != null;
var rows = [], rowobj = {}, rowrite = false;
var sheetStubs = !!opts.sheetStubs;
var date1904 = !!((wb || {}).WBProps || {}).date1904;
for (var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
x2 = marr[mt].trim();
var xlen = x2.length;
if (xlen === 0) continue;
var rstarti = 0;
outa: for (ri = 0; ri < xlen; ++ri) switch (
/*x.charCodeAt(ri)*/
x2[ri]
) {
case ">":
if (
/*x.charCodeAt(ri-1) != 47*/
x2[ri - 1] != "/"
) {
++ri;
break outa;
}
if (opts && opts.cellStyles) {
tag = parsexmltag(x2.slice(rstarti, ri), true);
tagr = tag.r != null ? parseInt(tag.r, 10) : tagr + 1;
tagc = -1;
if (opts.sheetRows && opts.sheetRows < tagr) continue;
rowobj = {};
rowrite = false;
if (tag.ht) {
rowrite = true;
rowobj.hpt = parseFloat(tag.ht);
rowobj.hpx = pt2px(rowobj.hpt);
}
if (tag.hidden && parsexmlbool(tag.hidden)) {
rowrite = true;
rowobj.hidden = true;
}
if (tag.outlineLevel != null) {
rowrite = true;
rowobj.level = +tag.outlineLevel;
}
if (rowrite) rows[tagr - 1] = rowobj;
}
break;
case "<":
rstarti = ri;
break;
}
if (rstarti >= ri) break;
tag = parsexmltag(x2.slice(rstarti, ri), true);
tagr = tag.r != null ? parseInt(tag.r, 10) : tagr + 1;
tagc = -1;
if (opts.sheetRows && opts.sheetRows < tagr) continue;
if (!opts.nodim) {
if (guess.s.r > tagr - 1) guess.s.r = tagr - 1;
if (guess.e.r < tagr - 1) guess.e.r = tagr - 1;
}
if (opts && opts.cellStyles) {
rowobj = {};
rowrite = false;
if (tag.ht) {
rowrite = true;
rowobj.hpt = parseFloat(tag.ht);
rowobj.hpx = pt2px(rowobj.hpt);
}
if (tag.hidden && parsexmlbool(tag.hidden)) {
rowrite = true;
rowobj.hidden = true;
}
if (tag.outlineLevel != null) {
rowrite = true;
rowobj.level = +tag.outlineLevel;
}
if (rowrite) rows[tagr - 1] = rowobj;
}
cells = x2.slice(ri).split(cellregex);
for (var rslice = 0; rslice != cells.length; ++rslice) if (cells[rslice].trim().charAt(0) != "<") break;
cells = cells.slice(rslice);
for (ri = 0; ri != cells.length; ++ri) {
x2 = cells[ri].trim();
if (x2.length === 0) continue;
cref = x2.match(rregex);
idx = ri;
i7 = 0;
cc = 0;
x2 = "" : "") + x2;
if (cref != null && cref.length === 2) {
idx = 0;
d4 = cref[1];
for (i7 = 0; i7 != d4.length; ++i7) {
if ((cc = d4.charCodeAt(i7) - 64) < 1 || cc > 26) break;
idx = 26 * idx + cc;
}
--idx;
tagc = idx;
} else ++tagc;
for (i7 = 0; i7 != x2.length; ++i7) if (x2.charCodeAt(i7) === 62) break;
++i7;
tag = parsexmltag(x2.slice(0, i7), true);
if (!tag.r) tag.r = encode_cell({ r: tagr - 1, c: tagc });
d4 = x2.slice(i7);
p4 = { t: "" };
if ((cref = str_match_xml_ns(d4, "v")) != null && /*::cref != null && */
cref[1] !== "") p4.v = unescapexml(cref[1]);
if (opts.cellFormula) {
if ((cref = str_match_xml_ns(d4, "f")) != null) {
if (cref[1] == "") {
if (
/*::cref != null && cref[0] != null && */
cref[0].indexOf('t="shared"') > -1
) {
ftag = parsexmltag(cref[0]);
if (sharedf[ftag.si]) p4.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2], tag.r);
}
} else {
p4.f = unescapexml(utf8read(cref[1]), true);
if (!opts.xlfn) p4.f = _xlfn(p4.f);
if (
/*::cref != null && cref[0] != null && */
cref[0].indexOf('t="array"') > -1
) {
p4.F = (d4.match(refregex) || [])[1];
if (p4.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p4.F), p4.F]);
} else if (
/*::cref != null && cref[0] != null && */
cref[0].indexOf('t="shared"') > -1
) {
ftag = parsexmltag(cref[0]);
var ___f = unescapexml(utf8read(cref[1]));
if (!opts.xlfn) ___f = _xlfn(___f);
sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r];
}
}
} else if (cref = d4.match(/]*\/>/)) {
ftag = parsexmltag(cref[0]);
if (sharedf[ftag.si]) p4.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2], tag.r);
}
var _tag = decode_cell(tag.r);
for (i7 = 0; i7 < arrayf.length; ++i7)
if (_tag.r >= arrayf[i7][0].s.r && _tag.r <= arrayf[i7][0].e.r) {
if (_tag.c >= arrayf[i7][0].s.c && _tag.c <= arrayf[i7][0].e.c)
p4.F = arrayf[i7][1];
}
}
if (tag.t == null && p4.v === void 0) {
if (p4.f || p4.F) {
p4.v = 0;
p4.t = "n";
} else if (!sheetStubs) continue;
else p4.t = "z";
} else p4.t = tag.t || "n";
if (guess.s.c > tagc) guess.s.c = tagc;
if (guess.e.c < tagc) guess.e.c = tagc;
switch (p4.t) {
case "n":
if (p4.v == "" || p4.v == null) {
if (!sheetStubs) continue;
p4.t = "z";
} else p4.v = parseFloat(p4.v);
break;
case "s":
if (typeof p4.v == "undefined") {
if (!sheetStubs) continue;
p4.t = "z";
} else {
sstr = strs[parseInt(p4.v, 10)];
p4.v = sstr.t;
p4.r = sstr.r;
if (opts.cellHTML) p4.h = sstr.h;
}
break;
case "str":
p4.t = "s";
p4.v = p4.v != null ? unescapexml(utf8read(p4.v), true) : "";
if (opts.cellHTML) p4.h = escapehtml(p4.v);
break;
case "inlineStr":
cref = str_match_xml_ns(d4, "is");
p4.t = "s";
if (cref != null && (sstr = parse_si(cref[1]))) {
p4.v = sstr.t;
if (opts.cellHTML) p4.h = sstr.h;
} else p4.v = "";
break;
case "b":
p4.v = parsexmlbool(p4.v);
break;
case "d":
if (opts.cellDates) p4.v = parseDate(p4.v, date1904);
else {
p4.v = datenum(parseDate(p4.v, date1904), date1904);
p4.t = "n";
}
break;
/* error string in .w, number in .v */
case "e":
if (!opts || opts.cellText !== false) p4.w = p4.v;
p4.v = RBErr[p4.v];
break;
}
fmtid = fillid = 0;
cf = null;
if (do_format && tag.s !== void 0) {
cf = styles2.CellXf[tag.s];
if (cf != null) {
if (cf.numFmtId != null) fmtid = cf.numFmtId;
if (opts.cellStyles) {
if (cf.fillId != null) fillid = cf.fillId;
}
}
}
safe_format(p4, fmtid, fillid, opts, themes, styles2, date1904);
if (opts.cellDates && do_format && p4.t == "n" && fmt_is_date(table_fmt[fmtid])) {
p4.v = numdate(p4.v + (date1904 ? 1462 : 0));
p4.t = typeof p4.v == "number" ? "n" : "d";
}
if (tag.cm && opts.xlmeta) {
var cm = (opts.xlmeta.Cell || [])[+tag.cm - 1];
if (cm && cm.type == "XLDAPR") p4.D = true;
}
var _r;
if (opts.nodim) {
_r = decode_cell(tag.r);
if (guess.s.r > _r.r) guess.s.r = _r.r;
if (guess.e.r < _r.r) guess.e.r = _r.r;
}
if (dense) {
_r = decode_cell(tag.r);
if (!s6["!data"][_r.r]) s6["!data"][_r.r] = [];
s6["!data"][_r.r][_r.c] = p4;
} else s6[tag.r] = p4;
}
}
if (rows.length > 0) s6["!rows"] = rows;
};
})();
parse_BrtWsDim = parse_UncheckedRfX;
parse_BrtMergeCell = parse_UncheckedRfX;
BrtMarginKeys = ["left", "right", "top", "bottom", "header", "footer"];
WBPropsDef = [
["allowRefreshQuery", false, "bool"],
["autoCompressPictures", true, "bool"],
["backupFile", false, "bool"],
["checkCompatibility", false, "bool"],
["CodeName", ""],
["date1904", false, "bool"],
["defaultThemeVersion", 0, "int"],
["filterPrivacy", false, "bool"],
["hidePivotFieldList", false, "bool"],
["promptedSolutions", false, "bool"],
["publishItems", false, "bool"],
["refreshAllConnections", false, "bool"],
["saveExternalLinkValues", true, "bool"],
["showBorderUnselectedTables", true, "bool"],
["showInkAnnotation", true, "bool"],
["showObjects", "all"],
["showPivotChartFilter", false, "bool"],
["updateLinks", "userSet"]
];
WBViewDef = [
["activeTab", 0, "int"],
["autoFilterDateGrouping", true, "bool"],
["firstSheet", 0, "int"],
["minimized", false, "bool"],
["showHorizontalScroll", true, "bool"],
["showSheetTabs", true, "bool"],
["showVerticalScroll", true, "bool"],
["tabRatio", 600, "int"],
["visibility", "visible"]
//window{Height,Width}, {x,y}Window
];
SheetDef = [
//['state', 'visible']
];
CalcPrDef = [
["calcCompleted", "true"],
["calcMode", "auto"],
["calcOnSave", "true"],
["concurrentCalc", "true"],
["fullCalcOnLoad", "false"],
["fullPrecision", "true"],
["iterate", "false"],
["iterateCount", "100"],
["iterateDelta", "0.001"],
["refMode", "A1"]
];
badchars = /* @__PURE__ */ ":][*?/\\".split("");
wbnsregex = /<\w+:workbook/;
attregexg2 = /\b((?:\w+:)?[\w]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:'))/g;
attregex2 = /\b((?:\w+:)?[\w]+)=((?:")(?:[^"]*)(?:")|(?:')(?:[^']*)(?:'))/;
CONTINUE_RT = [60, 1084, 2066, 2165, 2175];
PSCLSID = {
SI: "e0859ff2f94f6810ab9108002b27b3d9",
DSI: "02d5cdd59c2e1b10939708002b2cf9ae",
UDI: "05d5cdd59c2e1b10939708002b2cf9ae"
};
XLSBRecordEnum = {
0: {
/* n:"BrtRowHdr", */
f: parse_BrtRowHdr
},
1: {
/* n:"BrtCellBlank", */
f: parse_BrtCellBlank
},
2: {
/* n:"BrtCellRk", */
f: parse_BrtCellRk
},
3: {
/* n:"BrtCellError", */
f: parse_BrtCellError
},
4: {
/* n:"BrtCellBool", */
f: parse_BrtCellBool
},
5: {
/* n:"BrtCellReal", */
f: parse_BrtCellReal
},
6: {
/* n:"BrtCellSt", */
f: parse_BrtCellSt
},
7: {
/* n:"BrtCellIsst", */
f: parse_BrtCellIsst
},
8: {
/* n:"BrtFmlaString", */
f: parse_BrtFmlaString
},
9: {
/* n:"BrtFmlaNum", */
f: parse_BrtFmlaNum
},
10: {
/* n:"BrtFmlaBool", */
f: parse_BrtFmlaBool
},
11: {
/* n:"BrtFmlaError", */
f: parse_BrtFmlaError
},
12: {
/* n:"BrtShortBlank", */
f: parse_BrtShortBlank
},
13: {
/* n:"BrtShortRk", */
f: parse_BrtShortRk
},
14: {
/* n:"BrtShortError", */
f: parse_BrtShortError
},
15: {
/* n:"BrtShortBool", */
f: parse_BrtShortBool
},
16: {
/* n:"BrtShortReal", */
f: parse_BrtShortReal
},
17: {
/* n:"BrtShortSt", */
f: parse_BrtShortSt
},
18: {
/* n:"BrtShortIsst", */
f: parse_BrtShortIsst
},
19: {
/* n:"BrtSSTItem", */
f: parse_RichStr
},
20: {
/* n:"BrtPCDIMissing" */
},
21: {
/* n:"BrtPCDINumber" */
},
22: {
/* n:"BrtPCDIBoolean" */
},
23: {
/* n:"BrtPCDIError" */
},
24: {
/* n:"BrtPCDIString" */
},
25: {
/* n:"BrtPCDIDatetime" */
},
26: {
/* n:"BrtPCDIIndex" */
},
27: {
/* n:"BrtPCDIAMissing" */
},
28: {
/* n:"BrtPCDIANumber" */
},
29: {
/* n:"BrtPCDIABoolean" */
},
30: {
/* n:"BrtPCDIAError" */
},
31: {
/* n:"BrtPCDIAString" */
},
32: {
/* n:"BrtPCDIADatetime" */
},
33: {
/* n:"BrtPCRRecord" */
},
34: {
/* n:"BrtPCRRecordDt" */
},
35: {
/* n:"BrtFRTBegin", */
T: 1
},
36: {
/* n:"BrtFRTEnd", */
T: -1
},
37: {
/* n:"BrtACBegin", */
T: 1
},
38: {
/* n:"BrtACEnd", */
T: -1
},
39: {
/* n:"BrtName", */
f: parse_BrtName
},
40: {
/* n:"BrtIndexRowBlock" */
},
42: {
/* n:"BrtIndexBlock" */
},
43: {
/* n:"BrtFont", */
f: parse_BrtFont
},
44: {
/* n:"BrtFmt", */
f: parse_BrtFmt
},
45: {
/* n:"BrtFill", */
f: parse_BrtFill
},
46: {
/* n:"BrtBorder", */
f: parse_BrtBorder
},
47: {
/* n:"BrtXF", */
f: parse_BrtXF
},
48: {
/* n:"BrtStyle" */
},
49: {
/* n:"BrtCellMeta", */
f: parse_Int32LE
},
50: {
/* n:"BrtValueMeta" */
},
51: {
/* n:"BrtMdb" */
f: parse_BrtMdb
},
52: {
/* n:"BrtBeginFmd", */
T: 1
},
53: {
/* n:"BrtEndFmd", */
T: -1
},
54: {
/* n:"BrtBeginMdx", */
T: 1
},
55: {
/* n:"BrtEndMdx", */
T: -1
},
56: {
/* n:"BrtBeginMdxTuple", */
T: 1
},
57: {
/* n:"BrtEndMdxTuple", */
T: -1
},
58: {
/* n:"BrtMdxMbrIstr" */
},
59: {
/* n:"BrtStr" */
},
60: {
/* n:"BrtColInfo", */
f: parse_ColInfo
},
62: {
/* n:"BrtCellRString", */
f: parse_BrtCellRString
},
63: {
/* n:"BrtCalcChainItem$", */
f: parse_BrtCalcChainItem$
},
64: {
/* n:"BrtDVal", */
f: parse_BrtDVal
},
65: {
/* n:"BrtSxvcellNum" */
},
66: {
/* n:"BrtSxvcellStr" */
},
67: {
/* n:"BrtSxvcellBool" */
},
68: {
/* n:"BrtSxvcellErr" */
},
69: {
/* n:"BrtSxvcellDate" */
},
70: {
/* n:"BrtSxvcellNil" */
},
128: {
/* n:"BrtFileVersion" */
},
129: {
/* n:"BrtBeginSheet", */
T: 1
},
130: {
/* n:"BrtEndSheet", */
T: -1
},
131: {
/* n:"BrtBeginBook", */
T: 1,
f: parsenoop,
p: 0
},
132: {
/* n:"BrtEndBook", */
T: -1
},
133: {
/* n:"BrtBeginWsViews", */
T: 1
},
134: {
/* n:"BrtEndWsViews", */
T: -1
},
135: {
/* n:"BrtBeginBookViews", */
T: 1
},
136: {
/* n:"BrtEndBookViews", */
T: -1
},
137: {
/* n:"BrtBeginWsView", */
T: 1,
f: parse_BrtBeginWsView
},
138: {
/* n:"BrtEndWsView", */
T: -1
},
139: {
/* n:"BrtBeginCsViews", */
T: 1
},
140: {
/* n:"BrtEndCsViews", */
T: -1
},
141: {
/* n:"BrtBeginCsView", */
T: 1
},
142: {
/* n:"BrtEndCsView", */
T: -1
},
143: {
/* n:"BrtBeginBundleShs", */
T: 1
},
144: {
/* n:"BrtEndBundleShs", */
T: -1
},
145: {
/* n:"BrtBeginSheetData", */
T: 1
},
146: {
/* n:"BrtEndSheetData", */
T: -1
},
147: {
/* n:"BrtWsProp", */
f: parse_BrtWsProp
},
148: {
/* n:"BrtWsDim", */
f: parse_BrtWsDim,
p: 16
},
151: {
/* n:"BrtPane", */
f: parse_BrtPane
},
152: {
/* n:"BrtSel" */
},
153: {
/* n:"BrtWbProp", */
f: parse_BrtWbProp
},
154: {
/* n:"BrtWbFactoid" */
},
155: {
/* n:"BrtFileRecover" */
},
156: {
/* n:"BrtBundleSh", */
f: parse_BrtBundleSh
},
157: {
/* n:"BrtCalcProp" */
},
158: {
/* n:"BrtBookView" */
},
159: {
/* n:"BrtBeginSst", */
T: 1,
f: parse_BrtBeginSst
},
160: {
/* n:"BrtEndSst", */
T: -1
},
161: {
/* n:"BrtBeginAFilter", */
T: 1,
f: parse_UncheckedRfX
},
162: {
/* n:"BrtEndAFilter", */
T: -1
},
163: {
/* n:"BrtBeginFilterColumn", */
T: 1
},
164: {
/* n:"BrtEndFilterColumn", */
T: -1
},
165: {
/* n:"BrtBeginFilters", */
T: 1
},
166: {
/* n:"BrtEndFilters", */
T: -1
},
167: {
/* n:"BrtFilter" */
},
168: {
/* n:"BrtColorFilter" */
},
169: {
/* n:"BrtIconFilter" */
},
170: {
/* n:"BrtTop10Filter" */
},
171: {
/* n:"BrtDynamicFilter" */
},
172: {
/* n:"BrtBeginCustomFilters", */
T: 1
},
173: {
/* n:"BrtEndCustomFilters", */
T: -1
},
174: {
/* n:"BrtCustomFilter" */
},
175: {
/* n:"BrtAFilterDateGroupItem" */
},
176: {
/* n:"BrtMergeCell", */
f: parse_BrtMergeCell
},
177: {
/* n:"BrtBeginMergeCells", */
T: 1
},
178: {
/* n:"BrtEndMergeCells", */
T: -1
},
179: {
/* n:"BrtBeginPivotCacheDef", */
T: 1
},
180: {
/* n:"BrtEndPivotCacheDef", */
T: -1
},
181: {
/* n:"BrtBeginPCDFields", */
T: 1
},
182: {
/* n:"BrtEndPCDFields", */
T: -1
},
183: {
/* n:"BrtBeginPCDField", */
T: 1
},
184: {
/* n:"BrtEndPCDField", */
T: -1
},
185: {
/* n:"BrtBeginPCDSource", */
T: 1
},
186: {
/* n:"BrtEndPCDSource", */
T: -1
},
187: {
/* n:"BrtBeginPCDSRange", */
T: 1
},
188: {
/* n:"BrtEndPCDSRange", */
T: -1
},
189: {
/* n:"BrtBeginPCDFAtbl", */
T: 1
},
190: {
/* n:"BrtEndPCDFAtbl", */
T: -1
},
191: {
/* n:"BrtBeginPCDIRun", */
T: 1
},
192: {
/* n:"BrtEndPCDIRun", */
T: -1
},
193: {
/* n:"BrtBeginPivotCacheRecords", */
T: 1
},
194: {
/* n:"BrtEndPivotCacheRecords", */
T: -1
},
195: {
/* n:"BrtBeginPCDHierarchies", */
T: 1
},
196: {
/* n:"BrtEndPCDHierarchies", */
T: -1
},
197: {
/* n:"BrtBeginPCDHierarchy", */
T: 1
},
198: {
/* n:"BrtEndPCDHierarchy", */
T: -1
},
199: {
/* n:"BrtBeginPCDHFieldsUsage", */
T: 1
},
200: {
/* n:"BrtEndPCDHFieldsUsage", */
T: -1
},
201: {
/* n:"BrtBeginExtConnection", */
T: 1
},
202: {
/* n:"BrtEndExtConnection", */
T: -1
},
203: {
/* n:"BrtBeginECDbProps", */
T: 1
},
204: {
/* n:"BrtEndECDbProps", */
T: -1
},
205: {
/* n:"BrtBeginECOlapProps", */
T: 1
},
206: {
/* n:"BrtEndECOlapProps", */
T: -1
},
207: {
/* n:"BrtBeginPCDSConsol", */
T: 1
},
208: {
/* n:"BrtEndPCDSConsol", */
T: -1
},
209: {
/* n:"BrtBeginPCDSCPages", */
T: 1
},
210: {
/* n:"BrtEndPCDSCPages", */
T: -1
},
211: {
/* n:"BrtBeginPCDSCPage", */
T: 1
},
212: {
/* n:"BrtEndPCDSCPage", */
T: -1
},
213: {
/* n:"BrtBeginPCDSCPItem", */
T: 1
},
214: {
/* n:"BrtEndPCDSCPItem", */
T: -1
},
215: {
/* n:"BrtBeginPCDSCSets", */
T: 1
},
216: {
/* n:"BrtEndPCDSCSets", */
T: -1
},
217: {
/* n:"BrtBeginPCDSCSet", */
T: 1
},
218: {
/* n:"BrtEndPCDSCSet", */
T: -1
},
219: {
/* n:"BrtBeginPCDFGroup", */
T: 1
},
220: {
/* n:"BrtEndPCDFGroup", */
T: -1
},
221: {
/* n:"BrtBeginPCDFGItems", */
T: 1
},
222: {
/* n:"BrtEndPCDFGItems", */
T: -1
},
223: {
/* n:"BrtBeginPCDFGRange", */
T: 1
},
224: {
/* n:"BrtEndPCDFGRange", */
T: -1
},
225: {
/* n:"BrtBeginPCDFGDiscrete", */
T: 1
},
226: {
/* n:"BrtEndPCDFGDiscrete", */
T: -1
},
227: {
/* n:"BrtBeginPCDSDTupleCache", */
T: 1
},
228: {
/* n:"BrtEndPCDSDTupleCache", */
T: -1
},
229: {
/* n:"BrtBeginPCDSDTCEntries", */
T: 1
},
230: {
/* n:"BrtEndPCDSDTCEntries", */
T: -1
},
231: {
/* n:"BrtBeginPCDSDTCEMembers", */
T: 1
},
232: {
/* n:"BrtEndPCDSDTCEMembers", */
T: -1
},
233: {
/* n:"BrtBeginPCDSDTCEMember", */
T: 1
},
234: {
/* n:"BrtEndPCDSDTCEMember", */
T: -1
},
235: {
/* n:"BrtBeginPCDSDTCQueries", */
T: 1
},
236: {
/* n:"BrtEndPCDSDTCQueries", */
T: -1
},
237: {
/* n:"BrtBeginPCDSDTCQuery", */
T: 1
},
238: {
/* n:"BrtEndPCDSDTCQuery", */
T: -1
},
239: {
/* n:"BrtBeginPCDSDTCSets", */
T: 1
},
240: {
/* n:"BrtEndPCDSDTCSets", */
T: -1
},
241: {
/* n:"BrtBeginPCDSDTCSet", */
T: 1
},
242: {
/* n:"BrtEndPCDSDTCSet", */
T: -1
},
243: {
/* n:"BrtBeginPCDCalcItems", */
T: 1
},
244: {
/* n:"BrtEndPCDCalcItems", */
T: -1
},
245: {
/* n:"BrtBeginPCDCalcItem", */
T: 1
},
246: {
/* n:"BrtEndPCDCalcItem", */
T: -1
},
247: {
/* n:"BrtBeginPRule", */
T: 1
},
248: {
/* n:"BrtEndPRule", */
T: -1
},
249: {
/* n:"BrtBeginPRFilters", */
T: 1
},
250: {
/* n:"BrtEndPRFilters", */
T: -1
},
251: {
/* n:"BrtBeginPRFilter", */
T: 1
},
252: {
/* n:"BrtEndPRFilter", */
T: -1
},
253: {
/* n:"BrtBeginPNames", */
T: 1
},
254: {
/* n:"BrtEndPNames", */
T: -1
},
255: {
/* n:"BrtBeginPName", */
T: 1
},
256: {
/* n:"BrtEndPName", */
T: -1
},
257: {
/* n:"BrtBeginPNPairs", */
T: 1
},
258: {
/* n:"BrtEndPNPairs", */
T: -1
},
259: {
/* n:"BrtBeginPNPair", */
T: 1
},
260: {
/* n:"BrtEndPNPair", */
T: -1
},
261: {
/* n:"BrtBeginECWebProps", */
T: 1
},
262: {
/* n:"BrtEndECWebProps", */
T: -1
},
263: {
/* n:"BrtBeginEcWpTables", */
T: 1
},
264: {
/* n:"BrtEndECWPTables", */
T: -1
},
265: {
/* n:"BrtBeginECParams", */
T: 1
},
266: {
/* n:"BrtEndECParams", */
T: -1
},
267: {
/* n:"BrtBeginECParam", */
T: 1
},
268: {
/* n:"BrtEndECParam", */
T: -1
},
269: {
/* n:"BrtBeginPCDKPIs", */
T: 1
},
270: {
/* n:"BrtEndPCDKPIs", */
T: -1
},
271: {
/* n:"BrtBeginPCDKPI", */
T: 1
},
272: {
/* n:"BrtEndPCDKPI", */
T: -1
},
273: {
/* n:"BrtBeginDims", */
T: 1
},
274: {
/* n:"BrtEndDims", */
T: -1
},
275: {
/* n:"BrtBeginDim", */
T: 1
},
276: {
/* n:"BrtEndDim", */
T: -1
},
277: {
/* n:"BrtIndexPartEnd" */
},
278: {
/* n:"BrtBeginStyleSheet", */
T: 1
},
279: {
/* n:"BrtEndStyleSheet", */
T: -1
},
280: {
/* n:"BrtBeginSXView", */
T: 1
},
281: {
/* n:"BrtEndSXVI", */
T: -1
},
282: {
/* n:"BrtBeginSXVI", */
T: 1
},
283: {
/* n:"BrtBeginSXVIs", */
T: 1
},
284: {
/* n:"BrtEndSXVIs", */
T: -1
},
285: {
/* n:"BrtBeginSXVD", */
T: 1
},
286: {
/* n:"BrtEndSXVD", */
T: -1
},
287: {
/* n:"BrtBeginSXVDs", */
T: 1
},
288: {
/* n:"BrtEndSXVDs", */
T: -1
},
289: {
/* n:"BrtBeginSXPI", */
T: 1
},
290: {
/* n:"BrtEndSXPI", */
T: -1
},
291: {
/* n:"BrtBeginSXPIs", */
T: 1
},
292: {
/* n:"BrtEndSXPIs", */
T: -1
},
293: {
/* n:"BrtBeginSXDI", */
T: 1
},
294: {
/* n:"BrtEndSXDI", */
T: -1
},
295: {
/* n:"BrtBeginSXDIs", */
T: 1
},
296: {
/* n:"BrtEndSXDIs", */
T: -1
},
297: {
/* n:"BrtBeginSXLI", */
T: 1
},
298: {
/* n:"BrtEndSXLI", */
T: -1
},
299: {
/* n:"BrtBeginSXLIRws", */
T: 1
},
300: {
/* n:"BrtEndSXLIRws", */
T: -1
},
301: {
/* n:"BrtBeginSXLICols", */
T: 1
},
302: {
/* n:"BrtEndSXLICols", */
T: -1
},
303: {
/* n:"BrtBeginSXFormat", */
T: 1
},
304: {
/* n:"BrtEndSXFormat", */
T: -1
},
305: {
/* n:"BrtBeginSXFormats", */
T: 1
},
306: {
/* n:"BrtEndSxFormats", */
T: -1
},
307: {
/* n:"BrtBeginSxSelect", */
T: 1
},
308: {
/* n:"BrtEndSxSelect", */
T: -1
},
309: {
/* n:"BrtBeginISXVDRws", */
T: 1
},
310: {
/* n:"BrtEndISXVDRws", */
T: -1
},
311: {
/* n:"BrtBeginISXVDCols", */
T: 1
},
312: {
/* n:"BrtEndISXVDCols", */
T: -1
},
313: {
/* n:"BrtEndSXLocation", */
T: -1
},
314: {
/* n:"BrtBeginSXLocation", */
T: 1
},
315: {
/* n:"BrtEndSXView", */
T: -1
},
316: {
/* n:"BrtBeginSXTHs", */
T: 1
},
317: {
/* n:"BrtEndSXTHs", */
T: -1
},
318: {
/* n:"BrtBeginSXTH", */
T: 1
},
319: {
/* n:"BrtEndSXTH", */
T: -1
},
320: {
/* n:"BrtBeginISXTHRws", */
T: 1
},
321: {
/* n:"BrtEndISXTHRws", */
T: -1
},
322: {
/* n:"BrtBeginISXTHCols", */
T: 1
},
323: {
/* n:"BrtEndISXTHCols", */
T: -1
},
324: {
/* n:"BrtBeginSXTDMPS", */
T: 1
},
325: {
/* n:"BrtEndSXTDMPs", */
T: -1
},
326: {
/* n:"BrtBeginSXTDMP", */
T: 1
},
327: {
/* n:"BrtEndSXTDMP", */
T: -1
},
328: {
/* n:"BrtBeginSXTHItems", */
T: 1
},
329: {
/* n:"BrtEndSXTHItems", */
T: -1
},
330: {
/* n:"BrtBeginSXTHItem", */
T: 1
},
331: {
/* n:"BrtEndSXTHItem", */
T: -1
},
332: {
/* n:"BrtBeginMetadata", */
T: 1
},
333: {
/* n:"BrtEndMetadata", */
T: -1
},
334: {
/* n:"BrtBeginEsmdtinfo", */
T: 1
},
335: {
/* n:"BrtMdtinfo", */
f: parse_BrtMdtinfo
},
336: {
/* n:"BrtEndEsmdtinfo", */
T: -1
},
337: {
/* n:"BrtBeginEsmdb", */
f: parse_BrtBeginEsmdb,
T: 1
},
338: {
/* n:"BrtEndEsmdb", */
T: -1
},
339: {
/* n:"BrtBeginEsfmd", */
T: 1
},
340: {
/* n:"BrtEndEsfmd", */
T: -1
},
341: {
/* n:"BrtBeginSingleCells", */
T: 1
},
342: {
/* n:"BrtEndSingleCells", */
T: -1
},
343: {
/* n:"BrtBeginList", */
T: 1
},
344: {
/* n:"BrtEndList", */
T: -1
},
345: {
/* n:"BrtBeginListCols", */
T: 1
},
346: {
/* n:"BrtEndListCols", */
T: -1
},
347: {
/* n:"BrtBeginListCol", */
T: 1
},
348: {
/* n:"BrtEndListCol", */
T: -1
},
349: {
/* n:"BrtBeginListXmlCPr", */
T: 1
},
350: {
/* n:"BrtEndListXmlCPr", */
T: -1
},
351: {
/* n:"BrtListCCFmla" */
},
352: {
/* n:"BrtListTrFmla" */
},
353: {
/* n:"BrtBeginExternals", */
T: 1
},
354: {
/* n:"BrtEndExternals", */
T: -1
},
355: {
/* n:"BrtSupBookSrc", */
f: parse_RelID
},
357: {
/* n:"BrtSupSelf" */
},
358: {
/* n:"BrtSupSame" */
},
359: {
/* n:"BrtSupTabs" */
},
360: {
/* n:"BrtBeginSupBook", */
T: 1
},
361: {
/* n:"BrtPlaceholderName" */
},
362: {
/* n:"BrtExternSheet", */
f: parse_ExternSheet
},
363: {
/* n:"BrtExternTableStart" */
},
364: {
/* n:"BrtExternTableEnd" */
},
366: {
/* n:"BrtExternRowHdr" */
},
367: {
/* n:"BrtExternCellBlank" */
},
368: {
/* n:"BrtExternCellReal" */
},
369: {
/* n:"BrtExternCellBool" */
},
370: {
/* n:"BrtExternCellError" */
},
371: {
/* n:"BrtExternCellString" */
},
372: {
/* n:"BrtBeginEsmdx", */
T: 1
},
373: {
/* n:"BrtEndEsmdx", */
T: -1
},
374: {
/* n:"BrtBeginMdxSet", */
T: 1
},
375: {
/* n:"BrtEndMdxSet", */
T: -1
},
376: {
/* n:"BrtBeginMdxMbrProp", */
T: 1
},
377: {
/* n:"BrtEndMdxMbrProp", */
T: -1
},
378: {
/* n:"BrtBeginMdxKPI", */
T: 1
},
379: {
/* n:"BrtEndMdxKPI", */
T: -1
},
380: {
/* n:"BrtBeginEsstr", */
T: 1
},
381: {
/* n:"BrtEndEsstr", */
T: -1
},
382: {
/* n:"BrtBeginPRFItem", */
T: 1
},
383: {
/* n:"BrtEndPRFItem", */
T: -1
},
384: {
/* n:"BrtBeginPivotCacheIDs", */
T: 1
},
385: {
/* n:"BrtEndPivotCacheIDs", */
T: -1
},
386: {
/* n:"BrtBeginPivotCacheID", */
T: 1
},
387: {
/* n:"BrtEndPivotCacheID", */
T: -1
},
388: {
/* n:"BrtBeginISXVIs", */
T: 1
},
389: {
/* n:"BrtEndISXVIs", */
T: -1
},
390: {
/* n:"BrtBeginColInfos", */
T: 1
},
391: {
/* n:"BrtEndColInfos", */
T: -1
},
392: {
/* n:"BrtBeginRwBrk", */
T: 1
},
393: {
/* n:"BrtEndRwBrk", */
T: -1
},
394: {
/* n:"BrtBeginColBrk", */
T: 1
},
395: {
/* n:"BrtEndColBrk", */
T: -1
},
396: {
/* n:"BrtBrk" */
},
397: {
/* n:"BrtUserBookView" */
},
398: {
/* n:"BrtInfo" */
},
399: {
/* n:"BrtCUsr" */
},
400: {
/* n:"BrtUsr" */
},
401: {
/* n:"BrtBeginUsers", */
T: 1
},
403: {
/* n:"BrtEOF" */
},
404: {
/* n:"BrtUCR" */
},
405: {
/* n:"BrtRRInsDel" */
},
406: {
/* n:"BrtRREndInsDel" */
},
407: {
/* n:"BrtRRMove" */
},
408: {
/* n:"BrtRREndMove" */
},
409: {
/* n:"BrtRRChgCell" */
},
410: {
/* n:"BrtRREndChgCell" */
},
411: {
/* n:"BrtRRHeader" */
},
412: {
/* n:"BrtRRUserView" */
},
413: {
/* n:"BrtRRRenSheet" */
},
414: {
/* n:"BrtRRInsertSh" */
},
415: {
/* n:"BrtRRDefName" */
},
416: {
/* n:"BrtRRNote" */
},
417: {
/* n:"BrtRRConflict" */
},
418: {
/* n:"BrtRRTQSIF" */
},
419: {
/* n:"BrtRRFormat" */
},
420: {
/* n:"BrtRREndFormat" */
},
421: {
/* n:"BrtRRAutoFmt" */
},
422: {
/* n:"BrtBeginUserShViews", */
T: 1
},
423: {
/* n:"BrtBeginUserShView", */
T: 1
},
424: {
/* n:"BrtEndUserShView", */
T: -1
},
425: {
/* n:"BrtEndUserShViews", */
T: -1
},
426: {
/* n:"BrtArrFmla", */
f: parse_BrtArrFmla
},
427: {
/* n:"BrtShrFmla", */
f: parse_BrtShrFmla
},
428: {
/* n:"BrtTable" */
},
429: {
/* n:"BrtBeginExtConnections", */
T: 1
},
430: {
/* n:"BrtEndExtConnections", */
T: -1
},
431: {
/* n:"BrtBeginPCDCalcMems", */
T: 1
},
432: {
/* n:"BrtEndPCDCalcMems", */
T: -1
},
433: {
/* n:"BrtBeginPCDCalcMem", */
T: 1
},
434: {
/* n:"BrtEndPCDCalcMem", */
T: -1
},
435: {
/* n:"BrtBeginPCDHGLevels", */
T: 1
},
436: {
/* n:"BrtEndPCDHGLevels", */
T: -1
},
437: {
/* n:"BrtBeginPCDHGLevel", */
T: 1
},
438: {
/* n:"BrtEndPCDHGLevel", */
T: -1
},
439: {
/* n:"BrtBeginPCDHGLGroups", */
T: 1
},
440: {
/* n:"BrtEndPCDHGLGroups", */
T: -1
},
441: {
/* n:"BrtBeginPCDHGLGroup", */
T: 1
},
442: {
/* n:"BrtEndPCDHGLGroup", */
T: -1
},
443: {
/* n:"BrtBeginPCDHGLGMembers", */
T: 1
},
444: {
/* n:"BrtEndPCDHGLGMembers", */
T: -1
},
445: {
/* n:"BrtBeginPCDHGLGMember", */
T: 1
},
446: {
/* n:"BrtEndPCDHGLGMember", */
T: -1
},
447: {
/* n:"BrtBeginQSI", */
T: 1
},
448: {
/* n:"BrtEndQSI", */
T: -1
},
449: {
/* n:"BrtBeginQSIR", */
T: 1
},
450: {
/* n:"BrtEndQSIR", */
T: -1
},
451: {
/* n:"BrtBeginDeletedNames", */
T: 1
},
452: {
/* n:"BrtEndDeletedNames", */
T: -1
},
453: {
/* n:"BrtBeginDeletedName", */
T: 1
},
454: {
/* n:"BrtEndDeletedName", */
T: -1
},
455: {
/* n:"BrtBeginQSIFs", */
T: 1
},
456: {
/* n:"BrtEndQSIFs", */
T: -1
},
457: {
/* n:"BrtBeginQSIF", */
T: 1
},
458: {
/* n:"BrtEndQSIF", */
T: -1
},
459: {
/* n:"BrtBeginAutoSortScope", */
T: 1
},
460: {
/* n:"BrtEndAutoSortScope", */
T: -1
},
461: {
/* n:"BrtBeginConditionalFormatting", */
T: 1
},
462: {
/* n:"BrtEndConditionalFormatting", */
T: -1
},
463: {
/* n:"BrtBeginCFRule", */
T: 1
},
464: {
/* n:"BrtEndCFRule", */
T: -1
},
465: {
/* n:"BrtBeginIconSet", */
T: 1
},
466: {
/* n:"BrtEndIconSet", */
T: -1
},
467: {
/* n:"BrtBeginDatabar", */
T: 1
},
468: {
/* n:"BrtEndDatabar", */
T: -1
},
469: {
/* n:"BrtBeginColorScale", */
T: 1
},
470: {
/* n:"BrtEndColorScale", */
T: -1
},
471: {
/* n:"BrtCFVO" */
},
472: {
/* n:"BrtExternValueMeta" */
},
473: {
/* n:"BrtBeginColorPalette", */
T: 1
},
474: {
/* n:"BrtEndColorPalette", */
T: -1
},
475: {
/* n:"BrtIndexedColor" */
},
476: {
/* n:"BrtMargins", */
f: parse_BrtMargins
},
477: {
/* n:"BrtPrintOptions" */
},
478: {
/* n:"BrtPageSetup" */
},
479: {
/* n:"BrtBeginHeaderFooter", */
T: 1
},
480: {
/* n:"BrtEndHeaderFooter", */
T: -1
},
481: {
/* n:"BrtBeginSXCrtFormat", */
T: 1
},
482: {
/* n:"BrtEndSXCrtFormat", */
T: -1
},
483: {
/* n:"BrtBeginSXCrtFormats", */
T: 1
},
484: {
/* n:"BrtEndSXCrtFormats", */
T: -1
},
485: {
/* n:"BrtWsFmtInfo", */
f: parse_BrtWsFmtInfo
},
486: {
/* n:"BrtBeginMgs", */
T: 1
},
487: {
/* n:"BrtEndMGs", */
T: -1
},
488: {
/* n:"BrtBeginMGMaps", */
T: 1
},
489: {
/* n:"BrtEndMGMaps", */
T: -1
},
490: {
/* n:"BrtBeginMG", */
T: 1
},
491: {
/* n:"BrtEndMG", */
T: -1
},
492: {
/* n:"BrtBeginMap", */
T: 1
},
493: {
/* n:"BrtEndMap", */
T: -1
},
494: {
/* n:"BrtHLink", */
f: parse_BrtHLink
},
495: {
/* n:"BrtBeginDCon", */
T: 1
},
496: {
/* n:"BrtEndDCon", */
T: -1
},
497: {
/* n:"BrtBeginDRefs", */
T: 1
},
498: {
/* n:"BrtEndDRefs", */
T: -1
},
499: {
/* n:"BrtDRef" */
},
500: {
/* n:"BrtBeginScenMan", */
T: 1
},
501: {
/* n:"BrtEndScenMan", */
T: -1
},
502: {
/* n:"BrtBeginSct", */
T: 1
},
503: {
/* n:"BrtEndSct", */
T: -1
},
504: {
/* n:"BrtSlc" */
},
505: {
/* n:"BrtBeginDXFs", */
T: 1
},
506: {
/* n:"BrtEndDXFs", */
T: -1
},
507: {
/* n:"BrtDXF" */
},
508: {
/* n:"BrtBeginTableStyles", */
T: 1
},
509: {
/* n:"BrtEndTableStyles", */
T: -1
},
510: {
/* n:"BrtBeginTableStyle", */
T: 1
},
511: {
/* n:"BrtEndTableStyle", */
T: -1
},
512: {
/* n:"BrtTableStyleElement" */
},
513: {
/* n:"BrtTableStyleClient" */
},
514: {
/* n:"BrtBeginVolDeps", */
T: 1
},
515: {
/* n:"BrtEndVolDeps", */
T: -1
},
516: {
/* n:"BrtBeginVolType", */
T: 1
},
517: {
/* n:"BrtEndVolType", */
T: -1
},
518: {
/* n:"BrtBeginVolMain", */
T: 1
},
519: {
/* n:"BrtEndVolMain", */
T: -1
},
520: {
/* n:"BrtBeginVolTopic", */
T: 1
},
521: {
/* n:"BrtEndVolTopic", */
T: -1
},
522: {
/* n:"BrtVolSubtopic" */
},
523: {
/* n:"BrtVolRef" */
},
524: {
/* n:"BrtVolNum" */
},
525: {
/* n:"BrtVolErr" */
},
526: {
/* n:"BrtVolStr" */
},
527: {
/* n:"BrtVolBool" */
},
528: {
/* n:"BrtBeginCalcChain$", */
T: 1
},
529: {
/* n:"BrtEndCalcChain$", */
T: -1
},
530: {
/* n:"BrtBeginSortState", */
T: 1
},
531: {
/* n:"BrtEndSortState", */
T: -1
},
532: {
/* n:"BrtBeginSortCond", */
T: 1
},
533: {
/* n:"BrtEndSortCond", */
T: -1
},
534: {
/* n:"BrtBookProtection" */
},
535: {
/* n:"BrtSheetProtection" */
},
536: {
/* n:"BrtRangeProtection" */
},
537: {
/* n:"BrtPhoneticInfo" */
},
538: {
/* n:"BrtBeginECTxtWiz", */
T: 1
},
539: {
/* n:"BrtEndECTxtWiz", */
T: -1
},
540: {
/* n:"BrtBeginECTWFldInfoLst", */
T: 1
},
541: {
/* n:"BrtEndECTWFldInfoLst", */
T: -1
},
542: {
/* n:"BrtBeginECTwFldInfo", */
T: 1
},
548: {
/* n:"BrtFileSharing" */
},
549: {
/* n:"BrtOleSize" */
},
550: {
/* n:"BrtDrawing", */
f: parse_RelID
},
551: {
/* n:"BrtLegacyDrawing", */
f: parse_XLNullableWideString
},
552: {
/* n:"BrtLegacyDrawingHF" */
},
553: {
/* n:"BrtWebOpt" */
},
554: {
/* n:"BrtBeginWebPubItems", */
T: 1
},
555: {
/* n:"BrtEndWebPubItems", */
T: -1
},
556: {
/* n:"BrtBeginWebPubItem", */
T: 1
},
557: {
/* n:"BrtEndWebPubItem", */
T: -1
},
558: {
/* n:"BrtBeginSXCondFmt", */
T: 1
},
559: {
/* n:"BrtEndSXCondFmt", */
T: -1
},
560: {
/* n:"BrtBeginSXCondFmts", */
T: 1
},
561: {
/* n:"BrtEndSXCondFmts", */
T: -1
},
562: {
/* n:"BrtBkHim" */
},
564: {
/* n:"BrtColor" */
},
565: {
/* n:"BrtBeginIndexedColors", */
T: 1
},
566: {
/* n:"BrtEndIndexedColors", */
T: -1
},
569: {
/* n:"BrtBeginMRUColors", */
T: 1
},
570: {
/* n:"BrtEndMRUColors", */
T: -1
},
572: {
/* n:"BrtMRUColor" */
},
573: {
/* n:"BrtBeginDVals", */
T: 1
},
574: {
/* n:"BrtEndDVals", */
T: -1
},
577: {
/* n:"BrtSupNameStart" */
},
578: {
/* n:"BrtSupNameValueStart" */
},
579: {
/* n:"BrtSupNameValueEnd" */
},
580: {
/* n:"BrtSupNameNum" */
},
581: {
/* n:"BrtSupNameErr" */
},
582: {
/* n:"BrtSupNameSt" */
},
583: {
/* n:"BrtSupNameNil" */
},
584: {
/* n:"BrtSupNameBool" */
},
585: {
/* n:"BrtSupNameFmla" */
},
586: {
/* n:"BrtSupNameBits" */
},
587: {
/* n:"BrtSupNameEnd" */
},
588: {
/* n:"BrtEndSupBook", */
T: -1
},
589: {
/* n:"BrtCellSmartTagProperty" */
},
590: {
/* n:"BrtBeginCellSmartTag", */
T: 1
},
591: {
/* n:"BrtEndCellSmartTag", */
T: -1
},
592: {
/* n:"BrtBeginCellSmartTags", */
T: 1
},
593: {
/* n:"BrtEndCellSmartTags", */
T: -1
},
594: {
/* n:"BrtBeginSmartTags", */
T: 1
},
595: {
/* n:"BrtEndSmartTags", */
T: -1
},
596: {
/* n:"BrtSmartTagType" */
},
597: {
/* n:"BrtBeginSmartTagTypes", */
T: 1
},
598: {
/* n:"BrtEndSmartTagTypes", */
T: -1
},
599: {
/* n:"BrtBeginSXFilters", */
T: 1
},
600: {
/* n:"BrtEndSXFilters", */
T: -1
},
601: {
/* n:"BrtBeginSXFILTER", */
T: 1
},
602: {
/* n:"BrtEndSXFilter", */
T: -1
},
603: {
/* n:"BrtBeginFills", */
T: 1
},
604: {
/* n:"BrtEndFills", */
T: -1
},
605: {
/* n:"BrtBeginCellWatches", */
T: 1
},
606: {
/* n:"BrtEndCellWatches", */
T: -1
},
607: {
/* n:"BrtCellWatch" */
},
608: {
/* n:"BrtBeginCRErrs", */
T: 1
},
609: {
/* n:"BrtEndCRErrs", */
T: -1
},
610: {
/* n:"BrtCrashRecErr" */
},
611: {
/* n:"BrtBeginFonts", */
T: 1
},
612: {
/* n:"BrtEndFonts", */
T: -1
},
613: {
/* n:"BrtBeginBorders", */
T: 1
},
614: {
/* n:"BrtEndBorders", */
T: -1
},
615: {
/* n:"BrtBeginFmts", */
T: 1
},
616: {
/* n:"BrtEndFmts", */
T: -1
},
617: {
/* n:"BrtBeginCellXFs", */
T: 1
},
618: {
/* n:"BrtEndCellXFs", */
T: -1
},
619: {
/* n:"BrtBeginStyles", */
T: 1
},
620: {
/* n:"BrtEndStyles", */
T: -1
},
625: {
/* n:"BrtBigName" */
},
626: {
/* n:"BrtBeginCellStyleXFs", */
T: 1
},
627: {
/* n:"BrtEndCellStyleXFs", */
T: -1
},
628: {
/* n:"BrtBeginComments", */
T: 1
},
629: {
/* n:"BrtEndComments", */
T: -1
},
630: {
/* n:"BrtBeginCommentAuthors", */
T: 1
},
631: {
/* n:"BrtEndCommentAuthors", */
T: -1
},
632: {
/* n:"BrtCommentAuthor", */
f: parse_BrtCommentAuthor
},
633: {
/* n:"BrtBeginCommentList", */
T: 1
},
634: {
/* n:"BrtEndCommentList", */
T: -1
},
635: {
/* n:"BrtBeginComment", */
T: 1,
f: parse_BrtBeginComment
},
636: {
/* n:"BrtEndComment", */
T: -1
},
637: {
/* n:"BrtCommentText", */
f: parse_BrtCommentText
},
638: {
/* n:"BrtBeginOleObjects", */
T: 1
},
639: {
/* n:"BrtOleObject" */
},
640: {
/* n:"BrtEndOleObjects", */
T: -1
},
641: {
/* n:"BrtBeginSxrules", */
T: 1
},
642: {
/* n:"BrtEndSxRules", */
T: -1
},
643: {
/* n:"BrtBeginActiveXControls", */
T: 1
},
644: {
/* n:"BrtActiveX" */
},
645: {
/* n:"BrtEndActiveXControls", */
T: -1
},
646: {
/* n:"BrtBeginPCDSDTCEMembersSortBy", */
T: 1
},
648: {
/* n:"BrtBeginCellIgnoreECs", */
T: 1
},
649: {
/* n:"BrtCellIgnoreEC" */
},
650: {
/* n:"BrtEndCellIgnoreECs", */
T: -1
},
651: {
/* n:"BrtCsProp", */
f: parse_BrtCsProp
},
652: {
/* n:"BrtCsPageSetup" */
},
653: {
/* n:"BrtBeginUserCsViews", */
T: 1
},
654: {
/* n:"BrtEndUserCsViews", */
T: -1
},
655: {
/* n:"BrtBeginUserCsView", */
T: 1
},
656: {
/* n:"BrtEndUserCsView", */
T: -1
},
657: {
/* n:"BrtBeginPcdSFCIEntries", */
T: 1
},
658: {
/* n:"BrtEndPCDSFCIEntries", */
T: -1
},
659: {
/* n:"BrtPCDSFCIEntry" */
},
660: {
/* n:"BrtBeginListParts", */
T: 1
},
661: {
/* n:"BrtListPart" */
},
662: {
/* n:"BrtEndListParts", */
T: -1
},
663: {
/* n:"BrtSheetCalcProp" */
},
664: {
/* n:"BrtBeginFnGroup", */
T: 1
},
665: {
/* n:"BrtFnGroup" */
},
666: {
/* n:"BrtEndFnGroup", */
T: -1
},
667: {
/* n:"BrtSupAddin" */
},
668: {
/* n:"BrtSXTDMPOrder" */
},
669: {
/* n:"BrtCsProtection" */
},
671: {
/* n:"BrtBeginWsSortMap", */
T: 1
},
672: {
/* n:"BrtEndWsSortMap", */
T: -1
},
673: {
/* n:"BrtBeginRRSort", */
T: 1
},
674: {
/* n:"BrtEndRRSort", */
T: -1
},
675: {
/* n:"BrtRRSortItem" */
},
676: {
/* n:"BrtFileSharingIso" */
},
677: {
/* n:"BrtBookProtectionIso" */
},
678: {
/* n:"BrtSheetProtectionIso" */
},
679: {
/* n:"BrtCsProtectionIso" */
},
680: {
/* n:"BrtRangeProtectionIso" */
},
681: {
/* n:"BrtDValList" */
},
1024: {
/* n:"BrtRwDescent" */
},
1025: {
/* n:"BrtKnownFonts" */
},
1026: {
/* n:"BrtBeginSXTupleSet", */
T: 1
},
1027: {
/* n:"BrtEndSXTupleSet", */
T: -1
},
1028: {
/* n:"BrtBeginSXTupleSetHeader", */
T: 1
},
1029: {
/* n:"BrtEndSXTupleSetHeader", */
T: -1
},
1030: {
/* n:"BrtSXTupleSetHeaderItem" */
},
1031: {
/* n:"BrtBeginSXTupleSetData", */
T: 1
},
1032: {
/* n:"BrtEndSXTupleSetData", */
T: -1
},
1033: {
/* n:"BrtBeginSXTupleSetRow", */
T: 1
},
1034: {
/* n:"BrtEndSXTupleSetRow", */
T: -1
},
1035: {
/* n:"BrtSXTupleSetRowItem" */
},
1036: {
/* n:"BrtNameExt" */
},
1037: {
/* n:"BrtPCDH14" */
},
1038: {
/* n:"BrtBeginPCDCalcMem14", */
T: 1
},
1039: {
/* n:"BrtEndPCDCalcMem14", */
T: -1
},
1040: {
/* n:"BrtSXTH14" */
},
1041: {
/* n:"BrtBeginSparklineGroup", */
T: 1
},
1042: {
/* n:"BrtEndSparklineGroup", */
T: -1
},
1043: {
/* n:"BrtSparkline" */
},
1044: {
/* n:"BrtSXDI14" */
},
1045: {
/* n:"BrtWsFmtInfoEx14" */
},
1046: {
/* n:"BrtBeginConditionalFormatting14", */
T: 1
},
1047: {
/* n:"BrtEndConditionalFormatting14", */
T: -1
},
1048: {
/* n:"BrtBeginCFRule14", */
T: 1
},
1049: {
/* n:"BrtEndCFRule14", */
T: -1
},
1050: {
/* n:"BrtCFVO14" */
},
1051: {
/* n:"BrtBeginDatabar14", */
T: 1
},
1052: {
/* n:"BrtBeginIconSet14", */
T: 1
},
1053: {
/* n:"BrtDVal14", */
f: parse_BrtDVal14
},
1054: {
/* n:"BrtBeginDVals14", */
T: 1
},
1055: {
/* n:"BrtColor14" */
},
1056: {
/* n:"BrtBeginSparklines", */
T: 1
},
1057: {
/* n:"BrtEndSparklines", */
T: -1
},
1058: {
/* n:"BrtBeginSparklineGroups", */
T: 1
},
1059: {
/* n:"BrtEndSparklineGroups", */
T: -1
},
1061: {
/* n:"BrtSXVD14" */
},
1062: {
/* n:"BrtBeginSXView14", */
T: 1
},
1063: {
/* n:"BrtEndSXView14", */
T: -1
},
1064: {
/* n:"BrtBeginSXView16", */
T: 1
},
1065: {
/* n:"BrtEndSXView16", */
T: -1
},
1066: {
/* n:"BrtBeginPCD14", */
T: 1
},
1067: {
/* n:"BrtEndPCD14", */
T: -1
},
1068: {
/* n:"BrtBeginExtConn14", */
T: 1
},
1069: {
/* n:"BrtEndExtConn14", */
T: -1
},
1070: {
/* n:"BrtBeginSlicerCacheIDs", */
T: 1
},
1071: {
/* n:"BrtEndSlicerCacheIDs", */
T: -1
},
1072: {
/* n:"BrtBeginSlicerCacheID", */
T: 1
},
1073: {
/* n:"BrtEndSlicerCacheID", */
T: -1
},
1075: {
/* n:"BrtBeginSlicerCache", */
T: 1
},
1076: {
/* n:"BrtEndSlicerCache", */
T: -1
},
1077: {
/* n:"BrtBeginSlicerCacheDef", */
T: 1
},
1078: {
/* n:"BrtEndSlicerCacheDef", */
T: -1
},
1079: {
/* n:"BrtBeginSlicersEx", */
T: 1
},
1080: {
/* n:"BrtEndSlicersEx", */
T: -1
},
1081: {
/* n:"BrtBeginSlicerEx", */
T: 1
},
1082: {
/* n:"BrtEndSlicerEx", */
T: -1
},
1083: {
/* n:"BrtBeginSlicer", */
T: 1
},
1084: {
/* n:"BrtEndSlicer", */
T: -1
},
1085: {
/* n:"BrtSlicerCachePivotTables" */
},
1086: {
/* n:"BrtBeginSlicerCacheOlapImpl", */
T: 1
},
1087: {
/* n:"BrtEndSlicerCacheOlapImpl", */
T: -1
},
1088: {
/* n:"BrtBeginSlicerCacheLevelsData", */
T: 1
},
1089: {
/* n:"BrtEndSlicerCacheLevelsData", */
T: -1
},
1090: {
/* n:"BrtBeginSlicerCacheLevelData", */
T: 1
},
1091: {
/* n:"BrtEndSlicerCacheLevelData", */
T: -1
},
1092: {
/* n:"BrtBeginSlicerCacheSiRanges", */
T: 1
},
1093: {
/* n:"BrtEndSlicerCacheSiRanges", */
T: -1
},
1094: {
/* n:"BrtBeginSlicerCacheSiRange", */
T: 1
},
1095: {
/* n:"BrtEndSlicerCacheSiRange", */
T: -1
},
1096: {
/* n:"BrtSlicerCacheOlapItem" */
},
1097: {
/* n:"BrtBeginSlicerCacheSelections", */
T: 1
},
1098: {
/* n:"BrtSlicerCacheSelection" */
},
1099: {
/* n:"BrtEndSlicerCacheSelections", */
T: -1
},
1100: {
/* n:"BrtBeginSlicerCacheNative", */
T: 1
},
1101: {
/* n:"BrtEndSlicerCacheNative", */
T: -1
},
1102: {
/* n:"BrtSlicerCacheNativeItem" */
},
1103: {
/* n:"BrtRangeProtection14" */
},
1104: {
/* n:"BrtRangeProtectionIso14" */
},
1105: {
/* n:"BrtCellIgnoreEC14" */
},
1111: {
/* n:"BrtList14" */
},
1112: {
/* n:"BrtCFIcon" */
},
1113: {
/* n:"BrtBeginSlicerCachesPivotCacheIDs", */
T: 1
},
1114: {
/* n:"BrtEndSlicerCachesPivotCacheIDs", */
T: -1
},
1115: {
/* n:"BrtBeginSlicers", */
T: 1
},
1116: {
/* n:"BrtEndSlicers", */
T: -1
},
1117: {
/* n:"BrtWbProp14" */
},
1118: {
/* n:"BrtBeginSXEdit", */
T: 1
},
1119: {
/* n:"BrtEndSXEdit", */
T: -1
},
1120: {
/* n:"BrtBeginSXEdits", */
T: 1
},
1121: {
/* n:"BrtEndSXEdits", */
T: -1
},
1122: {
/* n:"BrtBeginSXChange", */
T: 1
},
1123: {
/* n:"BrtEndSXChange", */
T: -1
},
1124: {
/* n:"BrtBeginSXChanges", */
T: 1
},
1125: {
/* n:"BrtEndSXChanges", */
T: -1
},
1126: {
/* n:"BrtSXTupleItems" */
},
1128: {
/* n:"BrtBeginSlicerStyle", */
T: 1
},
1129: {
/* n:"BrtEndSlicerStyle", */
T: -1
},
1130: {
/* n:"BrtSlicerStyleElement" */
},
1131: {
/* n:"BrtBeginStyleSheetExt14", */
T: 1
},
1132: {
/* n:"BrtEndStyleSheetExt14", */
T: -1
},
1133: {
/* n:"BrtBeginSlicerCachesPivotCacheID", */
T: 1
},
1134: {
/* n:"BrtEndSlicerCachesPivotCacheID", */
T: -1
},
1135: {
/* n:"BrtBeginConditionalFormattings", */
T: 1
},
1136: {
/* n:"BrtEndConditionalFormattings", */
T: -1
},
1137: {
/* n:"BrtBeginPCDCalcMemExt", */
T: 1
},
1138: {
/* n:"BrtEndPCDCalcMemExt", */
T: -1
},
1139: {
/* n:"BrtBeginPCDCalcMemsExt", */
T: 1
},
1140: {
/* n:"BrtEndPCDCalcMemsExt", */
T: -1
},
1141: {
/* n:"BrtPCDField14" */
},
1142: {
/* n:"BrtBeginSlicerStyles", */
T: 1
},
1143: {
/* n:"BrtEndSlicerStyles", */
T: -1
},
1144: {
/* n:"BrtBeginSlicerStyleElements", */
T: 1
},
1145: {
/* n:"BrtEndSlicerStyleElements", */
T: -1
},
1146: {
/* n:"BrtCFRuleExt" */
},
1147: {
/* n:"BrtBeginSXCondFmt14", */
T: 1
},
1148: {
/* n:"BrtEndSXCondFmt14", */
T: -1
},
1149: {
/* n:"BrtBeginSXCondFmts14", */
T: 1
},
1150: {
/* n:"BrtEndSXCondFmts14", */
T: -1
},
1152: {
/* n:"BrtBeginSortCond14", */
T: 1
},
1153: {
/* n:"BrtEndSortCond14", */
T: -1
},
1154: {
/* n:"BrtEndDVals14", */
T: -1
},
1155: {
/* n:"BrtEndIconSet14", */
T: -1
},
1156: {
/* n:"BrtEndDatabar14", */
T: -1
},
1157: {
/* n:"BrtBeginColorScale14", */
T: 1
},
1158: {
/* n:"BrtEndColorScale14", */
T: -1
},
1159: {
/* n:"BrtBeginSxrules14", */
T: 1
},
1160: {
/* n:"BrtEndSxrules14", */
T: -1
},
1161: {
/* n:"BrtBeginPRule14", */
T: 1
},
1162: {
/* n:"BrtEndPRule14", */
T: -1
},
1163: {
/* n:"BrtBeginPRFilters14", */
T: 1
},
1164: {
/* n:"BrtEndPRFilters14", */
T: -1
},
1165: {
/* n:"BrtBeginPRFilter14", */
T: 1
},
1166: {
/* n:"BrtEndPRFilter14", */
T: -1
},
1167: {
/* n:"BrtBeginPRFItem14", */
T: 1
},
1168: {
/* n:"BrtEndPRFItem14", */
T: -1
},
1169: {
/* n:"BrtBeginCellIgnoreECs14", */
T: 1
},
1170: {
/* n:"BrtEndCellIgnoreECs14", */
T: -1
},
1171: {
/* n:"BrtDxf14" */
},
1172: {
/* n:"BrtBeginDxF14s", */
T: 1
},
1173: {
/* n:"BrtEndDxf14s", */
T: -1
},
1177: {
/* n:"BrtFilter14" */
},
1178: {
/* n:"BrtBeginCustomFilters14", */
T: 1
},
1180: {
/* n:"BrtCustomFilter14" */
},
1181: {
/* n:"BrtIconFilter14" */
},
1182: {
/* n:"BrtPivotCacheConnectionName" */
},
2048: {
/* n:"BrtBeginDecoupledPivotCacheIDs", */
T: 1
},
2049: {
/* n:"BrtEndDecoupledPivotCacheIDs", */
T: -1
},
2050: {
/* n:"BrtDecoupledPivotCacheID" */
},
2051: {
/* n:"BrtBeginPivotTableRefs", */
T: 1
},
2052: {
/* n:"BrtEndPivotTableRefs", */
T: -1
},
2053: {
/* n:"BrtPivotTableRef" */
},
2054: {
/* n:"BrtSlicerCacheBookPivotTables" */
},
2055: {
/* n:"BrtBeginSxvcells", */
T: 1
},
2056: {
/* n:"BrtEndSxvcells", */
T: -1
},
2057: {
/* n:"BrtBeginSxRow", */
T: 1
},
2058: {
/* n:"BrtEndSxRow", */
T: -1
},
2060: {
/* n:"BrtPcdCalcMem15" */
},
2067: {
/* n:"BrtQsi15" */
},
2068: {
/* n:"BrtBeginWebExtensions", */
T: 1
},
2069: {
/* n:"BrtEndWebExtensions", */
T: -1
},
2070: {
/* n:"BrtWebExtension" */
},
2071: {
/* n:"BrtAbsPath15" */
},
2072: {
/* n:"BrtBeginPivotTableUISettings", */
T: 1
},
2073: {
/* n:"BrtEndPivotTableUISettings", */
T: -1
},
2075: {
/* n:"BrtTableSlicerCacheIDs" */
},
2076: {
/* n:"BrtTableSlicerCacheID" */
},
2077: {
/* n:"BrtBeginTableSlicerCache", */
T: 1
},
2078: {
/* n:"BrtEndTableSlicerCache", */
T: -1
},
2079: {
/* n:"BrtSxFilter15" */
},
2080: {
/* n:"BrtBeginTimelineCachePivotCacheIDs", */
T: 1
},
2081: {
/* n:"BrtEndTimelineCachePivotCacheIDs", */
T: -1
},
2082: {
/* n:"BrtTimelineCachePivotCacheID" */
},
2083: {
/* n:"BrtBeginTimelineCacheIDs", */
T: 1
},
2084: {
/* n:"BrtEndTimelineCacheIDs", */
T: -1
},
2085: {
/* n:"BrtBeginTimelineCacheID", */
T: 1
},
2086: {
/* n:"BrtEndTimelineCacheID", */
T: -1
},
2087: {
/* n:"BrtBeginTimelinesEx", */
T: 1
},
2088: {
/* n:"BrtEndTimelinesEx", */
T: -1
},
2089: {
/* n:"BrtBeginTimelineEx", */
T: 1
},
2090: {
/* n:"BrtEndTimelineEx", */
T: -1
},
2091: {
/* n:"BrtWorkBookPr15" */
},
2092: {
/* n:"BrtPCDH15" */
},
2093: {
/* n:"BrtBeginTimelineStyle", */
T: 1
},
2094: {
/* n:"BrtEndTimelineStyle", */
T: -1
},
2095: {
/* n:"BrtTimelineStyleElement" */
},
2096: {
/* n:"BrtBeginTimelineStylesheetExt15", */
T: 1
},
2097: {
/* n:"BrtEndTimelineStylesheetExt15", */
T: -1
},
2098: {
/* n:"BrtBeginTimelineStyles", */
T: 1
},
2099: {
/* n:"BrtEndTimelineStyles", */
T: -1
},
2100: {
/* n:"BrtBeginTimelineStyleElements", */
T: 1
},
2101: {
/* n:"BrtEndTimelineStyleElements", */
T: -1
},
2102: {
/* n:"BrtDxf15" */
},
2103: {
/* n:"BrtBeginDxfs15", */
T: 1
},
2104: {
/* n:"BrtEndDxfs15", */
T: -1
},
2105: {
/* n:"BrtSlicerCacheHideItemsWithNoData" */
},
2106: {
/* n:"BrtBeginItemUniqueNames", */
T: 1
},
2107: {
/* n:"BrtEndItemUniqueNames", */
T: -1
},
2108: {
/* n:"BrtItemUniqueName" */
},
2109: {
/* n:"BrtBeginExtConn15", */
T: 1
},
2110: {
/* n:"BrtEndExtConn15", */
T: -1
},
2111: {
/* n:"BrtBeginOledbPr15", */
T: 1
},
2112: {
/* n:"BrtEndOledbPr15", */
T: -1
},
2113: {
/* n:"BrtBeginDataFeedPr15", */
T: 1
},
2114: {
/* n:"BrtEndDataFeedPr15", */
T: -1
},
2115: {
/* n:"BrtTextPr15" */
},
2116: {
/* n:"BrtRangePr15" */
},
2117: {
/* n:"BrtDbCommand15" */
},
2118: {
/* n:"BrtBeginDbTables15", */
T: 1
},
2119: {
/* n:"BrtEndDbTables15", */
T: -1
},
2120: {
/* n:"BrtDbTable15" */
},
2121: {
/* n:"BrtBeginDataModel", */
T: 1
},
2122: {
/* n:"BrtEndDataModel", */
T: -1
},
2123: {
/* n:"BrtBeginModelTables", */
T: 1
},
2124: {
/* n:"BrtEndModelTables", */
T: -1
},
2125: {
/* n:"BrtModelTable" */
},
2126: {
/* n:"BrtBeginModelRelationships", */
T: 1
},
2127: {
/* n:"BrtEndModelRelationships", */
T: -1
},
2128: {
/* n:"BrtModelRelationship" */
},
2129: {
/* n:"BrtBeginECTxtWiz15", */
T: 1
},
2130: {
/* n:"BrtEndECTxtWiz15", */
T: -1
},
2131: {
/* n:"BrtBeginECTWFldInfoLst15", */
T: 1
},
2132: {
/* n:"BrtEndECTWFldInfoLst15", */
T: -1
},
2133: {
/* n:"BrtBeginECTWFldInfo15", */
T: 1
},
2134: {
/* n:"BrtFieldListActiveItem" */
},
2135: {
/* n:"BrtPivotCacheIdVersion" */
},
2136: {
/* n:"BrtSXDI15" */
},
2137: {
/* n:"BrtBeginModelTimeGroupings", */
T: 1
},
2138: {
/* n:"BrtEndModelTimeGroupings", */
T: -1
},
2139: {
/* n:"BrtBeginModelTimeGrouping", */
T: 1
},
2140: {
/* n:"BrtEndModelTimeGrouping", */
T: -1
},
2141: {
/* n:"BrtModelTimeGroupingCalcCol" */
},
3072: {
/* n:"BrtUid" */
},
3073: {
/* n:"BrtRevisionPtr" */
},
4096: {
/* n:"BrtBeginDynamicArrayPr", */
T: 1
},
4097: {
/* n:"BrtEndDynamicArrayPr", */
T: -1
},
5002: {
/* n:"BrtBeginRichValueBlock", */
T: 1
},
5003: {
/* n:"BrtEndRichValueBlock", */
T: -1
},
5081: {
/* n:"BrtBeginRichFilters", */
T: 1
},
5082: {
/* n:"BrtEndRichFilters", */
T: -1
},
5083: {
/* n:"BrtRichFilter" */
},
5084: {
/* n:"BrtBeginRichFilterColumn", */
T: 1
},
5085: {
/* n:"BrtEndRichFilterColumn", */
T: -1
},
5086: {
/* n:"BrtBeginCustomRichFilters", */
T: 1
},
5087: {
/* n:"BrtEndCustomRichFilters", */
T: -1
},
5088: {
/* n:"BrtCustomRichFilter" */
},
5089: {
/* n:"BrtTop10RichFilter" */
},
5090: {
/* n:"BrtDynamicRichFilter" */
},
5092: {
/* n:"BrtBeginRichSortCondition", */
T: 1
},
5093: {
/* n:"BrtEndRichSortCondition", */
T: -1
},
5094: {
/* n:"BrtRichFilterDateGroupItem" */
},
5095: {
/* n:"BrtBeginCalcFeatures", */
T: 1
},
5096: {
/* n:"BrtEndCalcFeatures", */
T: -1
},
5097: {
/* n:"BrtCalcFeature" */
},
5099: {
/* n:"BrtExternalLinksPr" */
},
65535: { n: "" }
};
XLSRecordEnum = {
/* [MS-XLS] 2.3 Record Enumeration 2021-08-17 */
6: {
/* n:"Formula", */
f: parse_Formula
},
10: {
/* n:"EOF", */
f: parsenoop2
},
12: {
/* n:"CalcCount", */
f: parseuint16
},
//
13: {
/* n:"CalcMode", */
f: parseuint16
},
//
14: {
/* n:"CalcPrecision", */
f: parsebool
},
//
15: {
/* n:"CalcRefMode", */
f: parsebool
},
//
16: {
/* n:"CalcDelta", */
f: parse_Xnum
},
//
17: {
/* n:"CalcIter", */
f: parsebool
},
//
18: {
/* n:"Protect", */
f: parsebool
},
19: {
/* n:"Password", */
f: parseuint16
},
20: {
/* n:"Header", */
f: parse_XLHeaderFooter
},
21: {
/* n:"Footer", */
f: parse_XLHeaderFooter
},
23: {
/* n:"ExternSheet", */
f: parse_ExternSheet
},
24: {
/* n:"Lbl", */
f: parse_Lbl
},
25: {
/* n:"WinProtect", */
f: parsebool
},
26: {
/* n:"VerticalPageBreaks", */
},
27: {
/* n:"HorizontalPageBreaks", */
},
28: {
/* n:"Note", */
f: parse_Note
},
29: {
/* n:"Selection", */
},
34: {
/* n:"Date1904", */
f: parsebool
},
35: {
/* n:"ExternName", */
f: parse_ExternName
},
38: {
/* n:"LeftMargin", */
f: parse_Xnum
},
// *
39: {
/* n:"RightMargin", */
f: parse_Xnum
},
// *
40: {
/* n:"TopMargin", */
f: parse_Xnum
},
// *
41: {
/* n:"BottomMargin", */
f: parse_Xnum
},
// *
42: {
/* n:"PrintRowCol", */
f: parsebool
},
43: {
/* n:"PrintGrid", */
f: parsebool
},
47: {
/* n:"FilePass", */
f: parse_FilePass
},
49: {
/* n:"Font", */
f: parse_Font
},
51: {
/* n:"PrintSize", */
f: parseuint16
},
60: {
/* n:"Continue", */
},
61: {
/* n:"Window1", */
f: parse_Window1
},
64: {
/* n:"Backup", */
f: parsebool
},
65: {
/* n:"Pane", */
f: parse_Pane
},
66: {
/* n:"CodePage", */
f: parseuint16
},
77: {
/* n:"Pls", */
},
80: {
/* n:"DCon", */
},
81: {
/* n:"DConRef", */
},
82: {
/* n:"DConName", */
},
85: {
/* n:"DefColWidth", */
f: parseuint16
},
89: {
/* n:"XCT", */
},
90: {
/* n:"CRN", */
},
91: {
/* n:"FileSharing", */
},
92: {
/* n:"WriteAccess", */
f: parse_WriteAccess
},
93: {
/* n:"Obj", */
f: parse_Obj
},
94: {
/* n:"Uncalced", */
},
95: {
/* n:"CalcSaveRecalc", */
f: parsebool
},
//
96: {
/* n:"Template", */
},
97: {
/* n:"Intl", */
},
99: {
/* n:"ObjProtect", */
f: parsebool
},
125: {
/* n:"ColInfo", */
f: parse_ColInfo
},
128: {
/* n:"Guts", */
f: parse_Guts
},
129: {
/* n:"WsBool", */
f: parse_WsBool
},
130: {
/* n:"GridSet", */
f: parseuint16
},
131: {
/* n:"HCenter", */
f: parsebool
},
132: {
/* n:"VCenter", */
f: parsebool
},
133: {
/* n:"BoundSheet8", */
f: parse_BoundSheet8
},
134: {
/* n:"WriteProtect", */
},
140: {
/* n:"Country", */
f: parse_Country
},
141: {
/* n:"HideObj", */
f: parseuint16
},
144: {
/* n:"Sort", */
},
146: {
/* n:"Palette", */
f: parse_Palette
},
151: {
/* n:"Sync", */
},
152: {
/* n:"LPr", */
},
153: {
/* n:"DxGCol", */
},
154: {
/* n:"FnGroupName", */
},
155: {
/* n:"FilterMode", */
},
156: {
/* n:"BuiltInFnGroupCount", */
f: parseuint16
},
157: {
/* n:"AutoFilterInfo", */
},
158: {
/* n:"AutoFilter", */
},
160: {
/* n:"Scl", */
f: parse_Scl
},
161: {
/* n:"Setup", */
f: parse_Setup
},
174: {
/* n:"ScenMan", */
},
175: {
/* n:"SCENARIO", */
},
176: {
/* n:"SxView", */
},
177: {
/* n:"Sxvd", */
},
178: {
/* n:"SXVI", */
},
180: {
/* n:"SxIvd", */
},
181: {
/* n:"SXLI", */
},
182: {
/* n:"SXPI", */
},
184: {
/* n:"DocRoute", */
},
185: {
/* n:"RecipName", */
},
189: {
/* n:"MulRk", */
f: parse_MulRk
},
190: {
/* n:"MulBlank", */
f: parse_MulBlank
},
193: {
/* n:"Mms", */
f: parsenoop2
},
197: {
/* n:"SXDI", */
},
198: {
/* n:"SXDB", */
},
199: {
/* n:"SXFDB", */
},
200: {
/* n:"SXDBB", */
},
201: {
/* n:"SXNum", */
},
202: {
/* n:"SxBool", */
f: parsebool
},
203: {
/* n:"SxErr", */
},
204: {
/* n:"SXInt", */
},
205: {
/* n:"SXString", */
},
206: {
/* n:"SXDtr", */
},
207: {
/* n:"SxNil", */
},
208: {
/* n:"SXTbl", */
},
209: {
/* n:"SXTBRGIITM", */
},
210: {
/* n:"SxTbpg", */
},
211: {
/* n:"ObProj", */
},
213: {
/* n:"SXStreamID", */
},
215: {
/* n:"DBCell", */
},
216: {
/* n:"SXRng", */
},
217: {
/* n:"SxIsxoper", */
},
218: {
/* n:"BookBool", */
f: parseuint16
},
220: {
/* n:"DbOrParamQry", */
},
221: {
/* n:"ScenarioProtect", */
f: parsebool
},
222: {
/* n:"OleObjectSize", */
},
224: {
/* n:"XF", */
f: parse_XF
},
225: {
/* n:"InterfaceHdr", */
f: parse_InterfaceHdr
},
226: {
/* n:"InterfaceEnd", */
f: parsenoop2
},
227: {
/* n:"SXVS", */
},
229: {
/* n:"MergeCells", */
f: parse_MergeCells
},
233: {
/* n:"BkHim", */
},
235: {
/* n:"MsoDrawingGroup", */
},
236: {
/* n:"MsoDrawing", */
},
237: {
/* n:"MsoDrawingSelection", */
},
239: {
/* n:"PhoneticInfo", */
},
240: {
/* n:"SxRule", */
},
241: {
/* n:"SXEx", */
},
242: {
/* n:"SxFilt", */
},
244: {
/* n:"SxDXF", */
},
245: {
/* n:"SxItm", */
},
246: {
/* n:"SxName", */
},
247: {
/* n:"SxSelect", */
},
248: {
/* n:"SXPair", */
},
249: {
/* n:"SxFmla", */
},
251: {
/* n:"SxFormat", */
},
252: {
/* n:"SST", */
f: parse_SST
},
253: {
/* n:"LabelSst", */
f: parse_LabelSst
},
255: {
/* n:"ExtSST", */
f: parse_ExtSST
},
256: {
/* n:"SXVDEx", */
},
259: {
/* n:"SXFormula", */
},
290: {
/* n:"SXDBEx", */
},
311: {
/* n:"RRDInsDel", */
},
312: {
/* n:"RRDHead", */
},
315: {
/* n:"RRDChgCell", */
},
317: {
/* n:"RRTabId", */
f: parseuint16a
},
318: {
/* n:"RRDRenSheet", */
},
319: {
/* n:"RRSort", */
},
320: {
/* n:"RRDMove", */
},
330: {
/* n:"RRFormat", */
},
331: {
/* n:"RRAutoFmt", */
},
333: {
/* n:"RRInsertSh", */
},
334: {
/* n:"RRDMoveBegin", */
},
335: {
/* n:"RRDMoveEnd", */
},
336: {
/* n:"RRDInsDelBegin", */
},
337: {
/* n:"RRDInsDelEnd", */
},
338: {
/* n:"RRDConflict", */
},
339: {
/* n:"RRDDefName", */
},
340: {
/* n:"RRDRstEtxp", */
},
351: {
/* n:"LRng", */
},
352: {
/* n:"UsesELFs", */
f: parsebool
},
353: {
/* n:"DSF", */
f: parsenoop2
},
401: {
/* n:"CUsr", */
},
402: {
/* n:"CbUsr", */
},
403: {
/* n:"UsrInfo", */
},
404: {
/* n:"UsrExcl", */
},
405: {
/* n:"FileLock", */
},
406: {
/* n:"RRDInfo", */
},
407: {
/* n:"BCUsrs", */
},
408: {
/* n:"UsrChk", */
},
425: {
/* n:"UserBView", */
},
426: {
/* n:"UserSViewBegin", */
},
427: {
/* n:"UserSViewEnd", */
},
428: {
/* n:"RRDUserView", */
},
429: {
/* n:"Qsi", */
},
430: {
/* n:"SupBook", */
f: parse_SupBook
},
431: {
/* n:"Prot4Rev", */
f: parsebool
},
432: {
/* n:"CondFmt", */
},
433: {
/* n:"CF", */
},
434: {
/* n:"DVal", */
},
437: {
/* n:"DConBin", */
},
438: {
/* n:"TxO", */
f: parse_TxO
},
439: {
/* n:"RefreshAll", */
f: parsebool
},
//
440: {
/* n:"HLink", */
f: parse_HLink
},
441: {
/* n:"Lel", */
},
442: {
/* n:"CodeName", */
f: parse_XLUnicodeString
},
443: {
/* n:"SXFDBType", */
},
444: {
/* n:"Prot4RevPass", */
f: parseuint16
},
445: {
/* n:"ObNoMacros", */
},
446: {
/* n:"Dv", */
},
448: {
/* n:"Excel9File", */
f: parsenoop2
},
449: {
/* n:"RecalcId", */
f: parse_RecalcId,
r: 2
},
450: {
/* n:"EntExU2", */
f: parsenoop2
},
512: {
/* n:"Dimensions", */
f: parse_Dimensions
},
513: {
/* n:"Blank", */
f: parse_Blank
},
515: {
/* n:"Number", */
f: parse_Number
},
516: {
/* n:"Label", */
f: parse_Label
},
517: {
/* n:"BoolErr", */
f: parse_BoolErr
},
519: {
/* n:"String", */
f: parse_String
},
520: {
/* n:"Row", */
f: parse_Row
},
523: {
/* n:"Index", */
},
545: {
/* n:"Array", */
f: parse_Array
},
549: {
/* n:"DefaultRowHeight", */
f: parse_DefaultRowHeight
},
566: {
/* n:"Table", */
},
574: {
/* n:"Window2", */
f: parse_Window2
},
638: {
/* n:"RK", */
f: parse_RK
},
659: {
/* n:"Style", */
},
1048: {
/* n:"BigName", */
},
1054: {
/* n:"Format", */
f: parse_Format
},
1084: {
/* n:"ContinueBigName", */
},
1212: {
/* n:"ShrFmla", */
f: parse_ShrFmla
},
2048: {
/* n:"HLinkTooltip", */
f: parse_HLinkTooltip
},
2049: {
/* n:"WebPub", */
},
2050: {
/* n:"QsiSXTag", */
},
2051: {
/* n:"DBQueryExt", */
},
2052: {
/* n:"ExtString", */
},
2053: {
/* n:"TxtQry", */
},
2054: {
/* n:"Qsir", */
},
2055: {
/* n:"Qsif", */
},
2056: {
/* n:"RRDTQSIF", */
},
2057: {
/* n:"BOF", */
f: parse_BOF
},
2058: {
/* n:"OleDbConn", */
},
2059: {
/* n:"WOpt", */
},
2060: {
/* n:"SXViewEx", */
},
2061: {
/* n:"SXTH", */
},
2062: {
/* n:"SXPIEx", */
},
2063: {
/* n:"SXVDTEx", */
},
2064: {
/* n:"SXViewEx9", */
},
2066: {
/* n:"ContinueFrt", */
},
2067: {
/* n:"RealTimeData", */
},
2128: {
/* n:"ChartFrtInfo", */
},
2129: {
/* n:"FrtWrapper", */
},
2130: {
/* n:"StartBlock", */
},
2131: {
/* n:"EndBlock", */
},
2132: {
/* n:"StartObject", */
},
2133: {
/* n:"EndObject", */
},
2134: {
/* n:"CatLab", */
},
2135: {
/* n:"YMult", */
},
2136: {
/* n:"SXViewLink", */
},
2137: {
/* n:"PivotChartBits", */
},
2138: {
/* n:"FrtFontList", */
},
2146: {
/* n:"SheetExt", */
},
2147: {
/* n:"BookExt", */
r: 12
},
2148: {
/* n:"SXAddl", */
},
2149: {
/* n:"CrErr", */
},
2150: {
/* n:"HFPicture", */
},
2151: {
/* n:"FeatHdr", */
f: parsenoop2
},
2152: {
/* n:"Feat", */
},
2154: {
/* n:"DataLabExt", */
},
2155: {
/* n:"DataLabExtContents", */
},
2156: {
/* n:"CellWatch", */
},
2161: {
/* n:"FeatHdr11", */
},
2162: {
/* n:"Feature11", */
},
2164: {
/* n:"DropDownObjIds", */
},
2165: {
/* n:"ContinueFrt11", */
},
2166: {
/* n:"DConn", */
},
2167: {
/* n:"List12", */
},
2168: {
/* n:"Feature12", */
},
2169: {
/* n:"CondFmt12", */
},
2170: {
/* n:"CF12", */
},
2171: {
/* n:"CFEx", */
},
2172: {
/* n:"XFCRC", */
f: parse_XFCRC,
r: 12
},
2173: {
/* n:"XFExt", */
f: parse_XFExt,
r: 12
},
2174: {
/* n:"AutoFilter12", */
},
2175: {
/* n:"ContinueFrt12", */
},
2180: {
/* n:"MDTInfo", */
},
2181: {
/* n:"MDXStr", */
},
2182: {
/* n:"MDXTuple", */
},
2183: {
/* n:"MDXSet", */
},
2184: {
/* n:"MDXProp", */
},
2185: {
/* n:"MDXKPI", */
},
2186: {
/* n:"MDB", */
},
2187: {
/* n:"PLV", */
},
2188: {
/* n:"Compat12", */
f: parsebool,
r: 12
},
2189: {
/* n:"DXF", */
},
2190: {
/* n:"TableStyles", */
r: 12
},
2191: {
/* n:"TableStyle", */
},
2192: {
/* n:"TableStyleElement", */
},
2194: {
/* n:"StyleExt", */
},
2195: {
/* n:"NamePublish", */
},
2196: {
/* n:"NameCmt", */
f: parse_NameCmt,
r: 12
},
2197: {
/* n:"SortData", */
},
2198: {
/* n:"Theme", */
f: parse_Theme,
r: 12
},
2199: {
/* n:"GUIDTypeLib", */
},
2200: {
/* n:"FnGrp12", */
},
2201: {
/* n:"NameFnGrp12", */
},
2202: {
/* n:"MTRSettings", */
f: parse_MTRSettings,
r: 12
},
2203: {
/* n:"CompressPictures", */
f: parsenoop2
},
2204: {
/* n:"HeaderFooter", */
},
2205: {
/* n:"CrtLayout12", */
},
2206: {
/* n:"CrtMlFrt", */
},
2207: {
/* n:"CrtMlFrtContinue", */
},
2211: {
/* n:"ForceFullCalculation", */
f: parse_ForceFullCalculation
},
2212: {
/* n:"ShapePropsStream", */
},
2213: {
/* n:"TextPropsStream", */
},
2214: {
/* n:"RichTextStream", */
},
2215: {
/* n:"CrtLayout12A", */
},
4097: {
/* n:"Units", */
},
4098: {
/* n:"Chart", */
},
4099: {
/* n:"Series", */
},
4102: {
/* n:"DataFormat", */
},
4103: {
/* n:"LineFormat", */
},
4105: {
/* n:"MarkerFormat", */
},
4106: {
/* n:"AreaFormat", */
},
4107: {
/* n:"PieFormat", */
},
4108: {
/* n:"AttachedLabel", */
},
4109: {
/* n:"SeriesText", */
},
4116: {
/* n:"ChartFormat", */
},
4117: {
/* n:"Legend", */
},
4118: {
/* n:"SeriesList", */
},
4119: {
/* n:"Bar", */
},
4120: {
/* n:"Line", */
},
4121: {
/* n:"Pie", */
},
4122: {
/* n:"Area", */
},
4123: {
/* n:"Scatter", */
},
4124: {
/* n:"CrtLine", */
},
4125: {
/* n:"Axis", */
},
4126: {
/* n:"Tick", */
},
4127: {
/* n:"ValueRange", */
},
4128: {
/* n:"CatSerRange", */
},
4129: {
/* n:"AxisLine", */
},
4130: {
/* n:"CrtLink", */
},
4132: {
/* n:"DefaultText", */
},
4133: {
/* n:"Text", */
},
4134: {
/* n:"FontX", */
f: parseuint16
},
4135: {
/* n:"ObjectLink", */
},
4146: {
/* n:"Frame", */
},
4147: {
/* n:"Begin", */
},
4148: {
/* n:"End", */
},
4149: {
/* n:"PlotArea", */
},
4154: {
/* n:"Chart3d", */
},
4156: {
/* n:"PicF", */
},
4157: {
/* n:"DropBar", */
},
4158: {
/* n:"Radar", */
},
4159: {
/* n:"Surf", */
},
4160: {
/* n:"RadarArea", */
},
4161: {
/* n:"AxisParent", */
},
4163: {
/* n:"LegendException", */
},
4164: {
/* n:"ShtProps", */
f: parse_ShtProps
},
4165: {
/* n:"SerToCrt", */
},
4166: {
/* n:"AxesUsed", */
},
4168: {
/* n:"SBaseRef", */
},
4170: {
/* n:"SerParent", */
},
4171: {
/* n:"SerAuxTrend", */
},
4174: {
/* n:"IFmtRecord", */
},
4175: {
/* n:"Pos", */
},
4176: {
/* n:"AlRuns", */
},
4177: {
/* n:"BRAI", */
},
4187: {
/* n:"SerAuxErrBar", */
},
4188: {
/* n:"ClrtClient", */
f: parse_ClrtClient
},
4189: {
/* n:"SerFmt", */
},
4191: {
/* n:"Chart3DBarShape", */
},
4192: {
/* n:"Fbi", */
},
4193: {
/* n:"BopPop", */
},
4194: {
/* n:"AxcExt", */
},
4195: {
/* n:"Dat", */
},
4196: {
/* n:"PlotGrowth", */
},
4197: {
/* n:"SIIndex", */
},
4198: {
/* n:"GelFrame", */
},
4199: {
/* n:"BopPopCustom", */
},
4200: {
/* n:"Fbi2", */
},
0: {
/* n:"Dimensions", */
f: parse_Dimensions
},
1: {
/* n:"BIFF2BLANK", */
},
2: {
/* n:"BIFF2INT", */
f: parse_BIFF2INT
},
3: {
/* n:"BIFF2NUM", */
f: parse_BIFF2NUM
},
4: {
/* n:"BIFF2STR", */
f: parse_BIFF2STR
},
5: {
/* n:"BIFF2BOOLERR", */
f: parse_BIFF2BOOLERR
},
7: {
/* n:"String", */
f: parse_BIFF2STRING
},
8: {
/* n:"BIFF2ROW", */
},
9: {
/* n:"BOF", */
f: parse_BOF
},
11: {
/* n:"Index", */
},
22: {
/* n:"ExternCount", */
f: parseuint16
},
30: {
/* n:"BIFF2FORMAT", */
f: parse_BIFF2Format
},
31: {
/* n:"BIFF2FMTCNT", */
},
/* 16-bit cnt of BIFF2FORMAT records */
32: {
/* n:"BIFF2COLINFO", */
},
33: {
/* n:"Array", */
f: parse_Array
},
36: {
/* n:"COLWIDTH", */
},
37: {
/* n:"DefaultRowHeight", */
f: parse_DefaultRowHeight
},
// 0x002c ??
// 0x002d ??
// 0x002e ??
// 0x0030 FONTCOUNT: number of fonts
50: {
/* n:"BIFF2FONTXTRA", */
f: parse_BIFF2FONTXTRA
},
// 0x0035: INFOOPTS
// 0x0036: TABLE (BIFF2 only)
// 0x0037: TABLE2 (BIFF2 only)
// 0x0038: WNDESK
// 0x0039 ??
// 0x003a: BEGINPREF
// 0x003b: ENDPREF
62: {
/* n:"BIFF2WINDOW2", */
},
// 0x003f ??
// 0x0046: SHOWSCROLL
// 0x0047: SHOWFORMULA
// 0x0048: STATUSBAR
// 0x0049: SHORTMENUS
// 0x004A:
// 0x004B:
// 0x004C:
// 0x004E:
// 0x004F:
// 0x0058: TOOLBAR (BIFF3)
/* - - - */
52: {
/* n:"DDEObjName", */
},
67: {
/* n:"BIFF2XF", */
f: parse_BIFF2XF
},
68: {
/* n:"BIFF2XFINDEX", */
f: parseuint16
},
69: {
/* n:"BIFF2FONTCLR", */
},
86: {
/* n:"BIFF4FMTCNT", */
},
/* 16-bit cnt, similar to BIFF2 */
126: {
/* n:"RK", */
},
/* Not necessarily same as 0x027e */
127: {
/* n:"ImData", */
f: parse_ImData
},
135: {
/* n:"Addin", */
},
136: {
/* n:"Edg", */
},
137: {
/* n:"Pub", */
},
// 0x8A
// 0x8B LH: alternate menu key flag (BIFF3/4)
// 0x8E
143: {
/* n:"BIFF4SheetInfo", */
f: parse_BIFF4SheetInfo
},
145: {
/* n:"Sub", */
},
// 0x93 STYLE
148: {
/* n:"LHRecord", */
},
149: {
/* n:"LHNGraph", */
},
150: {
/* n:"Sound", */
},
// 0xA2 FNPROTO: function prototypes (BIFF4)
// 0xA3
// 0xA8
169: {
/* n:"CoordList", */
},
171: {
/* n:"GCW", */
},
188: {
/* n:"ShrFmla", */
},
/* Not necessarily same as 0x04bc */
191: {
/* n:"ToolbarHdr", */
},
192: {
/* n:"ToolbarEnd", */
},
194: {
/* n:"AddMenu", */
},
195: {
/* n:"DelMenu", */
},
214: {
/* n:"RString", */
f: parse_RString
},
223: {
/* n:"UDDesc", */
},
234: {
/* n:"TabIdConf", */
},
354: {
/* n:"XL5Modify", */
},
421: {
/* n:"FileSharing2", */
},
518: {
/* n:"Formula", */
f: parse_Formula
},
521: {
/* n:"BOF", */
f: parse_BOF
},
536: {
/* n:"Lbl", */
f: parse_Lbl
},
547: {
/* n:"ExternName", */
f: parse_ExternName
},
561: {
/* n:"Font", */
},
579: {
/* n:"BIFF3XF", */
f: parse_BIFF3XF
},
1030: {
/* n:"Formula", */
f: parse_Formula
},
1033: {
/* n:"BOF", */
f: parse_BOF
},
1091: {
/* n:"BIFF4XF", */
f: parse_BIFF4XF
},
2157: {
/* n:"FeatInfo", */
},
2163: {
/* n:"FeatInfo11", */
},
2177: {
/* n:"SXAddl12", */
},
2240: {
/* n:"AutoWebPub", */
},
2241: {
/* n:"ListObj", */
},
2242: {
/* n:"ListField", */
},
2243: {
/* n:"ListDV", */
},
2244: {
/* n:"ListCondFmt", */
},
2245: {
/* n:"ListCF", */
},
2246: {
/* n:"FMQry", */
},
2247: {
/* n:"FMSQry", */
},
2248: {
/* n:"PLV", */
},
2249: {
/* n:"LnExt", */
},
2250: {
/* n:"MkrExt", */
},
2251: {
/* n:"CrtCoopt", */
},
2262: {
/* n:"FRTArchId$", */
r: 12
},
/* --- multiplan 4 records --- */
101: {
/* n:"", */
},
// one per window
102: {
/* n:"", */
},
// calc settings
105: {
/* n:"", */
},
// print header
106: {
/* n:"", */
},
// print footer
107: {
/* n:"", */
},
// print settings
109: {
/* n:"", */
},
// one per window
112: {
/* n:"", */
},
// includes default col width
114: {
/* n:"", */
},
// includes selected cell
29282: {}
};
HTML_BEGIN = 'SheetJS Table Export ';
HTML_END = "";
subarray = (function() {
try {
if (typeof Uint8Array == "undefined")
return "slice";
if (typeof Uint8Array.prototype.subarray == "undefined")
return "slice";
if (typeof Buffer !== "undefined") {
if (typeof Buffer.prototype.subarray == "undefined")
return "slice";
if ((typeof Buffer.from == "function" ? Buffer.from([72, 62]) : new Buffer([72, 62])) instanceof Uint8Array)
return "subarray";
return "slice";
}
return "subarray";
} catch (e9) {
return "slice";
}
})();
numbers_lut_new = function() {
return { sst: [], rsst: [], ofmt: [], nfmt: [], fmla: [], ferr: [], cmnt: [] };
};
qreg = /"/g;
utils = {
encode_col,
encode_row,
encode_cell,
encode_range,
decode_col,
decode_row,
split_cell,
decode_cell,
decode_range,
format_cell,
sheet_new,
sheet_add_aoa,
sheet_add_json,
sheet_add_dom,
aoa_to_sheet,
json_to_sheet,
table_to_sheet: parse_dom_table,
table_to_book,
sheet_to_csv,
sheet_to_txt,
sheet_to_json,
sheet_to_html,
sheet_to_formulae,
sheet_to_row_object_array: sheet_to_json,
sheet_get_cell: ws_get_cell_stub,
book_new,
book_append_sheet,
book_set_sheet_visibility,
cell_set_number_format,
cell_set_hyperlink,
cell_set_internal_link,
cell_add_comment,
sheet_set_array_formula,
consts: {
SHEET_VISIBLE: 0,
SHEET_HIDDEN: 1,
SHEET_VERY_HIDDEN: 2
}
};
version3 = XLSX.version;
}
});
// ../pi-mono/packages/web-ui/dist/utils/attachment-utils.js
async function loadAttachment(source, fileName) {
let arrayBuffer;
let detectedFileName = fileName || "unnamed";
let mimeType = "application/octet-stream";
let size = 0;
if (typeof source === "string") {
const response = await fetch(source);
if (!response.ok) {
throw new Error(i18n("Failed to fetch file"));
}
arrayBuffer = await response.arrayBuffer();
size = arrayBuffer.byteLength;
mimeType = response.headers.get("content-type") || mimeType;
if (!fileName) {
const urlParts = source.split("/");
detectedFileName = urlParts[urlParts.length - 1] || "document";
}
} else if (source instanceof File) {
arrayBuffer = await source.arrayBuffer();
size = source.size;
mimeType = source.type || mimeType;
detectedFileName = fileName || source.name;
} else if (source instanceof Blob) {
arrayBuffer = await source.arrayBuffer();
size = source.size;
mimeType = source.type || mimeType;
} else if (source instanceof ArrayBuffer) {
arrayBuffer = source;
size = source.byteLength;
} else {
throw new Error(i18n("Invalid source type"));
}
const uint8Array = new Uint8Array(arrayBuffer);
let binary = "";
const chunkSize = 32768;
for (let i7 = 0; i7 < uint8Array.length; i7 += chunkSize) {
const chunk = uint8Array.slice(i7, i7 + chunkSize);
binary += String.fromCharCode(...chunk);
}
const base64Content = btoa(binary);
const id = `${detectedFileName}_${Date.now()}_${Math.random()}`;
if (mimeType === "application/pdf" || detectedFileName.toLowerCase().endsWith(".pdf")) {
const { extractedText, preview } = await processPdf(arrayBuffer, detectedFileName);
return {
id,
type: "document",
fileName: detectedFileName,
mimeType: "application/pdf",
size,
content: base64Content,
extractedText,
preview
};
}
if (mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || detectedFileName.toLowerCase().endsWith(".docx")) {
const { extractedText } = await processDocx(arrayBuffer, detectedFileName);
return {
id,
type: "document",
fileName: detectedFileName,
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
size,
content: base64Content,
extractedText
};
}
if (mimeType === "application/vnd.openxmlformats-officedocument.presentationml.presentation" || detectedFileName.toLowerCase().endsWith(".pptx")) {
const { extractedText } = await processPptx(arrayBuffer, detectedFileName);
return {
id,
type: "document",
fileName: detectedFileName,
mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
size,
content: base64Content,
extractedText
};
}
const excelMimeTypes = [
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-excel"
];
if (excelMimeTypes.includes(mimeType) || detectedFileName.toLowerCase().endsWith(".xlsx") || detectedFileName.toLowerCase().endsWith(".xls")) {
const { extractedText } = await processExcel(arrayBuffer, detectedFileName);
return {
id,
type: "document",
fileName: detectedFileName,
mimeType: mimeType.startsWith("application/vnd") ? mimeType : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
size,
content: base64Content,
extractedText
};
}
if (mimeType.startsWith("image/")) {
return {
id,
type: "image",
fileName: detectedFileName,
mimeType,
size,
content: base64Content,
preview: base64Content
// For images, preview is the same as content
};
}
const textExtensions = [
".txt",
".md",
".json",
".xml",
".html",
".css",
".js",
".ts",
".jsx",
".tsx",
".yml",
".yaml"
];
const isTextFile = mimeType.startsWith("text/") || textExtensions.some((ext2) => detectedFileName.toLowerCase().endsWith(ext2));
if (isTextFile) {
const decoder = new TextDecoder();
const text3 = decoder.decode(arrayBuffer);
return {
id,
type: "document",
fileName: detectedFileName,
mimeType: mimeType.startsWith("text/") ? mimeType : "text/plain",
size,
content: base64Content,
extractedText: text3
};
}
throw new Error(`Unsupported file type: ${mimeType}`);
}
async function processPdf(arrayBuffer, fileName) {
let pdf = null;
try {
pdf = await getDocument({ data: arrayBuffer }).promise;
let extractedText = ``;
for (let i7 = 1; i7 <= pdf.numPages; i7++) {
const page = await pdf.getPage(i7);
const textContent = await page.getTextContent();
const pageText = textContent.items.map((item) => item.str).filter((str2) => str2.trim()).join(" ");
extractedText += `
${pageText}
`;
}
extractedText += "\n ";
const preview = await generatePdfPreview(pdf);
return { extractedText, preview };
} catch (error) {
console.error("Error processing PDF:", error);
throw new Error(`Failed to process PDF: ${String(error)}`);
} finally {
if (pdf) {
pdf.destroy();
}
}
}
async function generatePdfPreview(pdf) {
try {
const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 1 });
const scale = Math.min(160 / viewport.width, 160 / viewport.height);
const scaledViewport = page.getViewport({ scale });
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
if (!context) {
return void 0;
}
canvas.height = scaledViewport.height;
canvas.width = scaledViewport.width;
const renderContext = {
canvasContext: context,
viewport: scaledViewport,
canvas
};
await page.render(renderContext).promise;
return canvas.toDataURL("image/png").split(",")[1];
} catch (error) {
console.error("Error generating PDF preview:", error);
return void 0;
}
}
async function processDocx(arrayBuffer, fileName) {
try {
const wordDoc = await parseAsync(arrayBuffer);
let extractedText = `
`;
const body = wordDoc.documentPart?.body;
if (body?.children) {
const texts = [];
for (const element of body.children) {
const text3 = extractTextFromElement(element);
if (text3) {
texts.push(text3);
}
}
extractedText += texts.join("\n");
}
extractedText += `
`;
return { extractedText };
} catch (error) {
console.error("Error processing DOCX:", error);
throw new Error(`Failed to process DOCX: ${String(error)}`);
}
}
function extractTextFromElement(element) {
let text3 = "";
const elementType = element.type?.toLowerCase() || "";
if (elementType === "paragraph" && element.children) {
for (const child of element.children) {
const childType = child.type?.toLowerCase() || "";
if (childType === "run" && child.children) {
for (const textChild of child.children) {
const textType = textChild.type?.toLowerCase() || "";
if (textType === "text") {
text3 += textChild.text || "";
}
}
} else if (childType === "text") {
text3 += child.text || "";
}
}
} else if (elementType === "table") {
if (element.children) {
const tableTexts = [];
for (const row of element.children) {
const rowType = row.type?.toLowerCase() || "";
if (rowType === "tablerow" && row.children) {
const rowTexts = [];
for (const cell of row.children) {
const cellType = cell.type?.toLowerCase() || "";
if (cellType === "tablecell" && cell.children) {
const cellTexts = [];
for (const cellElement of cell.children) {
const cellText = extractTextFromElement(cellElement);
if (cellText)
cellTexts.push(cellText);
}
if (cellTexts.length > 0)
rowTexts.push(cellTexts.join(" "));
}
}
if (rowTexts.length > 0)
tableTexts.push(rowTexts.join(" | "));
}
}
if (tableTexts.length > 0) {
text3 = `
[Table]
${tableTexts.join("\n")}
[/Table]
`;
}
}
} else if (element.children && Array.isArray(element.children)) {
const childTexts = [];
for (const child of element.children) {
const childText = extractTextFromElement(child);
if (childText)
childTexts.push(childText);
}
text3 = childTexts.join(" ");
}
return text3.trim();
}
async function processPptx(arrayBuffer, fileName) {
try {
const zip = await import_jszip2.default.loadAsync(arrayBuffer);
let extractedText = ``;
const slideFiles = Object.keys(zip.files).filter((name) => name.match(/ppt\/slides\/slide\d+\.xml$/)).sort((a3, b4) => {
const numA = Number.parseInt(a3.match(/slide(\d+)\.xml$/)?.[1] || "0", 10);
const numB = Number.parseInt(b4.match(/slide(\d+)\.xml$/)?.[1] || "0", 10);
return numA - numB;
});
for (let i7 = 0; i7 < slideFiles.length; i7++) {
const slideFile = zip.file(slideFiles[i7]);
if (slideFile) {
const slideXml = await slideFile.async("text");
const textMatches = slideXml.match(/]*>([^<]+)<\/a:t>/g);
if (textMatches) {
extractedText += `
`;
const slideTexts = textMatches.map((match2) => {
const textMatch = match2.match(/]*>([^<]+)<\/a:t>/);
return textMatch ? textMatch[1] : "";
}).filter((t6) => t6.trim());
if (slideTexts.length > 0) {
extractedText += `
${slideTexts.join("\n")}`;
}
extractedText += "\n ";
}
}
}
const notesFiles = Object.keys(zip.files).filter((name) => name.match(/ppt\/notesSlides\/notesSlide\d+\.xml$/)).sort((a3, b4) => {
const numA = Number.parseInt(a3.match(/notesSlide(\d+)\.xml$/)?.[1] || "0", 10);
const numB = Number.parseInt(b4.match(/notesSlide(\d+)\.xml$/)?.[1] || "0", 10);
return numA - numB;
});
if (notesFiles.length > 0) {
extractedText += "\n";
for (const noteFile of notesFiles) {
const file = zip.file(noteFile);
if (file) {
const noteXml = await file.async("text");
const textMatches = noteXml.match(/]*>([^<]+)<\/a:t>/g);
if (textMatches) {
const noteTexts = textMatches.map((match2) => {
const textMatch = match2.match(/]*>([^<]+)<\/a:t>/);
return textMatch ? textMatch[1] : "";
}).filter((t6) => t6.trim());
if (noteTexts.length > 0) {
const slideNum = noteFile.match(/notesSlide(\d+)\.xml$/)?.[1];
extractedText += `
[Slide ${slideNum} notes]: ${noteTexts.join(" ")}`;
}
}
}
}
extractedText += "\n ";
}
extractedText += "\n ";
return { extractedText };
} catch (error) {
console.error("Error processing PPTX:", error);
throw new Error(`Failed to process PPTX: ${String(error)}`);
}
}
async function processExcel(arrayBuffer, fileName) {
try {
const workbook = readSync(arrayBuffer, { type: "array" });
let extractedText = ``;
for (const [index2, sheetName] of workbook.SheetNames.entries()) {
const worksheet = workbook.Sheets[sheetName];
const csvText = utils.sheet_to_csv(worksheet);
extractedText += `
${csvText}
`;
}
extractedText += "\n ";
return { extractedText };
} catch (error) {
console.error("Error processing Excel:", error);
throw new Error(`Failed to process Excel: ${String(error)}`);
}
}
var import_jszip2;
var init_attachment_utils = __esm({
"../pi-mono/packages/web-ui/dist/utils/attachment-utils.js"() {
"use strict";
init_process_shim();
init_docx_preview();
import_jszip2 = __toESM(require_jszip_min(), 1);
init_pdf();
init_xlsx();
init_i18n2();
GlobalWorkerOptions.workerSrc = new URL("pdfjs-dist/build/pdf.worker.min.mjs", import.meta.url).toString();
}
});
// node_modules/lit/html.js
var init_html = __esm({
"node_modules/lit/html.js"() {
init_process_shim();
init_lit_html();
}
});
// ../mini-lit/dist/ModeToggle.js
var __decorate3, ModeToggle;
var init_ModeToggle = __esm({
"../mini-lit/dist/ModeToggle.js"() {
"use strict";
init_process_shim();
init_lit();
init_decorators();
init_i18n();
__decorate3 = function(decorators, target, key, desc) {
var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
ModeToggle = class ModeToggle2 extends i4 {
constructor() {
super(...arguments);
this.modes = [i18n("Mode 1"), i18n("Mode 2")];
this.selectedIndex = 0;
}
createRenderRoot() {
return this;
}
setMode(index2) {
if (this.selectedIndex !== index2 && index2 >= 0 && index2 < this.modes.length) {
this.selectedIndex = index2;
this.dispatchEvent(new CustomEvent("mode-change", {
detail: { index: index2, mode: this.modes[index2] },
bubbles: true
}));
}
}
render() {
if (this.modes.length < 2)
return b2``;
return b2`
${this.modes.map((mode, index2) => b2`
`)}
`;
}
};
__decorate3([
n6({ type: Array })
], ModeToggle.prototype, "modes", void 0);
__decorate3([
n6({ type: Number })
], ModeToggle.prototype, "selectedIndex", void 0);
ModeToggle = __decorate3([
t5("mode-toggle")
], ModeToggle);
}
});
// ../pi-mono/packages/web-ui/dist/dialogs/AttachmentOverlay.js
var __decorate4, AttachmentOverlay;
var init_AttachmentOverlay = __esm({
"../pi-mono/packages/web-ui/dist/dialogs/AttachmentOverlay.js"() {
"use strict";
init_process_shim();
init_ModeToggle();
init_dist();
init_Button();
init_docx_preview();
init_lit();
init_decorators();
init_lucide2();
init_pdf();
init_xlsx();
init_i18n2();
__decorate4 = function(decorators, target, key, desc) {
var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
AttachmentOverlay = class _AttachmentOverlay extends i4 {
constructor() {
super(...arguments);
this.showExtractedText = false;
this.error = null;
this.currentLoadingTask = null;
this.handleBackdropClick = () => {
this.close();
};
this.handleDownload = () => {
if (!this.attachment)
return;
const byteCharacters = atob(this.attachment.content);
const byteNumbers = new Array(byteCharacters.length);
for (let i7 = 0; i7 < byteCharacters.length; i7++) {
byteNumbers[i7] = byteCharacters.charCodeAt(i7);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: this.attachment.mimeType });
const url = URL.createObjectURL(blob);
const a3 = document.createElement("a");
a3.href = url;
a3.download = this.attachment.fileName;
document.body.appendChild(a3);
a3.click();
document.body.removeChild(a3);
URL.revokeObjectURL(url);
};
}
createRenderRoot() {
return this;
}
static open(attachment, onClose) {
const overlay = new _AttachmentOverlay();
overlay.attachment = attachment;
overlay.onCloseCallback = onClose;
document.body.appendChild(overlay);
overlay.setupEventListeners();
}
setupEventListeners() {
this.boundHandleKeyDown = (e9) => {
if (e9.key === "Escape") {
this.close();
}
};
window.addEventListener("keydown", this.boundHandleKeyDown);
}
close() {
this.cleanup();
if (this.boundHandleKeyDown) {
window.removeEventListener("keydown", this.boundHandleKeyDown);
}
this.onCloseCallback?.();
this.remove();
}
getFileType() {
if (!this.attachment)
return "text";
if (this.attachment.type === "image")
return "image";
if (this.attachment.mimeType === "application/pdf")
return "pdf";
if (this.attachment.mimeType?.includes("wordprocessingml"))
return "docx";
if (this.attachment.mimeType?.includes("presentationml") || this.attachment.fileName.toLowerCase().endsWith(".pptx"))
return "pptx";
if (this.attachment.mimeType?.includes("spreadsheetml") || this.attachment.mimeType?.includes("ms-excel") || this.attachment.fileName.toLowerCase().endsWith(".xlsx") || this.attachment.fileName.toLowerCase().endsWith(".xls"))
return "excel";
return "text";
}
getFileTypeLabel() {
const type = this.getFileType();
switch (type) {
case "pdf":
return i18n("PDF");
case "docx":
return i18n("Document");
case "pptx":
return i18n("Presentation");
case "excel":
return i18n("Spreadsheet");
default:
return "";
}
}
cleanup() {
this.showExtractedText = false;
this.error = null;
if (this.currentLoadingTask) {
this.currentLoadingTask.destroy();
this.currentLoadingTask = null;
}
}
render() {
if (!this.attachment)
return b2``;
return b2`
e9.stopPropagation()}>
${this.attachment.fileName}
${this.renderToggle()}
${Button({
variant: "ghost",
size: "icon",
onClick: this.handleDownload,
children: icon(Download2, "sm"),
className: "h-8 w-8"
})}
${Button({
variant: "ghost",
size: "icon",
onClick: () => this.close(),
children: icon(X, "sm"),
className: "h-8 w-8"
})}
e9.stopPropagation()}>
${this.renderContent()}
`;
}
renderToggle() {
if (!this.attachment)
return b2``;
const fileType = this.getFileType();
const hasExtractedText = !!this.attachment.extractedText;
const showToggle = fileType !== "image" && fileType !== "text" && fileType !== "pptx" && hasExtractedText;
if (!showToggle)
return b2``;
const fileTypeLabel = this.getFileTypeLabel();
return b2`
{
e9.stopPropagation();
this.showExtractedText = e9.detail.index === 1;
this.error = null;
}}
>
`;
}
renderContent() {
if (!this.attachment)
return b2``;
if (this.error) {
return b2`
${i18n("Error loading file")}
${this.error}
`;
}
return this.renderFileContent();
}
renderFileContent() {
if (!this.attachment)
return b2``;
const fileType = this.getFileType();
if (this.showExtractedText && fileType !== "image") {
return b2`
${this.attachment.extractedText || i18n("No text content available")}
`;
}
switch (fileType) {
case "image": {
const imageUrl = `data:${this.attachment.mimeType};base64,${this.attachment.content}`;
return b2`
`;
}
case "pdf":
return b2`
`;
case "docx":
return b2`
`;
case "excel":
return b2` `;
case "pptx":
return b2`
`;
default:
return b2`
${this.attachment.extractedText || i18n("No content available")}
`;
}
}
async updated(changedProperties) {
super.updated(changedProperties);
if ((changedProperties.has("attachment") || changedProperties.has("showExtractedText")) && this.attachment && !this.showExtractedText && !this.error) {
const fileType = this.getFileType();
switch (fileType) {
case "pdf":
await this.renderPdf();
break;
case "docx":
await this.renderDocx();
break;
case "excel":
await this.renderExcel();
break;
case "pptx":
await this.renderExtractedText();
break;
}
}
}
async renderPdf() {
const container = this.querySelector("#pdf-container");
if (!container || !this.attachment)
return;
let pdf = null;
try {
const arrayBuffer = this.base64ToArrayBuffer(this.attachment.content);
if (this.currentLoadingTask) {
this.currentLoadingTask.destroy();
}
this.currentLoadingTask = getDocument({ data: arrayBuffer });
pdf = await this.currentLoadingTask.promise;
this.currentLoadingTask = null;
container.innerHTML = "";
const wrapper = document.createElement("div");
wrapper.className = "";
container.appendChild(wrapper);
for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
const page = await pdf.getPage(pageNum);
const pageContainer = document.createElement("div");
pageContainer.className = "mb-4 last:mb-0";
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
const viewport = page.getViewport({ scale: 1.5 });
canvas.height = viewport.height;
canvas.width = viewport.width;
canvas.className = "w-full max-w-full h-auto block mx-auto bg-white rounded shadow-sm border border-border";
if (context) {
context.fillStyle = "white";
context.fillRect(0, 0, canvas.width, canvas.height);
}
await page.render({
canvasContext: context,
viewport,
canvas
}).promise;
pageContainer.appendChild(canvas);
if (pageNum < pdf.numPages) {
const separator = document.createElement("div");
separator.className = "h-px bg-border my-4";
pageContainer.appendChild(separator);
}
wrapper.appendChild(pageContainer);
}
} catch (error) {
console.error("Error rendering PDF:", error);
this.error = error?.message || i18n("Failed to load PDF");
} finally {
if (pdf) {
pdf.destroy();
}
}
}
async renderDocx() {
const container = this.querySelector("#docx-container");
if (!container || !this.attachment)
return;
try {
const arrayBuffer = this.base64ToArrayBuffer(this.attachment.content);
container.innerHTML = "";
const wrapper = document.createElement("div");
wrapper.className = "docx-wrapper-custom";
container.appendChild(wrapper);
await renderAsync(arrayBuffer, wrapper, void 0, {
className: "docx",
inWrapper: true,
ignoreWidth: true,
// Let it be responsive
ignoreHeight: false,
ignoreFonts: false,
breakPages: true,
ignoreLastRenderedPageBreak: true,
experimental: false,
trimXmlDeclaration: true,
useBase64URL: false,
renderHeaders: true,
renderFooters: true,
renderFootnotes: true,
renderEndnotes: true
});
const style = document.createElement("style");
style.textContent = `
#docx-container {
padding: 0;
}
#docx-container .docx-wrapper-custom {
max-width: 100%;
overflow-x: auto;
}
#docx-container .docx-wrapper {
max-width: 100% !important;
margin: 0 !important;
background: transparent !important;
padding: 0em !important;
}
#docx-container .docx-wrapper > section.docx {
box-shadow: none !important;
border: none !important;
border-radius: 0 !important;
margin: 0 !important;
padding: 2em !important;
background: white !important;
color: black !important;
max-width: 100% !important;
width: 100% !important;
min-width: 0 !important;
overflow-x: auto !important;
}
/* Fix tables and wide content */
#docx-container table {
max-width: 100% !important;
width: auto !important;
overflow-x: auto !important;
display: block !important;
}
#docx-container img {
max-width: 100% !important;
height: auto !important;
}
/* Fix paragraphs and text */
#docx-container p,
#docx-container span,
#docx-container div {
max-width: 100% !important;
word-wrap: break-word !important;
overflow-wrap: break-word !important;
}
/* Hide page breaks in web view */
#docx-container .docx-page-break {
display: none !important;
}
`;
container.appendChild(style);
} catch (error) {
console.error("Error rendering DOCX:", error);
this.error = error?.message || i18n("Failed to load document");
}
}
async renderExcel() {
const container = this.querySelector("#excel-container");
if (!container || !this.attachment)
return;
try {
const arrayBuffer = this.base64ToArrayBuffer(this.attachment.content);
const workbook = readSync(arrayBuffer, { type: "array" });
container.innerHTML = "";
const wrapper = document.createElement("div");
wrapper.className = "overflow-auto h-full flex flex-col";
container.appendChild(wrapper);
if (workbook.SheetNames.length > 1) {
const tabContainer = document.createElement("div");
tabContainer.className = "flex gap-2 mb-4 border-b border-border sticky top-0 bg-card z-10";
const sheetContents = [];
workbook.SheetNames.forEach((sheetName, index2) => {
const tab = document.createElement("button");
tab.textContent = sheetName;
tab.className = index2 === 0 ? "px-4 py-2 text-sm font-medium border-b-2 border-primary text-primary" : "px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:border-b-2 hover:border-border transition-colors";
const sheetDiv = document.createElement("div");
sheetDiv.style.display = index2 === 0 ? "flex" : "none";
sheetDiv.className = "flex-1 overflow-auto";
sheetDiv.appendChild(this.renderExcelSheet(workbook.Sheets[sheetName], sheetName));
sheetContents.push(sheetDiv);
tab.onclick = () => {
tabContainer.querySelectorAll("button").forEach((btn, btnIndex) => {
if (btnIndex === index2) {
btn.className = "px-4 py-2 text-sm font-medium border-b-2 border-primary text-primary";
} else {
btn.className = "px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:border-b-2 hover:border-border transition-colors";
}
});
sheetContents.forEach((content, contentIndex) => {
content.style.display = contentIndex === index2 ? "flex" : "none";
});
};
tabContainer.appendChild(tab);
});
wrapper.appendChild(tabContainer);
sheetContents.forEach((content) => {
wrapper.appendChild(content);
});
} else {
const sheetName = workbook.SheetNames[0];
wrapper.appendChild(this.renderExcelSheet(workbook.Sheets[sheetName], sheetName));
}
} catch (error) {
console.error("Error rendering Excel:", error);
this.error = error?.message || i18n("Failed to load spreadsheet");
}
}
renderExcelSheet(worksheet, sheetName) {
const sheetDiv = document.createElement("div");
const htmlTable = utils.sheet_to_html(worksheet, { id: `sheet-${sheetName}` });
const tempDiv = document.createElement("div");
tempDiv.innerHTML = htmlTable;
const table = tempDiv.querySelector("table");
if (table) {
table.className = "w-full border-collapse text-foreground";
table.querySelectorAll("td, th").forEach((cell) => {
const cellEl = cell;
cellEl.className = "border border-border px-3 py-2 text-sm text-left";
});
const headerCells = table.querySelectorAll("thead th, tr:first-child td");
if (headerCells.length > 0) {
headerCells.forEach((th) => {
const thEl = th;
thEl.className = "border border-border px-3 py-2 text-sm font-semibold bg-muted text-foreground sticky top-0";
});
}
table.querySelectorAll("tbody tr:nth-child(even)").forEach((row) => {
const rowEl = row;
rowEl.className = "bg-muted/30";
});
sheetDiv.appendChild(table);
}
return sheetDiv;
}
base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i7 = 0; i7 < binaryString.length; i7++) {
bytes[i7] = binaryString.charCodeAt(i7);
}
return bytes.buffer;
}
async renderExtractedText() {
const container = this.querySelector("#pptx-container");
if (!container || !this.attachment)
return;
try {
container.innerHTML = "";
const wrapper = document.createElement("div");
wrapper.className = "p-6 overflow-auto";
const pre = document.createElement("pre");
pre.className = "whitespace-pre-wrap text-sm text-foreground font-mono";
pre.textContent = this.attachment.extractedText || i18n("No text content available");
wrapper.appendChild(pre);
container.appendChild(wrapper);
} catch (error) {
console.error("Error rendering extracted text:", error);
this.error = error?.message || i18n("Failed to display text content");
}
}
};
__decorate4([
r7()
], AttachmentOverlay.prototype, "attachment", void 0);
__decorate4([
r7()
], AttachmentOverlay.prototype, "showExtractedText", void 0);
__decorate4([
r7()
], AttachmentOverlay.prototype, "error", void 0);
if (!customElements.get("attachment-overlay")) {
customElements.define("attachment-overlay", AttachmentOverlay);
}
}
});
// ../pi-mono/packages/web-ui/dist/components/AttachmentTile.js
var __decorate5, AttachmentTile;
var init_AttachmentTile = __esm({
"../pi-mono/packages/web-ui/dist/components/AttachmentTile.js"() {
"use strict";
init_process_shim();
init_icons();
init_lit();
init_decorators();
init_html();
init_lucide2();
init_AttachmentOverlay();
init_i18n2();
__decorate5 = function(decorators, target, key, desc) {
var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
AttachmentTile = class AttachmentTile2 extends i4 {
constructor() {
super(...arguments);
this.showDelete = false;
this.handleClick = () => {
AttachmentOverlay.open(this.attachment);
};
}
createRenderRoot() {
return this;
}
connectedCallback() {
super.connectedCallback();
this.style.display = "block";
this.classList.add("max-h-16");
}
render() {
const hasPreview = !!this.attachment.preview;
const isImage = this.attachment.type === "image";
const isPdf = this.attachment.mimeType === "application/pdf";
const isExcel = this.attachment.mimeType?.includes("spreadsheetml") || this.attachment.fileName.toLowerCase().endsWith(".xlsx") || this.attachment.fileName.toLowerCase().endsWith(".xls");
const getDocumentIcon = () => {
if (isExcel)
return icon(FileSpreadsheet, "md");
return icon(FileText, "md");
};
return b2`
${hasPreview ? b2`
${isPdf ? b2`
${i18n("PDF")}
` : ""}
` : b2`
${getDocumentIcon()}
${this.attachment.fileName.length > 10 ? `${this.attachment.fileName.substring(0, 8)}...` : this.attachment.fileName}
`}
${this.showDelete ? b2`
` : ""}
`;
}
};
__decorate5([
n6({ type: Object })
], AttachmentTile.prototype, "attachment", void 0);
__decorate5([
n6({ type: Boolean })
], AttachmentTile.prototype, "showDelete", void 0);
__decorate5([
n6()
], AttachmentTile.prototype, "onDelete", void 0);
AttachmentTile = __decorate5([
t5("attachment-tile")
], AttachmentTile);
}
});
// ../pi-mono/packages/web-ui/dist/components/MessageEditor.js
var __decorate6, MessageEditor;
var init_MessageEditor = __esm({
"../pi-mono/packages/web-ui/dist/components/MessageEditor.js"() {
"use strict";
init_process_shim();
init_dist();
init_Button();
init_Select();
init_lit();
init_decorators();
init_ref2();
init_lucide2();
init_attachment_utils();
init_i18n2();
init_AttachmentTile();
__decorate6 = function(decorators, target, key, desc) {
var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
MessageEditor = class MessageEditor2 extends i4 {
constructor() {
super(...arguments);
this._value = "";
this.textareaRef = e5();
this.isStreaming = false;
this.thinkingLevel = "off";
this.showAttachmentButton = true;
this.showModelSelector = true;
this.showThinkingSelector = true;
this.attachments = [];
this.maxFiles = 10;
this.maxFileSize = 20 * 1024 * 1024;
this.acceptedTypes = "image/*,application/pdf,.docx,.pptx,.xlsx,.xls,.txt,.md,.json,.xml,.html,.css,.js,.ts,.jsx,.tsx,.yml,.yaml";
this.processingFiles = false;
this.isDragging = false;
this.fileInputRef = e5();
this.handleTextareaInput = (e9) => {
const textarea = e9.target;
this.value = textarea.value;
this.onInput?.(this.value);
};
this.handleKeyDown = (e9) => {
if (e9.key === "Enter" && !e9.shiftKey) {
e9.preventDefault();
if (!this.isStreaming && !this.processingFiles && (this.value.trim() || this.attachments.length > 0)) {
this.handleSend();
}
} else if (e9.key === "Escape" && this.isStreaming) {
e9.preventDefault();
this.onAbort?.();
}
};
this.handlePaste = async (e9) => {
const items = e9.clipboardData?.items;
if (!items)
return;
const imageFiles = [];
for (let i7 = 0; i7 < items.length; i7++) {
const item = items[i7];
if (item.type.startsWith("image/")) {
const file = item.getAsFile();
if (file) {
imageFiles.push(file);
}
}
}
if (imageFiles.length > 0) {
e9.preventDefault();
if (imageFiles.length + this.attachments.length > this.maxFiles) {
alert(`Maximum ${this.maxFiles} files allowed`);
return;
}
this.processingFiles = true;
const newAttachments = [];
for (const file of imageFiles) {
try {
if (file.size > this.maxFileSize) {
alert(`Image exceeds maximum size of ${Math.round(this.maxFileSize / 1024 / 1024)}MB`);
continue;
}
const attachment = await loadAttachment(file);
newAttachments.push(attachment);
} catch (error) {
console.error("Error processing pasted image:", error);
alert(`Failed to process pasted image: ${String(error)}`);
}
}
this.attachments = [...this.attachments, ...newAttachments];
this.onFilesChange?.(this.attachments);
this.processingFiles = false;
}
};
this.handleSend = () => {
this.onSend?.(this.value, this.attachments);
};
this.handleAttachmentClick = () => {
this.fileInputRef.value?.click();
};
this.handleDragOver = (e9) => {
e9.preventDefault();
e9.stopPropagation();
if (!this.isDragging) {
this.isDragging = true;
}
};
this.handleDragLeave = (e9) => {
e9.preventDefault();
e9.stopPropagation();
const rect = e9.currentTarget.getBoundingClientRect();
const x2 = e9.clientX;
const y4 = e9.clientY;
if (x2 <= rect.left || x2 >= rect.right || y4 <= rect.top || y4 >= rect.bottom) {
this.isDragging = false;
}
};
this.handleDrop = async (e9) => {
e9.preventDefault();
e9.stopPropagation();
this.isDragging = false;
const files = Array.from(e9.dataTransfer?.files || []);
if (files.length === 0)
return;
if (files.length + this.attachments.length > this.maxFiles) {
alert(`Maximum ${this.maxFiles} files allowed`);
return;
}
this.processingFiles = true;
const newAttachments = [];
for (const file of files) {
try {
if (file.size > this.maxFileSize) {
alert(`${file.name} exceeds maximum size of ${Math.round(this.maxFileSize / 1024 / 1024)}MB`);
continue;
}
const attachment = await loadAttachment(file);
newAttachments.push(attachment);
} catch (error) {
console.error(`Error processing ${file.name}:`, error);
alert(`Failed to process ${file.name}: ${String(error)}`);
}
}
this.attachments = [...this.attachments, ...newAttachments];
this.onFilesChange?.(this.attachments);
this.processingFiles = false;
};
}
get value() {
return this._value;
}
set value(val2) {
const oldValue = this._value;
this._value = val2;
this.requestUpdate("value", oldValue);
}
createRenderRoot() {
return this;
}
async handleFilesSelected(e9) {
const input = e9.target;
const files = Array.from(input.files || []);
if (files.length === 0)
return;
if (files.length + this.attachments.length > this.maxFiles) {
alert(`Maximum ${this.maxFiles} files allowed`);
input.value = "";
return;
}
this.processingFiles = true;
const newAttachments = [];
for (const file of files) {
try {
if (file.size > this.maxFileSize) {
alert(`${file.name} exceeds maximum size of ${Math.round(this.maxFileSize / 1024 / 1024)}MB`);
continue;
}
const attachment = await loadAttachment(file);
newAttachments.push(attachment);
} catch (error) {
console.error(`Error processing ${file.name}:`, error);
alert(`Failed to process ${file.name}: ${String(error)}`);
}
}
this.attachments = [...this.attachments, ...newAttachments];
this.onFilesChange?.(this.attachments);
this.processingFiles = false;
input.value = "";
}
removeFile(fileId) {
this.attachments = this.attachments.filter((f4) => f4.id !== fileId);
this.onFilesChange?.(this.attachments);
}
firstUpdated() {
const textarea = this.textareaRef.value;
if (textarea) {
textarea.focus();
}
}
render() {
const model = this.currentModel;
const supportsThinking = model?.reasoning === true;
return b2`
${this.isDragging ? b2`
${i18n("Drop files here")}
` : ""}
${this.attachments.length > 0 ? b2`
${this.attachments.map((attachment) => b2`
this.removeFile(attachment.id)}
>
`)}
` : ""}
${this.showAttachmentButton ? this.processingFiles ? b2`
${icon(LoaderCircle, "sm", "animate-spin text-muted-foreground")}
` : b2`
${Button({
variant: "ghost",
size: "icon",
className: "h-8 w-8",
onClick: this.handleAttachmentClick,
children: icon(Paperclip, "sm")
})}
` : ""}
${supportsThinking && this.showThinkingSelector ? b2`
${Select({
value: this.thinkingLevel,
placeholder: i18n("Off"),
options: [
{ value: "off", label: i18n("Off"), icon: icon(Brain, "sm") },
{ value: "minimal", label: i18n("Minimal"), icon: icon(Brain, "sm") },
{ value: "low", label: i18n("Low"), icon: icon(Brain, "sm") },
{ value: "medium", label: i18n("Medium"), icon: icon(Brain, "sm") },
{ value: "high", label: i18n("High"), icon: icon(Brain, "sm") }
],
onChange: (value) => {
this.onThinkingChange?.(value);
},
width: "80px",
size: "sm",
variant: "ghost",
fitContent: true
})}
` : ""}
${this.showModelSelector && this.currentModel ? b2`
${Button({
variant: "ghost",
size: "sm",
onClick: () => {
this.textareaRef.value?.focus();
requestAnimationFrame(() => {
this.onModelSelect?.();
});
},
children: b2`
${icon(Sparkles, "sm")}
${this.currentModel.id}
`,
className: "h-8 text-xs truncate"
})}
` : ""}
${this.isStreaming ? b2`
${Button({
variant: "ghost",
size: "icon",
onClick: this.onAbort,
children: icon(Square, "sm"),
className: "h-8 w-8"
})}
` : b2`
${Button({
variant: "ghost",
size: "icon",
onClick: this.handleSend,
disabled: !this.value.trim() && this.attachments.length === 0 || this.processingFiles,
children: b2`${icon(Send, "sm")}`,
className: "h-8 w-8"
})}
`}
`;
}
};
__decorate6([
n6()
], MessageEditor.prototype, "value", null);
__decorate6([
n6()
], MessageEditor.prototype, "isStreaming", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "currentModel", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "thinkingLevel", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "showAttachmentButton", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "showModelSelector", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "showThinkingSelector", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "onInput", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "onSend", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "onAbort", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "onModelSelect", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "onThinkingChange", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "onFilesChange", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "attachments", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "maxFiles", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "maxFileSize", void 0);
__decorate6([
n6()
], MessageEditor.prototype, "acceptedTypes", void 0);
__decorate6([
r7()
], MessageEditor.prototype, "processingFiles", void 0);
__decorate6([
r7()
], MessageEditor.prototype, "isDragging", void 0);
MessageEditor = __decorate6([
t5("message-editor")
], MessageEditor);
}
});
// node_modules/lit-html/directives/repeat.js
var u4, c5;
var init_repeat = __esm({
"node_modules/lit-html/directives/repeat.js"() {
init_process_shim();
init_lit_html();
init_directive();
init_directive_helpers();
u4 = (e9, s6, t6) => {
const r8 = /* @__PURE__ */ new Map();
for (let l5 = s6; l5 <= t6; l5++) r8.set(e9[l5], l5);
return r8;
};
c5 = e4(class extends i6 {
constructor(e9) {
if (super(e9), e9.type !== t4.CHILD) throw Error("repeat() can only be used in text expressions");
}
dt(e9, s6, t6) {
let r8;
void 0 === t6 ? t6 = s6 : void 0 !== s6 && (r8 = s6);
const l5 = [], o9 = [];
let i7 = 0;
for (const s7 of e9) l5[i7] = r8 ? r8(s7, i7) : i7, o9[i7] = t6(s7, i7), i7++;
return { values: o9, keys: l5 };
}
render(e9, s6, t6) {
return this.dt(e9, s6, t6).values;
}
update(s6, [t6, r8, c6]) {
const d4 = M2(s6), { values: p4, keys: a3 } = this.dt(t6, r8, c6);
if (!Array.isArray(d4)) return this.ut = a3, p4;
const h7 = this.ut ??= [], v4 = [];
let m4, y4, x2 = 0, j3 = d4.length - 1, k2 = 0, w3 = p4.length - 1;
for (; x2 <= j3 && k2 <= w3; ) if (null === d4[x2]) x2++;
else if (null === d4[j3]) j3--;
else if (h7[x2] === a3[k2]) v4[k2] = u3(d4[x2], p4[k2]), x2++, k2++;
else if (h7[j3] === a3[w3]) v4[w3] = u3(d4[j3], p4[w3]), j3--, w3--;
else if (h7[x2] === a3[w3]) v4[w3] = u3(d4[x2], p4[w3]), v2(s6, v4[w3 + 1], d4[x2]), x2++, w3--;
else if (h7[j3] === a3[k2]) v4[k2] = u3(d4[j3], p4[k2]), v2(s6, d4[x2], d4[j3]), j3--, k2++;
else if (void 0 === m4 && (m4 = u4(a3, k2, w3), y4 = u4(h7, x2, j3)), m4.has(h7[x2])) if (m4.has(h7[j3])) {
const e9 = y4.get(a3[k2]), t7 = void 0 !== e9 ? d4[e9] : null;
if (null === t7) {
const e10 = v2(s6, d4[x2]);
u3(e10, p4[k2]), v4[k2] = e10;
} else v4[k2] = u3(t7, p4[k2]), v2(s6, d4[x2], t7), d4[e9] = null;
k2++;
} else h3(d4[j3]), j3--;
else h3(d4[x2]), x2++;
for (; k2 <= w3; ) {
const e9 = v2(s6, v4[w3 + 1]);
u3(e9, p4[k2]), v4[k2++] = e9;
}
for (; x2 <= j3; ) {
const e9 = d4[x2++];
null !== e9 && h3(e9);
}
return this.ut = a3, p3(s6, v4), E;
}
});
}
});
// node_modules/lit/directives/repeat.js
var init_repeat2 = __esm({
"node_modules/lit/directives/repeat.js"() {
init_process_shim();
init_repeat();
}
});
// ../pi-mono/packages/web-ui/dist/components/message-renderer-registry.js
function registerMessageRenderer(role, renderer) {
messageRenderers.set(role, renderer);
}
function renderMessage(message) {
return messageRenderers.get(message.role)?.render(message);
}
var messageRenderers;
var init_message_renderer_registry = __esm({
"../pi-mono/packages/web-ui/dist/components/message-renderer-registry.js"() {
"use strict";
init_process_shim();
messageRenderers = /* @__PURE__ */ new Map();
}
});
// ../pi-mono/packages/web-ui/dist/components/MessageList.js
var __decorate7, MessageList;
var init_MessageList = __esm({
"../pi-mono/packages/web-ui/dist/components/MessageList.js"() {
"use strict";
init_process_shim();
init_lit();
init_decorators();
init_repeat2();
init_message_renderer_registry();
__decorate7 = function(decorators, target, key, desc) {
var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
MessageList = class extends i4 {
constructor() {
super(...arguments);
this.messages = [];
this.tools = [];
this.isStreaming = false;
}
createRenderRoot() {
return this;
}
connectedCallback() {
super.connectedCallback();
this.style.display = "block";
}
buildRenderItems() {
const resultByCallId = /* @__PURE__ */ new Map();
for (const message of this.messages) {
if (message.role === "toolResult") {
resultByCallId.set(message.toolCallId, message);
}
}
const items = [];
let index2 = 0;
for (const msg of this.messages) {
if (msg.role === "artifact") {
continue;
}
const customTemplate = renderMessage(msg);
if (customTemplate) {
items.push({ key: `msg:${index2}`, template: customTemplate });
index2++;
continue;
}
if (msg.role === "user" || msg.role === "user-with-attachments") {
items.push({
key: `msg:${index2}`,
template: b2` `
});
index2++;
} else if (msg.role === "assistant") {
const amsg = msg;
items.push({
key: `msg:${index2}`,
template: b2` `
});
index2++;
} else {
}
}
return items;
}
render() {
const items = this.buildRenderItems();
return b2`
${c5(items, (it) => it.key, (it) => it.template)}
`;
}
};
__decorate7([
n6({ type: Array })
], MessageList.prototype, "messages", void 0);
__decorate7([
n6({ type: Array })
], MessageList.prototype, "tools", void 0);
__decorate7([
n6({ type: Object })
], MessageList.prototype, "pendingToolCalls", void 0);
__decorate7([
n6({ type: Boolean })
], MessageList.prototype, "isStreaming", void 0);
__decorate7([
n6({ attribute: false })
], MessageList.prototype, "onCostClick", void 0);
if (!customElements.get("message-list")) {
customElements.define("message-list", MessageList);
}
}
});
// ../pi-mono/packages/web-ui/dist/components/sandbox/ConsoleRuntimeProvider.js
var ConsoleRuntimeProvider;
var init_ConsoleRuntimeProvider = __esm({
"../pi-mono/packages/web-ui/dist/components/sandbox/ConsoleRuntimeProvider.js"() {
"use strict";
init_process_shim();
ConsoleRuntimeProvider = class {
constructor() {
this.logs = [];
this.completionError = null;
this.completed = false;
}
getData() {
return {};
}
getDescription() {
return "";
}
getRuntime() {
return (_sandboxId) => {
if (!window.__originalConsole) {
window.__originalConsole = {
log: console.log.bind(console),
error: console.error.bind(console),
warn: console.warn.bind(console),
info: console.info.bind(console)
};
}
const originalConsole = window.__originalConsole;
const pendingSends = [];
["log", "error", "warn", "info"].forEach((method) => {
console[method] = (...args) => {
const text3 = args.map((arg) => {
try {
return typeof arg === "object" ? JSON.stringify(arg) : String(arg);
} catch {
return String(arg);
}
}).join(" ");
originalConsole[method].apply(console, args);
if (window.sendRuntimeMessage) {
const sendPromise = window.sendRuntimeMessage({
type: "console",
method,
text: text3,
args
}).catch(() => {
});
pendingSends.push(sendPromise);
}
};
});
if (window.onCompleted) {
window.onCompleted(async (_success) => {
if (pendingSends.length > 0) {
await Promise.all(pendingSends);
}
});
}
let lastError = null;
window.addEventListener("error", (e9) => {
const text3 = `${e9.error?.stack || e9.message || String(e9)} at line ${e9.lineno || "?"}:${e9.colno || "?"}`;
lastError = {
message: e9.error?.message || e9.message || String(e9),
stack: e9.error?.stack || text3
};
});
window.addEventListener("unhandledrejection", (e9) => {
const text3 = `Unhandled promise rejection: ${e9.reason?.message || e9.reason || "Unknown error"}`;
lastError = {
message: e9.reason?.message || String(e9.reason) || "Unhandled promise rejection",
stack: e9.reason?.stack || text3
};
});
let completionSent = false;
window.complete = async (error, returnValue) => {
if (completionSent)
return;
completionSent = true;
const finalError = error || lastError;
if (window.sendRuntimeMessage) {
if (finalError) {
await window.sendRuntimeMessage({
type: "execution-error",
error: finalError
});
} else {
await window.sendRuntimeMessage({
type: "execution-complete",
returnValue
});
}
}
};
};
}
async handleMessage(message, respond) {
if (message.type === "console") {
this.logs.push({
type: message.method === "error" ? "error" : message.method === "warn" ? "warn" : message.method === "info" ? "info" : "log",
text: message.text,
args: message.args
});
respond({ success: true });
}
}
/**
* Get collected console logs
*/
getLogs() {
return this.logs;
}
/**
* Get completion status
*/
isCompleted() {
return this.completed;
}
/**
* Get completion error if any
*/
getCompletionError() {
return this.completionError;
}
/**
* Reset state for reuse
*/
reset() {
this.logs = [];
this.completionError = null;
this.completed = false;
}
};
}
});
// ../pi-mono/packages/web-ui/dist/components/sandbox/RuntimeMessageBridge.js
var RuntimeMessageBridge;
var init_RuntimeMessageBridge = __esm({
"../pi-mono/packages/web-ui/dist/components/sandbox/RuntimeMessageBridge.js"() {
"use strict";
init_process_shim();
RuntimeMessageBridge = class _RuntimeMessageBridge {
/**
* Generate sendRuntimeMessage() function as injectable string.
* Returns the function source code to be injected into target context.
*/
static generateBridgeCode(options) {
if (options.context === "sandbox-iframe") {
return _RuntimeMessageBridge.generateSandboxBridge(options.sandboxId);
} else {
return _RuntimeMessageBridge.generateUserScriptBridge(options.sandboxId);
}
}
static generateSandboxBridge(sandboxId) {
return `
window.__completionCallbacks = [];
window.sendRuntimeMessage = async (message) => {
const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substring(2, 9);
return new Promise((resolve, reject) => {
const handler = (e) => {
if (e.data.type === 'runtime-response' && e.data.messageId === messageId) {
window.removeEventListener('message', handler);
if (e.data.success) {
resolve(e.data);
} else {
reject(new Error(e.data.error || 'Operation failed'));
}
}
};
window.addEventListener('message', handler);
window.parent.postMessage({
...message,
sandboxId: ${JSON.stringify(sandboxId)},
messageId: messageId
}, '*');
// Timeout after 30s
setTimeout(() => {
window.removeEventListener('message', handler);
reject(new Error('Runtime message timeout'));
}, 30000);
});
};
window.onCompleted = (callback) => {
window.__completionCallbacks.push(callback);
};
`.trim();
}
static generateUserScriptBridge(sandboxId) {
return `
window.__completionCallbacks = [];
window.sendRuntimeMessage = async (message) => {
return await chrome.runtime.sendMessage({
...message,
sandboxId: ${JSON.stringify(sandboxId)}
});
};
window.onCompleted = (callback) => {
window.__completionCallbacks.push(callback);
};
`.trim();
}
};
}
});
// ../pi-mono/packages/web-ui/dist/components/sandbox/RuntimeMessageRouter.js
var RuntimeMessageRouter, RUNTIME_MESSAGE_ROUTER;
var init_RuntimeMessageRouter = __esm({
"../pi-mono/packages/web-ui/dist/components/sandbox/RuntimeMessageRouter.js"() {
"use strict";
init_process_shim();
RuntimeMessageRouter = class {
constructor() {
this.sandboxes = /* @__PURE__ */ new Map();
this.messageListener = null;
this.userScriptMessageListener = null;
}
/**
* Register a new sandbox with its runtime providers.
* Call this BEFORE creating the iframe (for sandbox contexts) or executing user script.
*/
registerSandbox(sandboxId, providers, consumers) {
this.sandboxes.set(sandboxId, {
sandboxId,
iframe: null,
// Will be set via setSandboxIframe() for sandbox contexts
providers,
consumers: new Set(consumers)
});
this.setupListener();
}
/**
* Update the iframe reference for a sandbox.
* Call this AFTER creating the iframe.
* This is needed so providers can send responses back to the sandbox.
*/
setSandboxIframe(sandboxId, iframe) {
const context = this.sandboxes.get(sandboxId);
if (context) {
context.iframe = iframe;
}
}
/**
* Unregister a sandbox and remove all its consumers.
* Call this when the sandbox is destroyed.
*/
unregisterSandbox(sandboxId) {
this.sandboxes.delete(sandboxId);
if (this.sandboxes.size === 0) {
if (this.messageListener) {
window.removeEventListener("message", this.messageListener);
this.messageListener = null;
}
if (this.userScriptMessageListener && typeof chrome !== "undefined" && chrome.runtime?.onUserScriptMessage) {
chrome.runtime.onUserScriptMessage.removeListener(this.userScriptMessageListener);
this.userScriptMessageListener = null;
}
}
}
/**
* Add a message consumer for a sandbox.
* Consumers receive broadcast messages (console, execution-complete, etc.)
*/
addConsumer(sandboxId, consumer) {
const context = this.sandboxes.get(sandboxId);
if (context) {
context.consumers.add(consumer);
}
}
/**
* Remove a message consumer from a sandbox.
*/
removeConsumer(sandboxId, consumer) {
const context = this.sandboxes.get(sandboxId);
if (context) {
context.consumers.delete(consumer);
}
}
/**
* Setup the global message listeners (called automatically)
*/
setupListener() {
if (!this.messageListener) {
this.messageListener = async (e9) => {
const { sandboxId, messageId } = e9.data;
if (!sandboxId)
return;
const context = this.sandboxes.get(sandboxId);
if (!context) {
return;
}
const respond = (response) => {
context.iframe?.contentWindow?.postMessage({
type: "runtime-response",
messageId,
sandboxId,
...response
}, "*");
};
for (const provider of context.providers) {
if (provider.handleMessage) {
await provider.handleMessage(e9.data, respond);
}
}
for (const consumer of context.consumers) {
await consumer.handleMessage(e9.data);
}
};
window.addEventListener("message", this.messageListener);
}
if (!this.userScriptMessageListener) {
if (typeof chrome === "undefined" || !chrome.runtime?.onUserScriptMessage) {
return;
}
this.userScriptMessageListener = (message, _sender, sendResponse) => {
const { sandboxId } = message;
if (!sandboxId)
return false;
const context = this.sandboxes.get(sandboxId);
if (!context)
return false;
const respond = (response) => {
sendResponse({
...response,
sandboxId
});
};
(async () => {
for (const provider of context.providers) {
if (provider.handleMessage) {
await provider.handleMessage(message, respond);
}
}
for (const consumer of context.consumers) {
await consumer.handleMessage(message);
}
})();
return true;
};
chrome.runtime.onUserScriptMessage.addListener(this.userScriptMessageListener);
}
}
};
RUNTIME_MESSAGE_ROUTER = new RuntimeMessageRouter();
}
});
// ../pi-mono/packages/web-ui/dist/components/SandboxedIframe.js
function escapeScriptContent(code) {
return code.replace(/<\/script/gi, "<\\/script");
}
var __decorate8, SandboxIframe;
var init_SandboxedIframe = __esm({
"../pi-mono/packages/web-ui/dist/components/SandboxedIframe.js"() {
"use strict";
init_process_shim();
init_lit();
init_decorators();
init_ConsoleRuntimeProvider();
init_RuntimeMessageBridge();
init_RuntimeMessageRouter();
__decorate8 = function(decorators, target, key, desc) {
var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc);
else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8;
return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8;
};
SandboxIframe = class SandboxIframe2 extends i4 {
createRenderRoot() {
return this;
}
connectedCallback() {
super.connectedCallback();
}
disconnectedCallback() {
super.disconnectedCallback();
this.iframe?.remove();
}
/**
* Load HTML content into sandbox and keep it displayed (for HTML artifacts)
* @param sandboxId Unique ID
* @param htmlContent Full HTML content
* @param providers Runtime providers to inject
* @param consumers Message consumers to register (optional)
*/
loadContent(sandboxId, htmlContent, providers = [], consumers = []) {
try {
RUNTIME_MESSAGE_ROUTER.unregisterSandbox(sandboxId);
} catch {
}
providers = [new ConsoleRuntimeProvider(), ...providers];
RUNTIME_MESSAGE_ROUTER.registerSandbox(sandboxId, providers, consumers);
const completeHtml = this.prepareHtmlDocument(sandboxId, htmlContent, providers, {
isHtmlArtifact: true,
isStandalone: false
});
const validationError = this.validateHtml(completeHtml);
if (validationError) {
console.error("HTML validation failed:", validationError);
this.iframe?.remove();
this.iframe = document.createElement("iframe");
this.iframe.style.cssText = "width: 100%; height: 100%; border: none;";
this.iframe.srcdoc = `
HTML Validation Error
${validationError}
`;
this.appendChild(this.iframe);
return;
}
this.iframe?.remove();
if (this.sandboxUrlProvider) {
this.loadViaSandboxUrl(sandboxId, completeHtml);
} else {
this.loadViaSrcdoc(sandboxId, completeHtml);
}
}
loadViaSandboxUrl(sandboxId, completeHtml) {
this.iframe = document.createElement("iframe");
this.iframe.sandbox.add("allow-scripts");
this.iframe.sandbox.add("allow-modals");
this.iframe.style.width = "100%";
this.iframe.style.height = "100%";
this.iframe.style.border = "none";
this.iframe.src = this.sandboxUrlProvider();
RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
const externalUrlHandler = (e9) => {
if (e9.data.type === "open-external-url" && e9.source === this.iframe?.contentWindow) {
const chromeAPI = globalThis.chrome;
if (chromeAPI?.tabs) {
chromeAPI.tabs.create({ url: e9.data.url });
} else {
window.open(e9.data.url, "_blank");
}
}
};
window.addEventListener("message", externalUrlHandler);
const readyHandler = (e9) => {
if (e9.data.type === "sandbox-ready" && e9.source === this.iframe?.contentWindow) {
window.removeEventListener("message", readyHandler);
window.removeEventListener("message", errorHandler);
this.iframe?.contentWindow?.postMessage({
type: "sandbox-load",
sandboxId,
code: completeHtml
}, "*");
}
};
const errorHandler = (e9) => {
if (e9.data.type === "sandbox-error" && e9.source === this.iframe?.contentWindow) {
window.removeEventListener("message", readyHandler);
window.removeEventListener("message", errorHandler);
window.postMessage({
sandboxId,
type: "execution-error",
error: { message: e9.data.error, stack: e9.data.stack }
}, "*");
}
};
window.addEventListener("message", readyHandler);
window.addEventListener("message", errorHandler);
this.appendChild(this.iframe);
}
loadViaSrcdoc(sandboxId, completeHtml) {
this.iframe = document.createElement("iframe");
this.iframe.sandbox.add("allow-scripts");
this.iframe.sandbox.add("allow-modals");
this.iframe.style.width = "100%";
this.iframe.style.height = "100%";
this.iframe.style.border = "none";
this.iframe.srcdoc = completeHtml;
RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
const externalUrlHandler = (e9) => {
if (e9.data.type === "open-external-url" && e9.source === this.iframe?.contentWindow) {
window.open(e9.data.url, "_blank");
}
};
window.addEventListener("message", externalUrlHandler);
this.appendChild(this.iframe);
}
/**
* Execute code in sandbox
* @param sandboxId Unique ID for this execution
* @param code User code (plain JS for REPL, or full HTML for artifacts)
* @param providers Runtime providers to inject
* @param consumers Additional message consumers (optional, execute has its own internal consumer)
* @param signal Abort signal
* @returns Promise resolving to execution result
*/
async execute(sandboxId, code, providers = [], consumers = [], signal, isHtmlArtifact = false) {
if (signal?.aborted) {
throw new Error("Execution aborted");
}
const consoleProvider = new ConsoleRuntimeProvider();
providers = [consoleProvider, ...providers];
RUNTIME_MESSAGE_ROUTER.registerSandbox(sandboxId, providers, consumers);
for (const provider of providers) {
provider.onExecutionStart?.(sandboxId, signal);
}
const files = [];
let completed = false;
return new Promise((resolve2, reject) => {
const executionConsumer = {
async handleMessage(message) {
if (message.type === "file-returned") {
files.push({
fileName: message.fileName,
content: message.content,
mimeType: message.mimeType
});
} else if (message.type === "execution-complete") {
completed = true;
cleanup();
resolve2({
success: true,
console: consoleProvider.getLogs(),
files,
returnValue: message.returnValue
});
} else if (message.type === "execution-error") {
completed = true;
cleanup();
resolve2({ success: false, console: consoleProvider.getLogs(), error: message.error, files });
}
}
};
RUNTIME_MESSAGE_ROUTER.addConsumer(sandboxId, executionConsumer);
const cleanup = () => {
for (const provider of providers) {
provider.onExecutionEnd?.(sandboxId);
}
RUNTIME_MESSAGE_ROUTER.unregisterSandbox(sandboxId);
signal?.removeEventListener("abort", abortHandler);
clearTimeout(timeoutId);
this.iframe?.remove();
this.iframe = void 0;
};
const abortHandler = () => {
if (!completed) {
completed = true;
cleanup();
reject(new Error("Execution aborted"));
}
};
if (signal) {
signal.addEventListener("abort", abortHandler);
}
const timeoutId = setTimeout(() => {
if (!completed) {
completed = true;
cleanup();
resolve2({
success: false,
console: consoleProvider.getLogs(),
error: { message: "Execution timeout (120s)", stack: "" },
files
});
}
}, 12e4);
const completeHtml = this.prepareHtmlDocument(sandboxId, code, providers, {
isHtmlArtifact,
isStandalone: false
});
const validationError = this.validateHtml(completeHtml);
if (validationError) {
reject(new Error(`HTML validation failed: ${validationError}`));
return;
}
if (this.sandboxUrlProvider) {
this.iframe = document.createElement("iframe");
this.iframe.sandbox.add("allow-scripts", "allow-modals");
this.iframe.style.cssText = "width: 100%; height: 100%; border: none;";
this.iframe.src = this.sandboxUrlProvider();
RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
const readyHandler = (e9) => {
if (e9.data.type === "sandbox-ready" && e9.source === this.iframe?.contentWindow) {
window.removeEventListener("message", readyHandler);
window.removeEventListener("message", errorHandler);
this.iframe?.contentWindow?.postMessage({
type: "sandbox-load",
sandboxId,
code: completeHtml
}, "*");
}
};
const errorHandler = (e9) => {
if (e9.data.type === "sandbox-error" && e9.source === this.iframe?.contentWindow) {
window.removeEventListener("message", readyHandler);
window.removeEventListener("message", errorHandler);
window.postMessage({
sandboxId,
type: "execution-error",
error: { message: e9.data.error, stack: e9.data.stack }
}, "*");
}
};
window.addEventListener("message", readyHandler);
window.addEventListener("message", errorHandler);
this.appendChild(this.iframe);
} else {
this.iframe = document.createElement("iframe");
this.iframe.sandbox.add("allow-scripts", "allow-modals");
this.iframe.style.cssText = "width: 100%; height: 100%; border: none; display: none;";
this.iframe.srcdoc = completeHtml;
RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
this.appendChild(this.iframe);
}
});
}
/**
* Validate HTML using DOMParser - returns error message if invalid, null if valid
* Note: JavaScript syntax validation is done in sandbox.js to avoid CSP restrictions
*/
validateHtml(html) {
try {
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const parserError = doc.querySelector("parsererror");
if (parserError) {
return parserError.textContent || "Unknown parse error";
}
return null;
} catch (error) {
return error.message || "Unknown validation error";
}
}
/**
* Prepare complete HTML document with runtime + user code
* PUBLIC so HtmlArtifact can use it for download button
*/
prepareHtmlDocument(sandboxId, userCode, providers = [], options) {
const opts = {
isHtmlArtifact: false,
isStandalone: false,
...options
};
const runtime = this.getRuntimeScript(sandboxId, providers, opts.isStandalone || false);
if (opts.isHtmlArtifact) {
const headMatch = userCode.match(/]*>/i);
if (headMatch) {
const index2 = headMatch.index + headMatch[0].length;
return userCode.slice(0, index2) + runtime + userCode.slice(index2);
}
const htmlMatch = userCode.match(/]*>/i);
if (htmlMatch) {
const index2 = htmlMatch.index + htmlMatch[0].length;
return userCode.slice(0, index2) + runtime + userCode.slice(index2);
}
return runtime + userCode;
} else {
const escapedUserCode = escapeScriptContent(userCode);
return `
${runtime}