const Ie = Math.pow(2, 32), Ht = () => Math.round(Math.random() * Ie).toString(36), De = () => `${Math.round(performance.now())}-${Ht()}-${Ht()}`, K = 1;
class ze {
  constructor(t) {
    this.destination = null, this.registrar = /* @__PURE__ */ new Map(), this.origin = "", this.channelId = "", this.receiver = this.receive.bind(this), this.preLog = [], this.wnd = t, t.addEventListener("message", this.receiver);
  }
  receive(t) {
    if (t.source === null) throw Error("Event source is null");
    if (typeof t.data != "object") return;
    const e = t.data;
    if (!(!("_readium" in e) || !e._readium || e._readium <= 0)) {
      if (e.key === "_ping") {
        if (!this.destination) {
          if (this.destination = t.source, this.origin = t.origin, this.channelId = e._channel, e._readium !== K) {
            e._readium > K ? this.send("error", `received comms version ${e._readium} higher than ${K}`) : this.send("error", `received comms version ${e._readium} lower than ${K}`), this.destination = null, this.origin = "", this.channelId = "";
            return;
          }
          this.send("_pong", void 0), this.preLog.forEach((i) => this.send("log", i)), this.preLog = [];
        }
        return;
      } else if (this.channelId) {
        if (e._channel !== this.channelId || t.origin !== this.origin) return;
      } else
        return;
      this.handle(e);
    }
  }
  handle(t) {
    const e = this.registrar.get(t.key);
    if (!e || e.length === 0) {
      t.strict && this.send("_unhandled", t);
      return;
    }
    e.forEach((i) => i.cb(t.data, (s) => {
      this.send("_ack", s, t.id);
    }));
  }
  register(t, e, i) {
    Array.isArray(t) || (t = [t]), t.forEach((s) => {
      const n = this.registrar.get(s);
      if (n && n.length >= 0) {
        if (n.find((a) => a.module === e)) throw new Error(`Trying to register another callback for combination of event ${s} and module ${e}`);
        n.push({
          cb: i,
          module: e
        }), this.registrar.set(s, n);
      } else
        this.registrar.set(s, [{
          cb: i,
          module: e
        }]);
    });
  }
  unregister(t, e) {
    Array.isArray(t) || (t = [t]), t.forEach((i) => {
      const s = this.registrar.get(i);
      !s || s.length === 0 || s.splice(s.findIndex((n) => n.module === e), 1);
    });
  }
  unregisterAll(t) {
    this.registrar.forEach((e, i) => this.registrar.set(i, e.filter((s) => s.module !== t)));
  }
  log(...t) {
    this.destination ? this.send("log", t) : this.preLog.push(t);
  }
  get ready() {
    return !!this.destination;
  }
  destroy() {
    this.destination = null, this.channelId = "", this.preLog = [], this.registrar.clear(), this.wnd.removeEventListener("message", this.receiver);
  }
  send(t, e, i = void 0, s = []) {
    if (!this.destination) throw Error("Attempted to send comms message before destination has been initialized");
    const n = {
      _readium: K,
      _channel: this.channelId,
      id: i ?? De(),
      // scrict,
      key: t,
      data: e
    };
    try {
      this.destination.postMessage(n, {
        targetOrigin: this.origin,
        transfer: s
      });
    } catch (o) {
      if (s.length > 0) throw o;
      this.destination.postMessage(n, this.origin, s);
    }
  }
}
const y = class y {
  constructor(t) {
    this.uri = t;
  }
  /**
   * Parses an [AccessibilityProfile] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!(!t || typeof t != "string"))
      return new y(t);
  }
  /**
   * Serializes an [AccessibilityProfile] to its RWPM JSON representation.
   */
  serialize() {
    return this.uri;
  }
  /**
   * Returns true if the profile is a WCAG Level A profile.
   */
  get isWCAGLevelA() {
    return this === y.EPUB_A11Y_10_WCAG_20_A || this === y.EPUB_A11Y_11_WCAG_20_A || this === y.EPUB_A11Y_11_WCAG_21_A || this === y.EPUB_A11Y_11_WCAG_22_A;
  }
  /**
   * Returns true if the profile is a WCAG Level AA profile.
   */
  get isWCAGLevelAA() {
    return this === y.EPUB_A11Y_10_WCAG_20_AA || this === y.EPUB_A11Y_11_WCAG_20_AA || this === y.EPUB_A11Y_11_WCAG_21_AA || this === y.EPUB_A11Y_11_WCAG_22_AA;
  }
  /**
   * Returns true if the profile is a WCAG Level AAA profile.
   */
  get isWCAGLevelAAA() {
    return this === y.EPUB_A11Y_10_WCAG_20_AAA || this === y.EPUB_A11Y_11_WCAG_20_AAA || this === y.EPUB_A11Y_11_WCAG_21_AAA || this === y.EPUB_A11Y_11_WCAG_22_AAA;
  }
};
y.EPUB_A11Y_10_WCAG_20_A = new y("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-a"), y.EPUB_A11Y_10_WCAG_20_AA = new y("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aa"), y.EPUB_A11Y_10_WCAG_20_AAA = new y("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aaa"), y.EPUB_A11Y_11_WCAG_20_A = new y("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-a"), y.EPUB_A11Y_11_WCAG_20_AA = new y("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aa"), y.EPUB_A11Y_11_WCAG_20_AAA = new y("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aaa"), y.EPUB_A11Y_11_WCAG_21_A = new y("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-a"), y.EPUB_A11Y_11_WCAG_21_AA = new y("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aa"), y.EPUB_A11Y_11_WCAG_21_AAA = new y("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aaa"), y.EPUB_A11Y_11_WCAG_22_A = new y("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-a"), y.EPUB_A11Y_11_WCAG_22_AA = new y("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aa"), y.EPUB_A11Y_11_WCAG_22_AAA = new y("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aaa");
let _t = y;
const w = class w {
  constructor(t) {
    this.value = t;
  }
  /**
   * Parses an [AccessMode] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!(!t || typeof t != "string"))
      return new w(t);
  }
  /**
   * Serializes an [AccessMode] to its RWPM JSON representation.
   */
  serialize() {
    return this.value;
  }
};
w.AUDITORY = new w("auditory"), w.CHART_ON_VISUAL = new w("chartOnVisual"), w.CHEM_ON_VISUAL = new w("chemOnVisual"), w.COLOR_DEPENDENT = new w("colorDependent"), w.DIAGRAM_ON_VISUAL = new w("diagramOnVisual"), w.MATH_ON_VISUAL = new w("mathOnVisual"), w.MUSIC_ON_VISUAL = new w("musicOnVisual"), w.TACTILE = new w("tactile"), w.TEXT_ON_VISUAL = new w("textOnVisual"), w.TEXTUAL = new w("textual"), w.VISUAL = new w("visual");
let Vt = w;
const T = class T {
  constructor(t) {
    if (typeof t == "string") {
      if (!T.VALID_MODES.has(t.toLowerCase()))
        return;
      this.value = t.toLowerCase();
    } else {
      const e = t.filter(
        (i) => T.VALID_MODES.has(i.toLowerCase())
      );
      if (e.length === 0)
        return;
      this.value = Array.from(new Set(e));
    }
  }
  /**
   * Parses a [PrimaryAccessMode] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!t) return;
    if (typeof t == "string")
      return new T(t);
    if (!Array.isArray(t)) return;
    const e = t.filter((i) => i ? T.VALID_MODES.has(i.toLowerCase()) : !1);
    if (e.length !== 0)
      return new T(e);
  }
  /**
   * Serializes a [PrimaryAccessMode] to its RWPM JSON representation.
   */
  serialize() {
    return this.value;
  }
};
T.VALID_MODES = /* @__PURE__ */ new Set(["auditory", "tactile", "textual", "visual"]), T.AUDITORY = new T("auditory"), T.TACTILE = new T("tactile"), T.TEXTUAL = new T("textual"), T.VISUAL = new T("visual");
let Gt = T;
const c = class c {
  constructor(t) {
    this.value = t;
  }
  /**
   * Parses a [Feature] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!(!t || typeof t != "string"))
      return new c(t);
  }
  /**
   * Serializes a [Feature] to its RWPM JSON representation.
   */
  serialize() {
    return this.value;
  }
};
c.NONE = new c("none"), c.ANNOTATIONS = new c("annotations"), c.ARIA = new c("ARIA"), c.INDEX = new c("index"), c.PAGE_BREAK_MARKERS = new c("pageBreakMarkers"), c.PAGE_NAVIGATION = new c("pageNavigation"), c.PRINT_PAGE_NUMBERS = new c("printPageNumbers"), c.READING_ORDER = new c("readingOrder"), c.STRUCTURAL_NAVIGATION = new c("structuralNavigation"), c.TABLE_OF_CONTENTS = new c("tableOfContents"), c.TAGGED_PDF = new c("taggedPDF"), c.ALTERNATIVE_TEXT = new c("alternativeText"), c.AUDIO_DESCRIPTION = new c("audioDescription"), c.CAPTIONS = new c("captions"), c.CLOSED_CAPTIONS = new c("closedCaptions"), c.DESCRIBED_MATH = new c("describedMath"), c.LONG_DESCRIPTION = new c("longDescription"), c.OPEN_CAPTIONS = new c("openCaptions"), c.SIGN_LANGUAGE = new c("signLanguage"), c.TRANSCRIPT = new c("transcript"), c.DISPLAY_TRANSFORMABILITY = new c("displayTransformability"), c.SYNCHRONIZED_AUDIO_TEXT = new c("synchronizedAudioText"), c.TIMING_CONTROL = new c("timingControl"), c.UNLOCKED = new c("unlocked"), c.CHEM_ML = new c("ChemML"), c.LATEX = new c("latex"), c.LATEX_CHEMISTRY = new c("latex-chemistry"), c.MATH_ML = new c("MathML"), c.MATH_ML_CHEMISTRY = new c("MathML-chemistry"), c.TTS_MARKUP = new c("ttsMarkup"), c.HIGH_CONTRAST_AUDIO = new c("highContrastAudio"), c.HIGH_CONTRAST_DISPLAY = new c("highContrastDisplay"), c.LARGE_PRINT = new c("largePrint"), c.BRAILLE = new c("braille"), c.TACTILE_GRAPHIC = new c("tactileGraphic"), c.TACTILE_OBJECT = new c("tactileObject"), c.FULL_RUBY_ANNOTATIONS = new c("fullRubyAnnotations"), c.HORIZONTAL_WRITING = new c("horizontalWriting"), c.RUBY_ANNOTATIONS = new c("rubyAnnotations"), c.VERTICAL_WRITING = new c("verticalWriting"), c.WITH_ADDITIONAL_WORD_SEGMENTATION = new c("withAdditionalWordSegmentation"), c.WITHOUT_ADDITIONAL_WORD_SEGMENTATION = new c("withoutAdditionalWordSegmentation");
let Ft = c;
const S = class S {
  constructor(t) {
    this.value = t;
  }
  /**
   * Parses a [Hazard] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!(!t || typeof t != "string"))
      return new S(t);
  }
  /**
   * Serializes a [Hazard] to its RWPM JSON representation.
   */
  serialize() {
    return this.value;
  }
};
S.FLASHING = new S("flashing"), S.NO_FLASHING_HAZARD = new S("noFlashingHazard"), S.UNKNOWN_FLASHING_HAZARD = new S("unknownFlashingHazard"), S.MOTION_SIMULATION = new S("motionSimulation"), S.NO_MOTION_SIMULATION_HAZARD = new S("noMotionSimulationHazard"), S.UNKNOWN_MOTION_SIMULATION_HAZARD = new S("unknownMotionSimulationHazard"), S.SOUND = new S("sound"), S.NO_SOUND_HAZARD = new S("noSoundHazard"), S.UNKNOWN_SOUND_HAZARD = new S("unknownSoundHazard"), S.UNKNOWN = new S("unknown"), S.NONE = new S("none");
let $t = S;
const E = class E {
  constructor(t) {
    this.value = t;
  }
  /**
   * Parses an [Exemption] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!(!t || typeof t != "string"))
      return new E(t);
  }
  /**
   * Serializes an [Exemption] to its RWPM JSON representation.
   */
  serialize() {
    return this.value;
  }
};
E.NONE = new E("none"), E.DOCUMENTED = new E("documented"), E.LEGAL = new E("legal"), E.TEMPORARY = new E("temporary"), E.TECHNICAL = new E("technical"), E.EAA_DISPROPORTIONATE_BURDEN = new E("eaa-disproportionate-burden"), E.EAA_FUNDAMENTAL_ALTERATION = new E("eaa-fundamental-alteration"), E.EAA_MICROENTERPRISE = new E("eaa-microenterprise"), E.EAA_TECHNICAL_IMPOSSIBILITY = new E("eaa-technical-impossibility"), E.EAA_TEMPORARY = new E("eaa-temporary");
let Yt = E;
const Xt = ["en", "ar", "da", "fr", "it", "pt_PT", "sv"], Me = /* @__PURE__ */ JSON.parse(`{"format":{"audiobook":"Audiobook","audiobookJSON":"Audiobook Manifest","cbz":"Comic Book Archive","divina":"Divina Publication","divinaJSON":"Divina Publication Manifest","epub":"EPUB","lcpa":"LCP Protected Audiobook","lcpdf":"LCP Protected PDF","lcpl":"LCP License Document","pdf":"PDF","rwp":"Readium Web Publication","rwpm":"Readium Web Publication Manifest","zab":"Audiobook Archive","zip":"ZIP Archive"},"kind":{"audiobook_one":"audiobook","audiobook_other":"audiobooks","book_one":"book","book_other":"books","comic_one":"comic","comic_other":"comics","document_one":"document","document_other":"documents"},"metadata":{"accessibility":{"display-guide":{"accessibility-summary":{"no-metadata":"No information is available","publisher-contact":"For more information about the accessibility of this product, please contact the publisher: ","title":"Accessibility summary"},"additional-accessibility-information":{"aria":{"compact":"ARIA roles included","descriptive":"Content is enhanced with ARIA roles to optimize organization and facilitate navigation"},"audio-descriptions":"Audio descriptions","braille":"Braille","color-not-sole-means-of-conveying-information":"Color is not the sole means of conveying information","dyslexia-readability":"Dyslexia readability","full-ruby-annotations":"Full ruby annotations","high-contrast-between-foreground-and-background-audio":"High contrast between foreground and background audio","high-contrast-between-text-and-background":"High contrast between foreground text and background","large-print":"Large print","page-breaks":{"compact":"Page breaks included","descriptive":"Page breaks included from the original print source"},"ruby-annotations":"Some Ruby annotations","sign-language":"Sign language","tactile-graphics":{"compact":"Tactile graphics included","descriptive":"Tactile graphics have been integrated to facilitate access to visual elements for blind people"},"tactile-objects":"Tactile 3D objects","text-to-speech-hinting":"Text-to-speech hinting provided","title":"Additional accessibility information","ultra-high-contrast-between-text-and-background":"Ultra high contrast between text and background","visible-page-numbering":"Visible page numbering","without-background-sounds":"Without background sounds"},"conformance":{"a":{"compact":"This publication meets minimum accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level A standard"},"aa":{"compact":"This publication meets accepted accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level AA standard"},"aaa":{"compact":"This publication exceeds accepted accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level AAA standard"},"certifier":"The publication was certified by ","certifier-credentials":"The certifier's credential is ","details":{"certification-info":"The publication was certified on ","certifier-report":"For more information refer to the certifier's report","claim":"This publication claims to meet","epub-accessibility-1-0":"EPUB Accessibility 1.0","epub-accessibility-1-1":"EPUB Accessibility 1.1","level-a":"Level A","level-aa":"Level AA","level-aaa":"Level AAA","wcag-2-0":{"compact":"WCAG 2.0","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.0"},"wcag-2-1":{"compact":"WCAG 2.1","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.1"},"wcag-2-2":{"compact":"WCAG 2.2","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.2"}},"details-title":"Detailed conformance information","no":"No information is available","title":"Conformance","unknown-standard":"Conformance to accepted standards for accessibility of this publication cannot be determined"},"hazards":{"flashing":{"compact":"Flashing content","descriptive":"The publication contains flashing content that can cause photosensitive seizures"},"flashing-none":{"compact":"No flashing hazards","descriptive":"The publication does not contain flashing content that can cause photosensitive seizures"},"flashing-unknown":{"compact":"Flashing hazards not known","descriptive":"The presence of flashing content that can cause photosensitive seizures could not be determined"},"motion":{"compact":"Motion simulation","descriptive":"The publication contains motion simulations that can cause motion sickness"},"motion-none":{"compact":"No motion simulation hazards","descriptive":"The publication does not contain motion simulations that can cause motion sickness"},"motion-unknown":{"compact":"Motion simulation hazards not known","descriptive":"The presence of motion simulations that can cause motion sickness could not be determined"},"no-metadata":"No information is available","none":{"compact":"No hazards","descriptive":"The publication contains no hazards"},"sound":{"compact":"Sounds","descriptive":"The publication contains sounds that can cause sensitivity issues"},"sound-none":{"compact":"No sound hazards","descriptive":"The publication does not contain sounds that can cause sensitivity issues"},"sound-unknown":{"compact":"Sound hazards not known","descriptive":"The presence of sounds that can cause sensitivity issues could not be determined"},"title":"Hazards","unknown":"The presence of hazards is unknown"},"legal-considerations":{"exempt":{"compact":"Claims an accessibility exemption in some jurisdictions","descriptive":"This publication claims an accessibility exemption in some jurisdictions"},"no-metadata":"No information is available","title":"Legal considerations"},"navigation":{"index":{"compact":"Index","descriptive":"Index with links to referenced entries"},"no-metadata":"No information is available","page-navigation":{"compact":"Go to page","descriptive":"Page list to go to pages from the print source version"},"structural":{"compact":"Headings","descriptive":"Elements such as headings, tables, etc for structured navigation"},"title":"Navigation","toc":{"compact":"Table of contents","descriptive":"Table of contents to all chapters of the text via links"}},"rich-content":{"accessible-chemistry-as-latex":{"compact":"Chemical formulas in LaTeX","descriptive":"Chemical formulas in accessible format (LaTeX)"},"accessible-chemistry-as-mathml":{"compact":"Chemical formulas in MathML","descriptive":"Chemical formulas in accessible format (MathML)"},"accessible-math-as-latex":{"compact":"Math as LaTeX","descriptive":"Math formulas in accessible format (LaTeX)"},"accessible-math-described":"Text descriptions of math are provided","closed-captions":{"compact":"Videos have closed captions","descriptive":"Videos included in publications have closed captions"},"extended-descriptions":"Information-rich images are described by extended descriptions","math-as-mathml":{"compact":"Math as MathML","descriptive":"Math formulas in accessible format (MathML)"},"open-captions":{"compact":"Videos have open captions","descriptive":"Videos included in publications have open captions"},"title":"Rich content","transcript":"Transcript(s) provided","unknown":"No information is available"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{"compact":"Has alternative text","descriptive":"Has alternative text descriptions for images"},"no-metadata":"No information about nonvisual reading is available","none":{"compact":"Not readable in read aloud or dynamic braille","descriptive":"The content is not readable as read aloud speech or dynamic braille"},"not-fully":{"compact":"Not fully readable in read aloud or dynamic braille","descriptive":"Not all of the content will be readable as read aloud speech or dynamic braille"},"readable":{"compact":"Readable in read aloud or dynamic braille","descriptive":"All content can be read as read aloud speech or dynamic braille"}},"prerecorded-audio":{"complementary":{"compact":"Prerecorded audio clips","descriptive":"Prerecorded audio clips are embedded in the content"},"no-metadata":"No information about prerecorded audio is available","only":{"compact":"Prerecorded audio only","descriptive":"Audiobook with no text alternative"},"synchronized":{"compact":"Prerecorded audio synchronized with text","descriptive":"All the content is available as prerecorded audio synchronized with text"}},"title":"Ways of reading","visual-adjustments":{"modifiable":{"compact":"Appearance can be modified","descriptive":"Appearance of the text and page layout can be modified according to the capabilities of the reading system (font family and font size, spaces between paragraphs, sentences, words, and letters, as well as color of background and text)"},"unknown":"No information about appearance modifiability is available","unmodifiable":{"compact":"Appearance cannot be modified","descriptive":"Text and page layout cannot be modified as the reading experience is close to a print version, but reading systems can still provide zooming options"}}}}},"altIdentifier_one":"alternate identifier","altIdentifier_other":"alternate identifiers","artist_one":"artist","artist_other":"artists","author_one":"author","author_other":"authors","collection_one":"editorial collection","collection_other":"editorial collections","colorist_one":"colorist","colorist_other":"colorists","contributor_one":"contributor","contributor_other":"contributors","description":"description","duration":"duration","editor_one":"editor","editor_other":"editors","identifier_one":"identifier","identifier_other":"identifiers","illustrator_one":"illustrator","illustrator_other":"illustrators","imprint_one":"imprint","imprint_other":"imprints","inker_one":"inker","inker_other":"inkers","language_one":"language","language_other":"languages","letterer_one":"letterer","letterer_other":"letterers","modified":"modification date","narrator_one":"narrator","narrator_other":"narrators","numberOfPages":"print length","penciler_one":"penciler","penciler_other":"pencilers","published":"publication date","publisher_one":"publisher","publisher_other":"publishers","series_one":"series","series_other":"series","subject_one":"subject","subject_other":"subjects","subtitle":"subtitle","title":"title","translator_one":"translator","translator_other":"translators"}}`), ke = {
  publication: Me
}, qt = {
  fr: () => import("./fr-C5HEel98.js"),
  ar: () => import("./ar-DyHX_uy2.js"),
  da: () => import("./da-Dct0PS3E.js"),
  //  'el': () => import('@edrlab/thorium-locales/publication-metadata/el.json'),
  //  'et': () => import('@edrlab/thorium-locales/publication-metadata/et.json'),
  it: () => import("./it-DFOBoXGy.js"),
  pt_PT: () => import("./pt_PT-Di3sVjze.js"),
  sv: () => import("./sv-BfzAFsVN.js")
  //  'tr': () => import('@edrlab/thorium-locales/publication-metadata/tr.json'),
  //  'uk': () => import('@edrlab/thorium-locales/publication-metadata/uk.json')
}, Kt = ke?.publication?.metadata?.accessibility?.["display-guide"] || {};
class F {
  constructor() {
    this.currentLocaleCode = "en", this.locale = Kt, this.loadedLocales = {}, this.loadedLocales.en = Kt;
  }
  static getInstance() {
    return F.instance || (F.instance = new F()), F.instance;
  }
  /**
   * Loads a locale dynamically
   * @param localeCode BCP 47 language code (e.g., 'en', 'fr')
   * @returns Promise indicating if the locale was loaded successfully
   */
  async loadLocale(t) {
    if (!Xt.includes(t))
      return console.warn(`Locale '${t}' is not enabled`), !1;
    if (t in this.loadedLocales)
      return !0;
    try {
      if (!(t in qt))
        return console.warn(`Locale file not found for: ${t}`), !1;
      const s = (await qt[t]()).default?.publication?.metadata?.accessibility?.["display-guide"];
      return s ? (this.loadedLocales[t] = s, !0) : (console.warn(`No accessibility strings found in locale ${t}`), !1);
    } catch (e) {
      return console.warn(`Failed to load locale ${t}:`, e), !1;
    }
  }
  /**
   * Registers a new locale or updates an existing one
   * @param localeCode BCP 47 language code (e.g., 'en', 'fr-FR')
   * @param localeData The locale data to register
   */
  registerLocale(t, e) {
    if (!t || typeof t != "string")
      throw new Error("Locale code must be a non-empty string");
    this.loadedLocales[t] = e;
  }
  /**
   * Sets the current locale by language code, loading it dynamically if needed
   * @param localeCode BCP 47 language code (e.g., 'en', 'fr')
   * @returns Promise indicating if the locale was set successfully
   */
  async setLocale(t) {
    return t in this.loadedLocales || await this.loadLocale(t), t in this.loadedLocales ? (this.locale = this.loadedLocales[t], this.currentLocaleCode = t, !0) : (console.warn(`Locale '${t}' is not available`), !1);
  }
  /**
   * Gets the current locale code (BCP 47)
   */
  getCurrentLocale() {
    return this.currentLocaleCode;
  }
  /**
   * Gets a list of available locale codes
   */
  getAvailableLocales() {
    return Xt;
  }
  getNestedValue(t, e) {
    const i = e.split(".");
    let s = t;
    for (const n of i) {
      if (s == null)
        return;
      s = s[n];
    }
    return s;
  }
  /**
   * Gets a localized string by key
   * @param key The key for the string to retrieve
   * @returns The localized string as a [L10nString], or an empty string if not found
   */
  getString(t) {
    let e = this.getNestedValue(this.locale, t);
    return e === void 0 && this.currentLocaleCode !== "en" && (e = this.getNestedValue(this.loadedLocales.en, t)), e !== void 0 ? typeof e == "string" ? { compact: e, descriptive: e } : e : (console.warn(`Missing localization for key: ${t}`), { compact: "", descriptive: "" });
  }
}
F.getInstance();
class Rt {
  /**
   * Creates a [Encryption].
   */
  constructor(t) {
    this.algorithm = t.algorithm, this.compression = t.compression, this.originalLength = t.originalLength, this.profile = t.profile, this.scheme = t.scheme;
  }
  /**
   * Parses a [Encryption] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (t && t.algorithm)
      return new Rt({
        algorithm: t.algorithm,
        compression: t.compression,
        originalLength: t.originalLength,
        profile: t.profile,
        scheme: t.scheme
      });
  }
  /**
   * Serializes a [Encryption] to its RWPM JSON representation.
   */
  serialize() {
    const t = { algorithm: this.algorithm };
    return this.compression !== void 0 && (t.compression = this.compression), this.originalLength !== void 0 && (t.originalLength = this.originalLength), this.profile !== void 0 && (t.profile = this.profile), this.scheme !== void 0 && (t.scheme = this.scheme), t;
  }
}
class R {
  constructor(t) {
    this.otherProperties = t;
  }
  get page() {
    return this.otherProperties.page;
  }
  /**
   * Creates a [Properties] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (t)
      return new R(t);
  }
  /**
   * Serializes a [Properties] to its RWPM JSON representation.
   */
  serialize() {
    return this.otherProperties;
  }
  /**
   * Makes a copy of this [Properties] after merging in the given additional other [properties].
   */
  add(t) {
    const e = Object.assign({}, this.otherProperties);
    for (const i in t)
      e[i] = t[i];
    return new R(e);
  }
}
Object.defineProperty(R.prototype, "encryption", {
  get: function() {
    return Rt.deserialize(this.otherProperties.encrypted);
  }
});
function We(r) {
  return r && Array.isArray(r) ? r : void 0;
}
function ye(r) {
  return r && typeof r == "string" ? [r] : We(r);
}
function Zt(r) {
  return typeof r == "string" ? new Date(r) : void 0;
}
function at(r) {
  return isNaN(r) ? void 0 : r;
}
function O(r) {
  return at(r) !== void 0 && Math.sign(r) >= 0 ? r : void 0;
}
function Ue(r) {
  const t = new Array();
  return r.forEach((e) => t.push(e)), t;
}
class l {
  /** Creates a MediaType object. */
  constructor(t) {
    let e, i, s = t.mediaType.replace(/\s/g, "").split(";");
    const n = s[0].split("/");
    if (n.length === 2) {
      if (e = n[0].toLowerCase().trim(), i = n[1].toLowerCase().trim(), e.length === 0 || i.length === 0)
        throw new Error("Invalid media type");
    } else
      throw new Error("Invalid media type");
    const o = {};
    for (let m = 1; m < s.length; m++) {
      const v = s[m].split("=");
      if (v.length === 2) {
        const f = v[0].toLocaleLowerCase(), p = f === "charset" ? v[1].toUpperCase() : v[1];
        o[f] = p;
      }
    }
    const a = {}, d = Object.keys(o);
    d.sort((m, v) => m.localeCompare(v)), d.forEach((m) => a[m] = o[m]);
    let h = "";
    for (const m in a) {
      const v = a[m];
      h += `;${m}=${v}`;
    }
    const u = `${e}/${i}${h}`, g = a.encoding;
    this.string = u, this.type = e, this.subtype = i, this.parameters = a, this.encoding = g, this.name = t.name, this.fileExtension = t.fileExtension;
  }
  static parse(t) {
    return new l(t);
  }
  /** Structured syntax suffix, e.g. `+zip` in `application/epub+zip`.
   *  Gives a hint on the underlying structure of this media type.
   *  See. https://tools.ietf.org/html/rfc6838#section-4.2.8
   */
  get structuredSyntaxSuffix() {
    const t = this.subtype.split("+");
    return t.length > 1 ? `+${t[t.length - 1]}` : void 0;
  }
  /** Parameter values might or might not be case-sensitive, depending on the semantics of
   * the parameter name.
   * https://tools.ietf.org/html/rfc2616#section-3.7
   *
   * The character set names may be up to 40 characters taken from the printable characters
   * of US-ASCII.  However, no distinction is made between use of upper and lower case
   * letters.
   * https://www.iana.org/assignments/character-sets/character-sets.xhtml
   */
  get charset() {
    return this.parameters.charset;
  }
  /** Returns whether the given `other` media type is included in this media type.
   *  For example, `text/html` contains `text/html;charset=utf-8`.
   *  - `other` must match the parameters in the `parameters` property, but extra parameters
   *  are ignored.
   *  - Order of parameters is ignored.
   *  - Wildcards are supported, meaning that `image/*` contains `image/png`
   */
  contains(t) {
    const e = typeof t == "string" ? l.parse({ mediaType: t }) : t;
    if (!((this.type === "*" || this.type === e.type) && (this.subtype === "*" || this.subtype === e.subtype)))
      return !1;
    const i = new Set(
      Object.entries(this.parameters).map(([n, o]) => `${n}=${o}`)
    ), s = new Set(
      Object.entries(e.parameters).map(([n, o]) => `${n}=${o}`)
    );
    for (const n of Array.from(i.values()))
      if (!s.has(n))
        return !1;
    return !0;
  }
  /** Returns whether this media type and `other` are the same, ignoring parameters that
   *  are not in both media types.
   *  For example, `text/html` matches `text/html;charset=utf-8`, but `text/html;charset=ascii`
   *  doesn't. This is basically like `contains`, but working in both direction.
   */
  matches(t) {
    const e = typeof t == "string" ? l.parse({ mediaType: t }) : t;
    return this.contains(e) || e.contains(this);
  }
  /**
   * Returns whether this media type matches any of the [others] media types.
   */
  matchesAny(...t) {
    for (const e of t)
      if (this.matches(e))
        return !0;
    return !1;
  }
  /** Checks the MediaType equals another one (comparing their string) */
  equals(t) {
    return this.string === t.string;
  }
  /** Returns whether this media type is structured as a ZIP archive. */
  get isZIP() {
    return this.matchesAny(
      l.ZIP,
      l.LCP_PROTECTED_AUDIOBOOK,
      l.LCP_PROTECTED_PDF
    ) || this.structuredSyntaxSuffix === "+zip";
  }
  /** Returns whether this media type is structured as a JSON file. */
  get isJSON() {
    return this.matchesAny(l.JSON) || this.structuredSyntaxSuffix === "+json";
  }
  /** Returns whether this media type is of an OPDS feed. */
  get isOPDS() {
    return this.matchesAny(
      l.OPDS1,
      l.OPDS1_ENTRY,
      l.OPDS2,
      l.OPDS2_PUBLICATION,
      l.OPDS_AUTHENTICATION
    ) || this.structuredSyntaxSuffix === "+json";
  }
  /** Returns whether this media type is of an HTML document. */
  get isHTML() {
    return this.matchesAny(l.HTML, l.XHTML);
  }
  /** Returns whether this media type is of a bitmap image, so excluding vectorial formats. */
  get isBitmap() {
    return this.matchesAny(
      l.BMP,
      l.GIF,
      l.JPEG,
      l.PNG,
      l.TIFF,
      l.WEBP
    );
  }
  /** Returns whether this media type is of an audio clip. */
  get isAudio() {
    return this.type === "audio";
  }
  /** Returns whether this media type is of a video clip. */
  get isVideo() {
    return this.type === "video";
  }
  /** Returns whether this media type is of a Readium Web Publication Manifest. */
  get isRWPM() {
    return this.matchesAny(
      l.READIUM_AUDIOBOOK_MANIFEST,
      l.DIVINA_MANIFEST,
      l.READIUM_WEBPUB_MANIFEST
    );
  }
  /** Returns whether this media type is of a publication file. */
  get isPublication() {
    return this.matchesAny(
      l.READIUM_AUDIOBOOK,
      l.READIUM_AUDIOBOOK_MANIFEST,
      l.CBZ,
      l.DIVINA,
      l.DIVINA_MANIFEST,
      l.EPUB,
      l.LCP_PROTECTED_AUDIOBOOK,
      l.LCP_PROTECTED_PDF,
      l.LPF,
      l.PDF,
      l.W3C_WPUB_MANIFEST,
      l.READIUM_WEBPUB,
      l.READIUM_WEBPUB_MANIFEST,
      l.ZAB
    );
  }
  // Known Media Types
  static get AAC() {
    return l.parse({ mediaType: "audio/aac", fileExtension: "aac" });
  }
  static get ACSM() {
    return l.parse({
      mediaType: "application/vnd.adobe.adept+xml",
      name: "Adobe Content Server Message",
      fileExtension: "acsm"
    });
  }
  static get AIFF() {
    return l.parse({ mediaType: "audio/aiff", fileExtension: "aiff" });
  }
  static get AVI() {
    return l.parse({
      mediaType: "video/x-msvideo",
      fileExtension: "avi"
    });
  }
  static get BINARY() {
    return l.parse({ mediaType: "application/octet-stream" });
  }
  static get BMP() {
    return l.parse({ mediaType: "image/bmp", fileExtension: "bmp" });
  }
  static get CBZ() {
    return l.parse({
      mediaType: "application/vnd.comicbook+zip",
      name: "Comic Book Archive",
      fileExtension: "cbz"
    });
  }
  static get CSS() {
    return l.parse({ mediaType: "text/css", fileExtension: "css" });
  }
  static get DIVINA() {
    return l.parse({
      mediaType: "application/divina+zip",
      name: "Digital Visual Narratives",
      fileExtension: "divina"
    });
  }
  static get DIVINA_MANIFEST() {
    return l.parse({
      mediaType: "application/divina+json",
      name: "Digital Visual Narratives",
      fileExtension: "json"
    });
  }
  static get EPUB() {
    return l.parse({
      mediaType: "application/epub+zip",
      name: "EPUB",
      fileExtension: "epub"
    });
  }
  static get GIF() {
    return l.parse({ mediaType: "image/gif", fileExtension: "gif" });
  }
  static get GZ() {
    return l.parse({
      mediaType: "application/gzip",
      fileExtension: "gz"
    });
  }
  static get HTML() {
    return l.parse({ mediaType: "text/html", fileExtension: "html" });
  }
  static get JAVASCRIPT() {
    return l.parse({
      mediaType: "text/javascript",
      fileExtension: "js"
    });
  }
  static get JPEG() {
    return l.parse({ mediaType: "image/jpeg", fileExtension: "jpeg" });
  }
  static get JSON() {
    return l.parse({ mediaType: "application/json" });
  }
  static get LCP_LICENSE_DOCUMENT() {
    return l.parse({
      mediaType: "application/vnd.readium.lcp.license.v1.0+json",
      name: "LCP License",
      fileExtension: "lcpl"
    });
  }
  static get LCP_PROTECTED_AUDIOBOOK() {
    return l.parse({
      mediaType: "application/audiobook+lcp",
      name: "LCP Protected Audiobook",
      fileExtension: "lcpa"
    });
  }
  static get LCP_PROTECTED_PDF() {
    return l.parse({
      mediaType: "application/pdf+lcp",
      name: "LCP Protected PDF",
      fileExtension: "lcpdf"
    });
  }
  static get LCP_STATUS_DOCUMENT() {
    return l.parse({
      mediaType: "application/vnd.readium.license.status.v1.0+json"
    });
  }
  static get LPF() {
    return l.parse({
      mediaType: "application/lpf+zip",
      fileExtension: "lpf"
    });
  }
  static get MP3() {
    return l.parse({ mediaType: "audio/mpeg", fileExtension: "mp3" });
  }
  static get MPEG() {
    return l.parse({ mediaType: "video/mpeg", fileExtension: "mpeg" });
  }
  static get NCX() {
    return l.parse({
      mediaType: "application/x-dtbncx+xml",
      fileExtension: "ncx"
    });
  }
  static get OGG() {
    return l.parse({ mediaType: "audio/ogg", fileExtension: "oga" });
  }
  static get OGV() {
    return l.parse({ mediaType: "video/ogg", fileExtension: "ogv" });
  }
  static get OPDS1() {
    return l.parse({
      mediaType: "application/atom+xml;profile=opds-catalog"
    });
  }
  static get OPDS1_ENTRY() {
    return l.parse({
      mediaType: "application/atom+xml;type=entry;profile=opds-catalog"
    });
  }
  static get OPDS2() {
    return l.parse({ mediaType: "application/opds+json" });
  }
  static get OPDS2_PUBLICATION() {
    return l.parse({ mediaType: "application/opds-publication+json" });
  }
  static get OPDS_AUTHENTICATION() {
    return l.parse({
      mediaType: "application/opds-authentication+json"
    });
  }
  static get OPUS() {
    return l.parse({ mediaType: "audio/opus", fileExtension: "opus" });
  }
  static get OTF() {
    return l.parse({ mediaType: "font/otf", fileExtension: "otf" });
  }
  static get PDF() {
    return l.parse({
      mediaType: "application/pdf",
      name: "PDF",
      fileExtension: "pdf"
    });
  }
  static get PNG() {
    return l.parse({ mediaType: "image/png", fileExtension: "png" });
  }
  static get READIUM_AUDIOBOOK() {
    return l.parse({
      mediaType: "application/audiobook+zip",
      name: "Readium Audiobook",
      fileExtension: "audiobook"
    });
  }
  static get READIUM_AUDIOBOOK_MANIFEST() {
    return l.parse({
      mediaType: "application/audiobook+json",
      name: "Readium Audiobook",
      fileExtension: "json"
    });
  }
  static get READIUM_CONTENT_DOCUMENT() {
    return l.parse({
      mediaType: "application/vnd.readium.content+json",
      name: "Readium Content Document",
      fileExtension: "json"
    });
  }
  static get READIUM_GUIDED_NAVIGATION_DOCUMENT() {
    return l.parse({
      mediaType: "application/guided-navigation+json",
      name: "Readium Guided Navigation Document",
      fileExtension: "json"
    });
  }
  static get READIUM_POSITION_LIST() {
    return l.parse({
      mediaType: "application/vnd.readium.position-list+json",
      name: "Readium Position List",
      fileExtension: "json"
    });
  }
  static get READIUM_WEBPUB() {
    return l.parse({
      mediaType: "application/webpub+zip",
      name: "Readium Web Publication",
      fileExtension: "webpub"
    });
  }
  static get READIUM_WEBPUB_MANIFEST() {
    return l.parse({
      mediaType: "application/webpub+json",
      name: "Readium Web Publication",
      fileExtension: "json"
    });
  }
  static get SMIL() {
    return l.parse({
      mediaType: "application/smil+xml",
      fileExtension: "smil"
    });
  }
  static get SVG() {
    return l.parse({
      mediaType: "image/svg+xml",
      fileExtension: "svg"
    });
  }
  static get TEXT() {
    return l.parse({ mediaType: "text/plain", fileExtension: "txt" });
  }
  static get TIFF() {
    return l.parse({ mediaType: "image/tiff", fileExtension: "tiff" });
  }
  static get TTF() {
    return l.parse({ mediaType: "font/ttf", fileExtension: "ttf" });
  }
  static get W3C_WPUB_MANIFEST() {
    return l.parse({
      mediaType: "application/x.readium.w3c.wpub+json",
      name: "Web Publication",
      fileExtension: "json"
    });
  }
  static get WAV() {
    return l.parse({ mediaType: "audio/wav", fileExtension: "wav" });
  }
  static get WEBM_AUDIO() {
    return l.parse({ mediaType: "audio/webm", fileExtension: "webm" });
  }
  static get WEBM_VIDEO() {
    return l.parse({ mediaType: "video/webm", fileExtension: "webm" });
  }
  static get WEBP() {
    return l.parse({ mediaType: "image/webp", fileExtension: "webp" });
  }
  static get WOFF() {
    return l.parse({ mediaType: "font/woff", fileExtension: "woff" });
  }
  static get WOFF2() {
    return l.parse({ mediaType: "font/woff2", fileExtension: "woff2" });
  }
  static get XHTML() {
    return l.parse({
      mediaType: "application/xhtml+xml",
      fileExtension: "xhtml"
    });
  }
  static get XML() {
    return l.parse({
      mediaType: "application/xml",
      fileExtension: "xml"
    });
  }
  static get ZAB() {
    return l.parse({
      mediaType: "application/x.readium.zab+zip",
      name: "Zipped Audio Book",
      fileExtension: "zab"
    });
  }
  static get ZIP() {
    return l.parse({
      mediaType: "application/zip",
      fileExtension: "zip"
    });
  }
}
class Jt {
  constructor(t) {
    this.uri = t, this.parameters = this.getParameters(t);
  }
  /**
   * List of URI template parameter keys, if the [Link] is templated.
   */
  getParameters(t) {
    const e = /\{\??([^}]+)\}/g, i = t.match(e);
    return i ? new Set(
      i.join(",").replace(e, "$1").split(",").map((s) => s.trim())
    ) : /* @__PURE__ */ new Set();
  }
  /** Expands the URI by replacing the template variables by the given parameters.
   *  Any extra parameter is appended as query parameters.
   *  See RFC 6570 on URI template: https://tools.ietf.org/html/rfc6570
   */
  expand(t) {
    const e = (s) => s.split(",").map((n) => {
      const o = t[n];
      return o ? encodeURIComponent(o) : "";
    }).join(","), i = (s) => "?" + s.split(",").map((n) => {
      const o = n.split("=")[0], a = t[o];
      return a ? `${o}=${encodeURIComponent(a)}` : "";
    }).join("&");
    return this.uri.replace(/\{(\??)([^}]+)\}/g, (...s) => s[1] ? i(s[2]) : e(s[2]));
  }
}
class C {
  /**
   * Creates a [Locations].
   */
  constructor(t) {
    this.fragments = t.fragments ? t.fragments : new Array(), this.progression = t.progression, this.totalProgression = t.totalProgression, this.position = t.position, this.otherLocations = t.otherLocations;
  }
  /**
   * Parses a [Locations] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!t) return;
    const e = at(t.progression), i = at(t.totalProgression), s = at(t.position), n = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Set([
      "fragment",
      "fragments",
      "progression",
      "totalProgression",
      "position"
    ]);
    return Object.entries(t).forEach(([a, d]) => {
      o.has(a) || n.set(a, d);
    }), new C({
      fragments: ye(t.fragments || t.fragment),
      progression: e !== void 0 && e >= 0 && e <= 1 ? e : void 0,
      totalProgression: i !== void 0 && i >= 0 && i <= 1 ? i : void 0,
      position: s !== void 0 && s > 0 ? s : void 0,
      otherLocations: n.size === 0 ? void 0 : n
    });
  }
  /**
   * Serializes a [Locations] to its RWPM JSON representation.
   */
  serialize() {
    const t = {};
    return this.fragments && (t.fragments = this.fragments), this.progression !== void 0 && (t.progression = this.progression), this.totalProgression !== void 0 && (t.totalProgression = this.totalProgression), this.position !== void 0 && (t.position = this.position), this.otherLocations && this.otherLocations.forEach((e, i) => t[i] = e), t;
  }
}
class H {
  /**
   * Creates a [Text].
   */
  constructor(t) {
    this.after = t.after, this.before = t.before, this.highlight = t.highlight;
  }
  /**
   * Parses a [Locations] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (t)
      return new H({
        after: t.after,
        before: t.before,
        highlight: t.highlight
      });
  }
  /**
   * Serializes a [Locations] to its RWPM JSON representation.
   */
  serialize() {
    const t = {};
    return this.after !== void 0 && (t.after = this.after), this.before !== void 0 && (t.before = this.before), this.highlight !== void 0 && (t.highlight = this.highlight), t;
  }
}
class W {
  /**
   * Creates a [Locator].
   */
  constructor(t) {
    this.href = t.href, this.type = t.type, this.title = t.title, this.locations = t.locations ? t.locations : new C({}), this.text = t.text;
  }
  /**
   * Parses a [Link] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (t && t.href && t.type)
      return new W({
        href: t.href,
        type: t.type,
        title: t.title,
        locations: C.deserialize(t.locations),
        text: H.deserialize(t.text)
      });
  }
  /**
   * Serializes a [Link] to its RWPM JSON representation.
   */
  serialize() {
    const t = { href: this.href, type: this.type };
    return this.title !== void 0 && (t.title = this.title), this.locations && (t.locations = this.locations.serialize()), this.text && (t.text = this.text.serialize()), t;
  }
  /**
   * Shortcut to get a copy of the [Locator] with different [Locations] sub-properties.
   */
  copyWithLocations(t) {
    return new W({
      href: this.href,
      type: this.type,
      title: this.title,
      text: this.text,
      locations: new C({ ...this.locations, ...t })
    });
  }
}
class Y {
  /**
   * Creates a [Link].
   */
  constructor(t) {
    this.href = t.href, this.templated = t.templated, this.type = t.type, this.title = t.title, this.rels = t.rels, this.properties = t.properties, this.height = t.height, this.width = t.width, this.size = t.size, this.duration = t.duration, this.bitrate = t.bitrate, this.languages = t.languages, this.alternates = t.alternates, this.children = t.children;
  }
  /**
   * Parses a [Link] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!(!t || typeof t.href != "string"))
      return new Y({
        href: t.href,
        templated: t.templated,
        type: t.type,
        title: t.title,
        rels: t.rel ? Array.isArray(t.rel) ? new Set(t.rel) : /* @__PURE__ */ new Set([t.rel]) : void 0,
        properties: R.deserialize(t.properties),
        height: O(t.height),
        width: O(t.width),
        size: O(t.size),
        duration: O(t.duration),
        bitrate: O(t.bitrate),
        languages: ye(t.language),
        alternates: lt.deserialize(t.alternate),
        children: lt.deserialize(t.children)
      });
  }
  /**
   * Serializes a [Link] to its RWPM JSON representation.
   */
  serialize() {
    const t = { href: this.href };
    return this.templated !== void 0 && (t.templated = this.templated), this.type !== void 0 && (t.type = this.type), this.title !== void 0 && (t.title = this.title), this.rels && (t.rel = Ue(this.rels)), this.properties && (t.properties = this.properties.serialize()), this.height !== void 0 && (t.height = this.height), this.width !== void 0 && (t.width = this.width), this.size !== void 0 && (t.size = this.size), this.duration !== void 0 && (t.duration = this.duration), this.bitrate !== void 0 && (t.bitrate = this.bitrate), this.languages && (t.language = this.languages), this.alternates && (t.alternate = this.alternates.serialize()), this.children && (t.children = this.children.serialize()), t;
  }
  /** MediaType of the linked resource. */
  get mediaType() {
    return this.type !== void 0 ? l.parse({ mediaType: this.type }) : l.BINARY;
  }
  /** Computes an absolute URL to the link, relative to the given `baseURL`.
   *  If the link's `href` is already absolute, the `baseURL` is ignored.
   */
  toURL(t) {
    const e = this.href.replace(/^(\/)/, "");
    if (e.length === 0) return;
    let i = t || "/";
    return i.startsWith("/") && (i = "file://" + i), new URL(e, i).href.replace(/^(file:\/\/)/, "");
  }
  /** List of URI template parameter keys, if the `Link` is templated. */
  get templateParameters() {
    return this.templated ? new Jt(this.href).parameters : /* @__PURE__ */ new Set();
  }
  /** Expands the `Link`'s HREF by replacing URI template variables by the given parameters.
   *  See RFC 6570 on URI template: https://tools.ietf.org/html/rfc6570
   */
  expandTemplate(t) {
    return new Y({
      href: new Jt(this.href).expand(t),
      templated: !1
    });
  }
  /**
   * Makes a copy of this [Link] after merging in the given additional other [properties].
   */
  addProperties(t) {
    const e = Y.deserialize(this.serialize());
    return e.properties = e.properties ? e.properties?.add(t) : new R(t), e;
  }
  /**
   * Creates a [Locator] from a reading order [Link].
   */
  get locator() {
    let t = this.href.split("#");
    return new W({
      href: t.length > 0 && t[0] !== void 0 ? t[0] : this.href,
      type: this.type ?? "",
      title: this.title,
      locations: new C({
        fragments: t.length > 1 && t[1] !== void 0 ? [t[1]] : []
      })
    });
  }
}
class lt {
  /**
   * Creates a [Links].
   */
  constructor(t) {
    this.items = t;
  }
  /**
   * Creates a list of [Link] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (t && Array.isArray(t))
      return new lt(
        t.map((e) => Y.deserialize(e)).filter((e) => e !== void 0)
      );
  }
  /**
   * Serializes an array of [Link] to its RWPM JSON representation.
   */
  serialize() {
    return this.items.map((t) => t.serialize());
  }
  /** Finds the first link with the given relation. */
  findWithRel(t) {
    const e = (i) => i.rels && i.rels.has(t);
    return this.items.find(e);
  }
  /** Finds all the links with the given relation. */
  filterByRel(t) {
    const e = (i) => i.rels && i.rels.has(t);
    return this.items.filter(e);
  }
  /** Finds the first link matching the given HREF. */
  findWithHref(t) {
    const e = (i) => i.href === t;
    return this.items.find(e);
  }
  /** Finds the index of the first link matching the given HREF. */
  findIndexWithHref(t) {
    const e = (i) => i.href === t;
    return this.items.findIndex(e);
  }
  /** Finds the first link matching the given media type. */
  findWithMediaType(t) {
    const e = (i) => i.mediaType.matches(t);
    return this.items.find(e);
  }
  /** Finds all the links matching the given media type. */
  filterByMediaType(t) {
    const e = (i) => i.mediaType.matches(t);
    return this.items.filter(e);
  }
  /** Finds all the links matching any of the given media types. */
  filterByMediaTypes(t) {
    const e = (i) => {
      for (const s of t)
        if (i.mediaType.matches(s))
          return !0;
      return !1;
    };
    return this.items.filter(e);
  }
  /** Returns whether all the resources in the collection are audio clips. */
  everyIsAudio() {
    const t = (e) => e.mediaType.isAudio;
    return this.items.length > 0 && this.items.every(t);
  }
  /** Returns whether all the resources in the collection are bitmaps. */
  everyIsBitmap() {
    const t = (e) => e.mediaType.isBitmap;
    return this.items.length > 0 && this.items.every(t);
  }
  /** Returns whether all the resources in the collection are HTML documents. */
  everyIsHTML() {
    const t = (e) => e.mediaType.isHTML;
    return this.items.length > 0 && this.items.every(t);
  }
  /** Returns whether all the resources in the collection are video clips. */
  everyIsVideo() {
    const t = (e) => e.mediaType.isVideo;
    return this.items.length > 0 && this.items.every(t);
  }
  /** Returns whether all the resources in the collection are matching any of the given media types. */
  everyMatchesMediaType(t) {
    return Array.isArray(t) ? this.items.length > 0 && this.items.every((e) => {
      for (const i of t)
        return e.mediaType.matches(i);
      return !1;
    }) : this.items.length > 0 && this.items.every((e) => e.mediaType.matches(t));
  }
  filterLinksHasType() {
    return this.items.filter((t) => t.type);
  }
}
R.prototype.getContains = function() {
  return new Set(this.otherProperties.contains || []);
};
class ct {
  /**
   * Creates a [DomRange].
   */
  constructor(t) {
    this.cssSelector = t.cssSelector, this.textNodeIndex = t.textNodeIndex, this.charOffset = t.charOffset;
  }
  /**
   * Parses a [DomRangePoint] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!(t && t.cssSelector)) return;
    let e = O(t.textNodeIndex);
    if (e === void 0) return;
    let i = O(t.charOffset);
    return i === void 0 && (i = O(t.offset)), new ct({
      cssSelector: t.cssSelector,
      textNodeIndex: e,
      charOffset: i
    });
  }
  /**
   * Serializes a [DomRangePoint] to its RWPM JSON representation.
   */
  serialize() {
    const t = {
      cssSelector: this.cssSelector,
      textNodeIndex: this.textNodeIndex
    };
    return this.charOffset !== void 0 && (t.charOffset = this.charOffset), t;
  }
}
class It {
  /**
   * Creates a [DomRange].
   */
  constructor(t) {
    this.start = t.start, this.end = t.end;
  }
  /**
   * Parses a [DomRange] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!t) return;
    let e = ct.deserialize(t.start);
    if (e)
      return new It({
        start: e,
        end: ct.deserialize(t.end)
      });
  }
  /**
   * Serializes a [DomRange] to its RWPM JSON representation.
   */
  serialize() {
    const t = { start: this.start.serialize() };
    return this.end && (t.end = this.end.serialize()), t;
  }
}
C.prototype.getCssSelector = function() {
  return this.otherLocations?.get("cssSelector");
};
C.prototype.getPartialCfi = function() {
  return this.otherLocations?.get("partialCfi");
};
C.prototype.getDomRange = function() {
  return It.deserialize(this.otherLocations?.get("domRange"));
};
C.prototype.fragmentParameters = function() {
  return new Map(
    this.fragments.map((r) => r.startsWith("#") ? r.slice(1) : r).join("&").split("&").filter((r) => !r.startsWith("#")).map((r) => r.split("=")).filter((r) => r.length === 2).map((r) => [
      r[0].trim().toLowerCase(),
      r[1].trim()
    ])
  );
};
C.prototype.htmlId = function() {
  if (!this.fragments.length) return;
  let r = this.fragments.find((t) => t.length && !t.includes("="));
  if (!r) {
    const t = this.fragmentParameters();
    t.has("id") ? r = t.get("id") : t.has("name") && (r = t.get("name"));
  }
  return r?.startsWith("#") ? r.slice(1) : r;
};
C.prototype.page = function() {
  const r = parseInt(this.fragmentParameters().get("page"));
  if (!isNaN(r) && r >= 0) return r;
};
C.prototype.time = function() {
  const r = parseInt(this.fragmentParameters().get("t"));
  if (!isNaN(r)) return r;
};
C.prototype.space = function() {
  const r = this.fragmentParameters();
  if (!r.has("xywh")) return;
  const t = r.get("xywh").split(",").map((e) => parseInt(e));
  if (t.length === 4 && !t.some(isNaN))
    return t;
};
class Dt {
  /** Creates a [Price]. */
  constructor(t) {
    this.currency = t.currency, this.value = t.value;
  }
  /**
   * Parses a [Price] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (!t) return;
    let e = t.currency;
    if (!(e && typeof e == "string" && e.length > 0))
      return;
    let i = O(t.value);
    if (i !== void 0)
      return new Dt({ currency: e, value: i });
  }
  /**
   * Serializes a [Price] to its RWPM JSON representation.
   */
  serialize() {
    return { currency: this.currency, value: this.value };
  }
}
class J {
  /** Creates a [Acquisition]. */
  constructor(t) {
    this.type = t.type, this.children = t.children;
  }
  /**
   * Parses a [Acquisition] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (t && t.type)
      return new J({
        type: t.type,
        children: J.deserializeArray(t.children)
      });
  }
  static deserializeArray(t) {
    if (Array.isArray(t))
      return t.map((e) => J.deserialize(e)).filter((e) => e !== void 0);
  }
  /**
   * Serializes a [Acquisition] to its RWPM JSON representation.
   */
  serialize() {
    const t = { type: this.type };
    return this.children && (t.children = this.children.map((e) => e.serialize())), t;
  }
}
class zt {
  /** Creates a [Price]. */
  constructor(t) {
    this.total = t.total, this.position = t.position;
  }
  /**
   * Parses a [Holds] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (t)
      return new zt({
        total: O(t.total),
        position: O(t.position)
      });
  }
  /**
   * Serializes a [Holds] to its RWPM JSON representation.
   */
  serialize() {
    const t = {};
    return this.total !== void 0 && (t.total = this.total), this.position !== void 0 && (t.position = this.position), t;
  }
}
class Mt {
  /** Creates a [Copies]. */
  constructor(t) {
    this.total = t.total, this.available = t.available;
  }
  /**
   * Parses a [Copies] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (t)
      return new Mt({
        total: O(t.total),
        available: O(t.available)
      });
  }
  /**
   * Serializes a [Copies] to its RWPM JSON representation.
   */
  serialize() {
    const t = {};
    return this.total !== void 0 && (t.total = this.total), this.available !== void 0 && (t.available = this.available), t;
  }
}
class kt {
  /** Creates a [Availability]. */
  constructor(t) {
    this.state = t.state, this.since = t.since, this.until = t.until;
  }
  /**
   * Parses a [Availability] from its RWPM JSON representation.
   */
  static deserialize(t) {
    if (t && t.state)
      return new kt({
        state: t.state,
        since: Zt(t.since),
        until: Zt(t.until)
      });
  }
  /**
   * Serializes a [Availability] to its RWPM JSON representation.
   */
  serialize() {
    const t = { state: this.state };
    return this.since !== void 0 && (t.since = this.since.toISOString()), this.until !== void 0 && (t.until = this.until.toISOString()), t;
  }
}
R.prototype.getNumberOfItems = function() {
  return O(this.otherProperties.numberOfItems);
};
R.prototype.getPrice = function() {
  return Dt.deserialize(this.otherProperties.price);
};
R.prototype.getIndirectAcquisitions = function() {
  const r = this.otherProperties.indirectAcquisition;
  if (r && Array.isArray(r))
    return r.map((t) => J.deserialize(t)).filter((t) => t !== void 0);
};
R.prototype.getHolds = function() {
  return zt.deserialize(this.otherProperties.holds);
};
R.prototype.getCopies = function() {
  return Mt.deserialize(this.otherProperties.copies);
};
R.prototype.getAvailability = function() {
  return kt.deserialize(this.otherProperties.availability);
};
R.prototype.getAuthenticate = function() {
  return Y.deserialize(this.otherProperties.authenticate);
};
const Be = "CssSelectorGenerator";
function Qt(r = "unknown problem", ...t) {
  console.warn(`${Be}: ${r}`, ...t);
}
function He(r) {
  return r instanceof RegExp;
}
function _e(r) {
  return r.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".+");
}
function Ve(r) {
  const t = r.map((e) => {
    if (He(e))
      return (i) => e.test(i);
    if (typeof e == "function")
      return (i) => {
        const s = e(i);
        return typeof s != "boolean" ? (Qt("pattern matcher function invalid", "Provided pattern matching function does not return boolean. It's result will be ignored.", e), !1) : s;
      };
    if (typeof e == "string") {
      const i = new RegExp("^" + _e(e) + "$");
      return (s) => i.test(s);
    }
    return Qt("pattern matcher invalid", "Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.", e), () => !1;
  });
  return (e) => t.some((i) => i(e));
}
Ve([
  "class",
  "id",
  // Angular attributes
  "ng-*"
]);
class X {
}
function jt(r) {
  return r.split("").reverse().join("");
}
function Ge(r, t, e) {
  const i = jt(t);
  return e.map((s) => {
    const n = Math.max(0, s.end - t.length - s.errors), o = jt(r.slice(n, s.end));
    return {
      start: be(o, i, s.errors).reduce((d, h) => s.end - h.end < d ? s.end - h.end : d, s.end),
      end: s.end,
      errors: s.errors
    };
  });
}
function ft(r) {
  return (r | -r) >> 31 & 1;
}
function te(r, t, e, i) {
  let s = r.P[e], n = r.M[e];
  const o = i >>> 31, a = t[e] | o, d = a | n, h = (a & s) + s ^ s | a;
  let u = n | ~(h | s), g = s & h;
  const m = ft(u & r.lastRowMask[e]) - ft(g & r.lastRowMask[e]);
  return u <<= 1, g <<= 1, g |= o, u |= ft(i) - o, s = g | ~(d | u), n = u & d, r.P[e] = s, r.M[e] = n, m;
}
function be(r, t, e) {
  if (t.length === 0)
    return [];
  e = Math.min(e, t.length);
  const i = [], s = 32, n = Math.ceil(t.length / s) - 1, o = {
    P: new Uint32Array(n + 1),
    M: new Uint32Array(n + 1),
    lastRowMask: new Uint32Array(n + 1)
  };
  o.lastRowMask.fill(1 << 31), o.lastRowMask[n] = 1 << (t.length - 1) % s;
  const a = new Uint32Array(n + 1), d = /* @__PURE__ */ new Map(), h = [];
  for (let m = 0; m < 256; m++)
    h.push(a);
  for (let m = 0; m < t.length; m += 1) {
    const v = t.charCodeAt(m);
    if (d.has(v))
      continue;
    const f = new Uint32Array(n + 1);
    d.set(v, f), v < h.length && (h[v] = f);
    for (let p = 0; p <= n; p += 1) {
      f[p] = 0;
      for (let b = 0; b < s; b += 1) {
        const x = p * s + b;
        if (x >= t.length)
          continue;
        t.charCodeAt(x) === v && (f[p] |= 1 << b);
      }
    }
  }
  let u = Math.max(0, Math.ceil(e / s) - 1);
  const g = new Uint32Array(n + 1);
  for (let m = 0; m <= u; m += 1)
    g[m] = (m + 1) * s;
  g[n] = t.length;
  for (let m = 0; m <= u; m += 1)
    o.P[m] = -1, o.M[m] = 0;
  for (let m = 0; m < r.length; m += 1) {
    const v = r.charCodeAt(m);
    let f;
    v < h.length ? f = h[v] : (f = d.get(v), typeof f > "u" && (f = a));
    let p = 0;
    for (let b = 0; b <= u; b += 1)
      p = te(o, f, b, p), g[b] += p;
    if (g[u] - p <= e && u < n && (f[u + 1] & 1 || p < 0)) {
      u += 1, o.P[u] = -1, o.M[u] = 0;
      let b;
      if (u === n) {
        const x = t.length % s;
        b = x === 0 ? s : x;
      } else
        b = s;
      g[u] = g[u - 1] + b - p + te(o, f, u, p);
    } else
      for (; u > 0 && g[u] >= e + s; )
        u -= 1;
    u === n && g[u] <= e && (g[u] < e && i.splice(0, i.length), i.push({
      start: -1,
      end: m + 1,
      errors: g[u]
    }), e = g[u]);
  }
  return i;
}
function Fe(r, t, e) {
  const i = be(r, t, e);
  return Ge(r, t, i);
}
function ve(r, t, e) {
  let i = 0;
  const s = [];
  for (; i !== -1; )
    i = r.indexOf(t, i), i !== -1 && (s.push({
      start: i,
      end: i + t.length,
      errors: 0
    }), i += 1);
  return s.length > 0 ? s : Fe(r, t, e);
}
function ee(r, t) {
  return t.length === 0 || r.length === 0 ? 0 : 1 - ve(r, t, t.length)[0].errors / t.length;
}
function $e(r, t, e = {}) {
  if (t.length === 0)
    return null;
  const i = Math.min(256, t.length / 2), s = ve(r, t, i);
  if (s.length === 0)
    return null;
  const n = (a) => {
    const m = 1 - a.errors / t.length, v = e.prefix ? ee(
      r.slice(
        Math.max(0, a.start - e.prefix.length),
        a.start
      ),
      e.prefix
    ) : 1, f = e.suffix ? ee(
      r.slice(a.end, a.end + e.suffix.length),
      e.suffix
    ) : 1;
    let p = 1;
    return typeof e.hint == "number" && (p = 1 - Math.abs(a.start - e.hint) / r.length), (50 * m + 20 * v + 20 * f + 2 * p) / 92;
  }, o = s.map((a) => ({
    start: a.start,
    end: a.end,
    score: n(a)
  }));
  return o.sort((a, d) => d.score - a.score), o[0];
}
function vt(r, t, e) {
  const i = e === 1 ? t : t - 1;
  if (r.charAt(i).trim() !== "")
    return t;
  let s, n;
  if (e === 2 ? (s = r.substring(0, t), n = s.trimEnd()) : (s = r.substring(t), n = s.trimStart()), !n.length)
    return -1;
  const o = s.length - n.length;
  return e === 2 ? t - o : t + o;
}
function ie(r, t) {
  const e = r.commonAncestorContainer.ownerDocument.createNodeIterator(
    r.commonAncestorContainer,
    NodeFilter.SHOW_TEXT
  ), i = t === 1 ? r.startContainer : r.endContainer, s = t === 1 ? r.endContainer : r.startContainer;
  let n = e.nextNode();
  for (; n && n !== i; )
    n = e.nextNode();
  t === 2 && (n = e.previousNode());
  let o = -1;
  const a = () => {
    if (n = t === 1 ? e.nextNode() : e.previousNode(), n) {
      const d = n.textContent, h = t === 1 ? 0 : d.length;
      o = vt(d, h, t);
    }
  };
  for (; n && o === -1 && n !== s; )
    a();
  if (n && o >= 0)
    return { node: n, offset: o };
  throw new RangeError("No text nodes with non-whitespace text found in range");
}
function Ye(r) {
  if (!r.toString().trim().length)
    throw new RangeError("Range contains no non-whitespace text");
  if (r.startContainer.nodeType !== Node.TEXT_NODE)
    throw new RangeError("Range startContainer is not a text node");
  if (r.endContainer.nodeType !== Node.TEXT_NODE)
    throw new RangeError("Range endContainer is not a text node");
  const t = r.cloneRange();
  let e = !1, i = !1;
  const s = {
    start: vt(
      r.startContainer.textContent,
      r.startOffset,
      1
      /* Forwards */
    ),
    end: vt(
      r.endContainer.textContent,
      r.endOffset,
      2
      /* Backwards */
    )
  };
  if (s.start >= 0 && (t.setStart(r.startContainer, s.start), e = !0), s.end > 0 && (t.setEnd(r.endContainer, s.end), i = !0), e && i)
    return t;
  if (!e) {
    const { node: n, offset: o } = ie(
      t,
      1
      /* Forwards */
    );
    n && o >= 0 && t.setStart(n, o);
  }
  if (!i) {
    const { node: n, offset: o } = ie(
      t,
      2
      /* Backwards */
    );
    n && o > 0 && t.setEnd(n, o);
  }
  return t;
}
function we(r) {
  switch (r.nodeType) {
    case Node.ELEMENT_NODE:
    case Node.TEXT_NODE:
      return r.textContent?.length ?? 0;
    default:
      return 0;
  }
}
function se(r) {
  let t = r.previousSibling, e = 0;
  for (; t; )
    e += we(t), t = t.previousSibling;
  return e;
}
function Se(r, ...t) {
  let e = t.shift();
  const i = r.ownerDocument.createNodeIterator(
    r,
    NodeFilter.SHOW_TEXT
  ), s = [];
  let n = i.nextNode(), o, a = 0;
  for (; e !== void 0 && n; )
    o = n, a + o.data.length > e ? (s.push({ node: o, offset: e - a }), e = t.shift()) : (n = i.nextNode(), a += o.data.length);
  for (; e !== void 0 && o && a === e; )
    s.push({ node: o, offset: o.data.length }), e = t.shift();
  if (e !== void 0)
    throw new RangeError("Offset exceeds text length");
  return s;
}
class z {
  constructor(t, e) {
    if (e < 0)
      throw new Error("Offset is invalid");
    this.element = t, this.offset = e;
  }
  /**
   * Return a copy of this position with offset relative to a given ancestor
   * element.
   *
   * @param parent - Ancestor of `this.element`
   */
  relativeTo(t) {
    if (!t.contains(this.element))
      throw new Error("Parent is not an ancestor of current element");
    let e = this.element, i = this.offset;
    for (; e !== t; )
      i += se(e), e = e.parentElement;
    return new z(e, i);
  }
  /**
   * Resolve the position to a specific text node and offset within that node.
   *
   * Throws if `this.offset` exceeds the length of the element's text. In the
   * case where the element has no text and `this.offset` is 0, the `direction`
   * option determines what happens.
   *
   * Offsets at the boundary between two nodes are resolved to the start of the
   * node that begins at the boundary.
   *
   * @param options.direction - Specifies in which direction to search for the
   *                            nearest text node if `this.offset` is `0` and
   *                            `this.element` has no text. If not specified an
   *                            error is thrown.
   *
   * @throws {RangeError}
   */
  resolve(t = {}) {
    try {
      return Se(this.element, this.offset)[0];
    } catch (e) {
      if (this.offset === 0 && t.direction !== void 0) {
        const i = document.createTreeWalker(
          this.element.getRootNode(),
          NodeFilter.SHOW_TEXT
        );
        i.currentNode = this.element;
        const s = t.direction === 1, n = s ? i.nextNode() : i.previousNode();
        if (!n)
          throw e;
        return { node: n, offset: s ? 0 : n.data.length };
      } else
        throw e;
    }
  }
  /**
   * Construct a `TextPosition` that refers to the `offset`th character within
   * `node`.
   */
  static fromCharOffset(t, e) {
    switch (t.nodeType) {
      case Node.TEXT_NODE:
        return z.fromPoint(t, e);
      case Node.ELEMENT_NODE:
        return new z(t, e);
      default:
        throw new Error("Node is not an element or text node");
    }
  }
  /**
   * Construct a `TextPosition` representing the range start or end point (node, offset).
   *
   * @param node
   * @param offset - Offset within the node
   */
  static fromPoint(t, e) {
    switch (t.nodeType) {
      case Node.TEXT_NODE: {
        if (e < 0 || e > t.data.length)
          throw new Error("Text node offset is out of range");
        if (!t.parentElement)
          throw new Error("Text node has no parent");
        const i = se(t) + e;
        return new z(t.parentElement, i);
      }
      case Node.ELEMENT_NODE: {
        if (e < 0 || e > t.childNodes.length)
          throw new Error("Child node offset is out of range");
        let i = 0;
        for (let s = 0; s < e; s++)
          i += we(t.childNodes[s]);
        return new z(t, i);
      }
      default:
        throw new Error("Point is not in an element or text node");
    }
  }
}
class U {
  constructor(t, e) {
    this.start = t, this.end = e;
  }
  /**
   * Create a new TextRange whose `start` and `end` are computed relative to
   * `element`. `element` must be an ancestor of both `start.element` and
   * `end.element`.
   */
  relativeTo(t) {
    return new U(
      this.start.relativeTo(t),
      this.end.relativeTo(t)
    );
  }
  /**
   * Resolve this TextRange to a (DOM) Range.
   *
   * The resulting DOM Range will always start and end in a `Text` node.
   * Hence `TextRange.fromRange(range).toRange()` can be used to "shrink" a
   * range to the text it contains.
   *
   * May throw if the `start` or `end` positions cannot be resolved to a range.
   */
  toRange() {
    let t, e;
    this.start.element === this.end.element && this.start.offset <= this.end.offset ? [t, e] = Se(
      this.start.element,
      this.start.offset,
      this.end.offset
    ) : (t = this.start.resolve({
      direction: 1
      /* FORWARDS */
    }), e = this.end.resolve({
      direction: 2
      /* BACKWARDS */
    }));
    const i = new Range();
    return i.setStart(t.node, t.offset), i.setEnd(e.node, e.offset), i;
  }
  /**
   * Create a TextRange from a (DOM) Range
   */
  static fromRange(t) {
    const e = z.fromPoint(
      t.startContainer,
      t.startOffset
    ), i = z.fromPoint(t.endContainer, t.endOffset);
    return new U(e, i);
  }
  /**
   * Create a TextRange representing the `start`th to `end`th characters in
   * `root`
   */
  static fromOffsets(t, e, i) {
    return new U(
      new z(t, e),
      new z(t, i)
    );
  }
  /**
   * Return a new Range representing `range` trimmed of any leading or trailing
   * whitespace
   */
  static trimmedRange(t) {
    return Ye(U.fromRange(t).toRange());
  }
}
class ht {
  constructor(t, e, i) {
    this.root = t, this.start = e, this.end = i;
  }
  static fromRange(t, e) {
    const i = U.fromRange(e).relativeTo(t);
    return new ht(
      t,
      i.start.offset,
      i.end.offset
    );
  }
  static fromSelector(t, e) {
    return new ht(t, e.start, e.end);
  }
  toSelector() {
    return {
      type: "TextPositionSelector",
      start: this.start,
      end: this.end
    };
  }
  toRange() {
    return U.fromOffsets(this.root, this.start, this.end).toRange();
  }
}
class dt {
  /**
   * @param root - A root element from which to anchor.
   */
  constructor(t, e, i = {}) {
    this.root = t, this.exact = e, this.context = i;
  }
  /**
   * Create a `TextQuoteAnchor` from a range.
   *
   * Will throw if `range` does not contain any text nodes.
   */
  static fromRange(t, e) {
    const i = t.textContent, s = U.fromRange(e).relativeTo(t), n = s.start.offset, o = s.end.offset, a = 32;
    return new dt(t, i.slice(n, o), {
      prefix: i.slice(Math.max(0, n - a), n),
      suffix: i.slice(o, Math.min(i.length, o + a))
    });
  }
  static fromSelector(t, e) {
    const { prefix: i, suffix: s } = e;
    return new dt(t, e.exact, { prefix: i, suffix: s });
  }
  toSelector() {
    return {
      type: "TextQuoteSelector",
      exact: this.exact,
      prefix: this.context.prefix,
      suffix: this.context.suffix
    };
  }
  toRange(t = {}) {
    return this.toPositionAnchor(t).toRange();
  }
  toPositionAnchor(t = {}) {
    const e = this.root.textContent, i = $e(e, this.exact, {
      ...this.context,
      hint: t.hint
    });
    if (!i)
      throw new Error("Quote not found");
    return new ht(this.root, i.start, i.end);
  }
}
function Xe(r) {
  const t = r.tagName.toUpperCase();
  return t === "IMG" || t === "VIDEO" || t === "AUDIO" || t === "IFRAME" || t === "OBJECT" || t === "EMBED" || t === "CANVAS";
}
function pt(r, t) {
  try {
    const e = t.locations, i = t.text;
    if (i && i.highlight) {
      let s;
      e && e.getCssSelector() && (s = r.querySelector(e.getCssSelector())), s || (s = r.body);
      const n = new dt(s, i.highlight, {
        prefix: i.before,
        suffix: i.after
      });
      try {
        return n.toRange();
      } catch {
        return console.warn("Quote not found:", n), null;
      }
    }
    if (e) {
      let s = null;
      if (!s && e.getCssSelector() && (s = r.querySelector(e.getCssSelector())), !s && e.fragments) {
        for (const n of e.fragments)
          if (s = r.getElementById(n), s)
            break;
      }
      if (s) {
        const n = r.createRange();
        return s.childNodes.length === 0 || Xe(s) ? (n.selectNode(s), n) : (n.setStartBefore(s), n.setEndAfter(s), n);
      }
    }
  } catch (e) {
    console.error(e);
  }
  return null;
}
function qe(r, t) {
  let e = r.getClientRects();
  e.length || r.commonAncestorContainer.nodeType === Node.ELEMENT_NODE && (e = r.commonAncestorContainer.getClientRects());
  const i = 1, s = [];
  for (const h of e)
    s.push({
      bottom: h.bottom,
      height: h.height,
      left: h.left,
      right: h.right,
      top: h.top,
      width: h.width
    });
  const n = Ee(
    s,
    i
  ), o = Ze(n, i), a = Ae(o), d = 4;
  for (let h = a.length - 1; h >= 0; h--) {
    const u = a[h];
    if (!(u.width * u.height > d))
      if (a.length > 1)
        a.splice(h, 1);
      else
        break;
  }
  return a;
}
function Ee(r, t, e) {
  for (let i = 0; i < r.length; i++)
    for (let s = i + 1; s < r.length; s++) {
      const n = r[i], o = r[s];
      if (n === o)
        continue;
      const a = I(n.top, o.top, t) && I(n.bottom, o.bottom, t), d = I(n.left, o.left, t) && I(n.right, o.right, t);
      if (a && !d && Ce(n, o, t)) {
        const g = r.filter((v) => v !== n && v !== o), m = Ke(n, o);
        return g.push(m), Ee(
          g,
          t
        );
      }
    }
  return r;
}
function Ke(r, t) {
  const e = Math.min(r.left, t.left), i = Math.max(r.right, t.right), s = Math.min(r.top, t.top), n = Math.max(r.bottom, t.bottom);
  return {
    bottom: n,
    height: n - s,
    left: e,
    right: i,
    top: s,
    width: i - e
  };
}
function Ze(r, t) {
  const e = new Set(r);
  for (const i of r) {
    if (!(i.width > 1 && i.height > 1)) {
      e.delete(i);
      continue;
    }
    for (const n of r)
      if (i !== n && e.has(n) && Je(n, i, t)) {
        e.delete(i);
        break;
      }
  }
  return Array.from(e);
}
function Je(r, t, e) {
  return nt(r, t.left, t.top, e) && nt(r, t.right, t.top, e) && nt(r, t.left, t.bottom, e) && nt(r, t.right, t.bottom, e);
}
function nt(r, t, e, i) {
  return (r.left < t || I(r.left, t, i)) && (r.right > t || I(r.right, t, i)) && (r.top < e || I(r.top, e, i)) && (r.bottom > e || I(r.bottom, e, i));
}
function Ae(r) {
  for (let t = 0; t < r.length; t++)
    for (let e = t + 1; e < r.length; e++) {
      const i = r[t], s = r[e];
      if (i !== s && Ce(i, s, -1)) {
        let n = [], o;
        const a = ne(i, s);
        if (a.length === 1)
          n = a, o = i;
        else {
          const h = ne(s, i);
          a.length < h.length ? (n = a, o = i) : (n = h, o = s);
        }
        const d = r.filter((h) => h !== o);
        return Array.prototype.push.apply(d, n), Ae(d);
      }
    }
  return r;
}
function ne(r, t) {
  const e = Qe(t, r);
  if (e.height === 0 || e.width === 0)
    return [r];
  const i = [];
  {
    const s = {
      bottom: r.bottom,
      height: 0,
      left: r.left,
      right: e.left,
      top: r.top,
      width: 0
    };
    s.width = s.right - s.left, s.height = s.bottom - s.top, s.height !== 0 && s.width !== 0 && i.push(s);
  }
  {
    const s = {
      bottom: e.top,
      height: 0,
      left: e.left,
      right: e.right,
      top: r.top,
      width: 0
    };
    s.width = s.right - s.left, s.height = s.bottom - s.top, s.height !== 0 && s.width !== 0 && i.push(s);
  }
  {
    const s = {
      bottom: r.bottom,
      height: 0,
      left: e.left,
      right: e.right,
      top: e.bottom,
      width: 0
    };
    s.width = s.right - s.left, s.height = s.bottom - s.top, s.height !== 0 && s.width !== 0 && i.push(s);
  }
  {
    const s = {
      bottom: r.bottom,
      height: 0,
      left: e.right,
      right: r.right,
      top: r.top,
      width: 0
    };
    s.width = s.right - s.left, s.height = s.bottom - s.top, s.height !== 0 && s.width !== 0 && i.push(s);
  }
  return i;
}
function Qe(r, t) {
  const e = Math.max(r.left, t.left), i = Math.min(r.right, t.right), s = Math.max(r.top, t.top), n = Math.min(r.bottom, t.bottom);
  return {
    bottom: n,
    height: Math.max(0, n - s),
    left: e,
    right: i,
    top: s,
    width: Math.max(0, i - e)
  };
}
function Ce(r, t, e) {
  return (r.left < t.right || e >= 0 && I(r.left, t.right, e)) && (t.left < r.right || e >= 0 && I(t.left, r.right, e)) && (r.top < t.bottom || e >= 0 && I(r.top, t.bottom, e)) && (t.top < r.bottom || e >= 0 && I(t.top, r.bottom, e));
}
function I(r, t, e) {
  return Math.abs(r - t) <= e;
}
function Wt(r) {
  const t = {}, e = r.document.documentElement.style;
  for (const i in r.document.documentElement.style)
    Object.hasOwn(e, i) && !Number.isNaN(Number.parseInt(i)) && (t[e[i]] = e.getPropertyValue(e[i]));
  return t;
}
function xe(r, t) {
  const e = Wt(r);
  Object.keys(e).forEach((i) => {
    t.hasOwnProperty(i) || mt(r, i);
  }), Object.entries(t).forEach(([i, s]) => {
    e[i] !== s && it(r, i, s);
  });
}
function gt(r, t) {
  return r.document.documentElement.style.getPropertyValue(t);
}
function it(r, t, e) {
  r.document.documentElement.style.setProperty(t, e);
}
function mt(r, t) {
  r.document.documentElement.style.removeProperty(t);
}
let rt = null, yt = null, Z = 0;
const G = { r: 255, g: 255, b: 255, a: 1 }, V = /* @__PURE__ */ new Map(), je = () => {
  if (!rt)
    if (typeof OffscreenCanvas < "u")
      rt = new OffscreenCanvas(5, 5), yt = rt.getContext("2d", {
        willReadFrequently: !0,
        desynchronized: !0
      });
    else {
      const r = document.createElement("canvas");
      r.width = 5, r.height = 5, rt = r, yt = r.getContext("2d", {
        willReadFrequently: !0,
        desynchronized: !0
      });
    }
  return yt;
}, ti = (r) => {
  if (!r) return !0;
  const t = r.trim().toLowerCase();
  return t.startsWith("var(") || [
    "transparent",
    "currentcolor",
    "inherit",
    "initial",
    "revert",
    "unset",
    "revert-layer"
  ].includes(t) ? !0 : [
    "linear-gradient",
    "radial-gradient",
    "conic-gradient",
    "repeating-linear-gradient",
    "repeating-radial-gradient",
    "repeating-conic-gradient"
  ].some((s) => t.includes(s));
}, ot = (r, t) => {
  console.warn(
    `[Decorator] Could not parse color: "${r}". ${t} Falling back to ${JSON.stringify(G)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`
  );
}, wt = (r, t = null) => {
  const e = t ? `${r}|${t}` : r, i = V.get(e);
  if (i !== void 0)
    return i ?? G;
  if (ti(r))
    return ot(r, "Unsupported color format or special value."), V.set(e, null), G;
  const s = je();
  if (!s)
    return ot(r, "Could not get canvas context."), V.set(e, null), G;
  try {
    Z === 0 && s.clearRect(0, 0, 5, 5);
    const n = Z % 5, o = Math.floor(Z / 5);
    s.clearRect(n, o, 1, 1), t && (s.fillStyle = t, s.fillRect(n, o, 1, 1)), s.fillStyle = r, s.fillRect(n, o, 1, 1);
    const a = s.getImageData(n, o, 1, 1);
    Z = (Z + 1) % 25;
    const [d, h, u, g] = a.data;
    if (g === 0)
      return ot(r, "Fully transparent color."), V.set(e, null), G;
    const m = { r: d, g: h, b: u, a: g / 255 };
    return V.set(e, m), m;
  } catch (n) {
    return ot(r, `Error: ${n instanceof Error ? n.message : String(n)}`), V.set(e, null), G;
  }
}, bt = (r) => {
  const t = r / 255;
  return t <= 0.03928 ? t / 12.92 : Math.pow((t + 0.055) / 1.055, 2.4);
}, re = (r) => {
  const t = bt(r.r), e = bt(r.g), i = bt(r.b);
  return 0.2126 * t + 0.7152 * e + 0.0722 * i;
}, oe = (r, t) => {
  const e = typeof r == "string" ? wt(r) : r, i = typeof t == "string" ? wt(t) : t, s = re(e), n = re(i), o = Math.max(s, n), a = Math.min(s, n);
  return (o + 0.05) / (a + 0.05);
}, St = (r, t = null) => {
  const e = wt(r, t), i = oe(e, { r: 255, g: 255, b: 255, a: 1 }), s = oe(e, { r: 0, g: 0, b: 0, a: 1 });
  return i > s;
}, ei = (r, t = null) => St(r, t) ? "white" : "black", ae = "#FFFF00";
var ii = /* @__PURE__ */ ((r) => (r.Wrap = "wrap", r.Viewport = "viewport", r.Bounds = "bounds", r.Page = "page", r))(ii || {}), si = /* @__PURE__ */ ((r) => (r.Boxes = "boxes", r.Bounds = "bounds", r))(si || {});
const ni = () => "Highlight" in window, le = ["IMG", "IMAGE", "AUDIO", "VIDEO", "SVG"];
class ri {
  /**
   * Creates a DecorationGroup object
   * @param id Unique HTML ID-adhering name of the group
   * @param name Human-readable name of the group
   */
  constructor(t, e, i, s) {
    this.wnd = t, this.comms = e, this.id = i, this.name = s, this.items = [], this.lastItemId = 0, this.container = void 0, this.activateable = !1, this.experimentalHighlights = !1, this.currentRender = 0, ni() && (this.experimentalHighlights = !0, this.notTextFlag = /* @__PURE__ */ new Map());
  }
  get activeable() {
    return this.activateable;
  }
  set activeable(t) {
    this.activateable = t;
  }
  /**
   * Adds a new decoration to the group.
   * @param decoration Decoration to add
   */
  add(t) {
    const e = `${this.id}-${this.lastItemId++}`, i = pt(this.wnd.document, t.locator);
    if (!i) {
      this.comms.log("Can't locate DOM range for decoration", t);
      return;
    }
    const s = i.commonAncestorContainer;
    s.nodeType !== Node.TEXT_NODE && this.experimentalHighlights && (le.includes(s.nodeName.toUpperCase()) && this.notTextFlag?.set(e, !0), i.cloneContents().querySelector(le.join(", ").toLowerCase()) && this.notTextFlag?.set(e, !0), (s.textContent?.trim() || "").length === 0 && this.notTextFlag?.set(e, !0));
    const n = {
      decoration: t,
      id: e,
      range: i
    };
    this.items.push(n), this.layout(n), this.renderLayout([n]);
  }
  /**
   * Removes the decoration with given ID from the group.
   * @param identifier ID of item to remove
   */
  remove(t) {
    const e = this.items.findIndex((s) => s.decoration.id === t);
    if (e < 0) return;
    const i = this.items[e];
    this.items.splice(e, 1), i.clickableElements = void 0, i.container && (i.container.remove(), i.container = void 0), this.experimentalHighlights && !this.notTextFlag?.has(i.id) && this.wnd.CSS.highlights.get(this.id)?.delete(i.range), this.notTextFlag?.delete(i.id);
  }
  /**
   * Notifies that the given decoration was modified and needs to be updated.
   * @param decoration Decoration to update
   */
  update(t) {
    this.remove(t.id), this.add(t);
  }
  /**
   * Removes all decorations from this group.
   */
  clear() {
    this.clearContainer(), this.items.length = 0, this.notTextFlag?.clear();
  }
  /**
   * Recreates the decoration elements.
   * To be called after reflowing the resource, for example.
   */
  requestLayout() {
    this.wnd.cancelAnimationFrame(this.currentRender), this.clearContainer(), this.items.forEach((t) => this.layout(t)), this.renderLayout(this.items);
  }
  experimentalLayout(t) {
    const [e, i] = this.requireContainer(!0);
    i.add(t.range);
    const s = gt(this.wnd, "--USER__backgroundColor") || this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color"), n = t.decoration?.style?.tint ?? ae;
    e.innerHTML = `
        ::highlight(${this.id}) {
            color: ${ei(n, s)};
            background-color: ${n};
        }`;
  }
  /**
   * Layouts a single DecorationItem.
   * @param item 
   */
  layout(t) {
    if (this.experimentalHighlights && !this.notTextFlag?.has(t.id))
      return this.experimentalLayout(t);
    const e = this.wnd.document.createElement("div");
    e.setAttribute("id", t.id), e.dataset.highlightId = t.decoration.id, e.style.setProperty("pointer-events", "none");
    const i = this.wnd.innerWidth, s = parseInt(
      getComputedStyle(this.wnd.document.documentElement).getPropertyValue(
        "column-count"
      )
    ), n = i / (s || 1), o = this.wnd.document.scrollingElement, a = o.scrollLeft, d = o.scrollTop, h = (f, p, b) => {
      if (f.style.position = "absolute", t.decoration?.style?.width === "viewport") {
        f.style.width = `${i}px`, f.style.height = `${p.height}px`;
        let x = Math.floor(p.left / i) * i;
        f.style.left = `${x + a}px`, f.style.top = `${p.top + d}px`;
      } else if (t.decoration?.style?.width === "bounds")
        f.style.width = `${b.width}px`, f.style.height = `${p.height}px`, f.style.left = `${b.left + a}px`, f.style.top = `${p.top + d}px`;
      else if (t.decoration?.style?.width === "page") {
        f.style.width = `${n}px`, f.style.height = `${p.height}px`;
        let x = Math.floor(p.left / n) * n;
        f.style.left = `${x + a}px`, f.style.top = `${p.top + d}px`;
      } else
        f.style.width = `${p.width}px`, f.style.height = `${p.height}px`, f.style.left = `${p.left + a}px`, f.style.top = `${p.top + d}px`;
    }, u = t.range.getBoundingClientRect();
    let g = this.wnd.document.createElement("template");
    const m = this.getCurrentDarkMode();
    g.innerHTML = `
        <div
            data-readium="true" 
            class="readium-highlight"
            style="${[
      `background-color: ${t.decoration?.style?.tint ?? ae} !important`,
      //"opacity: 0.3 !important",
      `mix-blend-mode: ${m ? "exclusion" : "multiply"} !important`,
      "opacity: 1 !important",
      "box-sizing: border-box !important"
    ].join("; ")}"
        >
        </div>
        `.trim();
    const v = g.content.firstElementChild;
    if (t.decoration?.style?.layout === "bounds") {
      const f = v.cloneNode(!0);
      f.style.setProperty("pointer-events", "none"), h(f, u, u), e.append(f);
    } else {
      let f = qe(
        t.range
      );
      f = f.sort((p, b) => p.top < b.top ? -1 : p.top > b.top ? 1 : 0);
      for (let p of f) {
        const b = v.cloneNode(!0);
        b.style.setProperty("pointer-events", "none"), h(b, p, u), e.append(b);
      }
    }
    t.container = e, t.clickableElements = Array.from(
      e.querySelectorAll("[data-activable='1']")
    ), t.clickableElements.length || (t.clickableElements = Array.from(e.children));
  }
  renderLayout(t) {
    this.wnd.cancelAnimationFrame(this.currentRender), this.currentRender = this.wnd.requestAnimationFrame(() => {
      if (t = t.filter((i) => !this.experimentalHighlights || !!this.notTextFlag?.has(i.id)), !t || t.length === 0) return;
      this.requireContainer().append(...t.map((i) => i.container).filter((i) => !!i));
    });
  }
  /**
   * Returns the group container element, after making sure it exists.
   * @returns Group's container
   */
  requireContainer(t = !1) {
    if (t) {
      let e;
      this.wnd.document.getElementById(`${this.id}-style`) ? e = this.wnd.document.getElementById(`${this.id}-style`) : (e = this.wnd.document.createElement("style"), e.dataset.readium = "true", e.id = `${this.id}-style`, this.wnd.document.head.appendChild(e));
      let i;
      return this.wnd.CSS.highlights.has(this.id) ? i = this.wnd.CSS.highlights.get(this.id) : (i = new this.wnd.Highlight(), this.wnd.CSS.highlights.set(this.id, i)), [e, i];
    }
    return this.container || (this.container = this.wnd.document.createElement("div"), this.container.setAttribute("id", this.id), this.container.dataset.group = this.name, this.container.dataset.readium = "true", this.container.style.setProperty("pointer-events", "none"), this.container.style.display = "contents", this.wnd.document.body.append(this.container)), this.container;
  }
  getCurrentDarkMode() {
    return gt(this.wnd, "--USER__appearance") === "readium-night-on" || St(gt(this.wnd, "--USER__backgroundColor")) || St(this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color"));
  }
  /**
   * Removes the group container.
   */
  clearContainer() {
    this.experimentalHighlights && this.wnd.CSS.highlights.delete(this.id), this.container && (this.container.remove(), this.container = void 0);
  }
}
const Q = class Q extends X {
  constructor() {
    super(...arguments), this.resizeFrame = 0, this.lastGroupId = 0, this.groups = /* @__PURE__ */ new Map(), this.handleResizer = this.handleResize.bind(this);
  }
  cleanup() {
    this.groups.forEach((t) => t.clear()), this.groups.clear();
  }
  updateHighlightStyles() {
    this.groups.forEach((t) => {
      t.requestLayout();
    });
  }
  extractCustomProperty(t, e) {
    if (!t) return null;
    const i = t.match(new RegExp(`${e}:\\s*([^;]+)`));
    return i ? i[1].trim() : null;
  }
  handleResize() {
    this.wnd.clearTimeout(this.resizeFrame), this.resizeFrame = this.wnd.setTimeout(() => {
      this.groups.forEach((t) => {
        t.experimentalHighlights || t.requestLayout();
      });
    }, 50);
  }
  mount(t, e) {
    return this.wnd = t, e.register("decorate", Q.moduleName, (i, s) => {
      const n = i;
      n.decoration && n.decoration.locator && (n.decoration.locator = W.deserialize(n.decoration.locator)), this.groups.has(n.group) || this.groups.set(n.group, new ri(
        t,
        e,
        `readium-decoration-${this.lastGroupId++}`,
        n.group
      ));
      const o = this.groups.get(n.group);
      switch (n.action) {
        case "add":
          o?.add(n.decoration);
          break;
        case "remove":
          o?.remove(n.decoration.id);
          break;
        case "clear":
          o?.clear();
          break;
        case "update":
          o?.update(n.decoration);
          break;
      }
      s(!0);
    }), this.resizeObserver = new ResizeObserver(() => t.requestAnimationFrame(() => this.handleResize())), this.resizeObserver.observe(t.document.body), t.addEventListener("orientationchange", this.handleResizer), t.addEventListener("resize", this.handleResizer), this.backgroundObserver = new MutationObserver((i) => {
      i.some((n) => {
        if (n.type === "attributes" && n.attributeName === "style") {
          const o = n.target, a = n.oldValue, d = o.getAttribute("style"), h = this.extractCustomProperty(a, "--USER__appearance"), u = this.extractCustomProperty(d, "--USER__appearance"), g = this.extractCustomProperty(a, "--USER__backgroundColor"), m = this.extractCustomProperty(d, "--USER__backgroundColor");
          return h !== u || g !== m;
        }
        return !1;
      }) && this.updateHighlightStyles();
    }), this.backgroundObserver.observe(t.document.documentElement, {
      attributes: !0,
      attributeFilter: ["style"],
      attributeOldValue: !0,
      subtree: !0
    }), e.log("Decorator Mounted"), !0;
  }
  unmount(t, e) {
    return t.removeEventListener("orientationchange", this.handleResizer), t.removeEventListener("resize", this.handleResizer), e.unregisterAll(Q.moduleName), this.resizeObserver.disconnect(), this.backgroundObserver.disconnect(), this.cleanup(), e.log("Decorator Unmounted"), !0;
  }
};
Q.moduleName = "decorator";
let Et = Q;
const ce = "readium-snapper-style", j = class j extends X {
  constructor() {
    super(...arguments), this.protected = !1;
  }
  buildStyles() {
    return `
        html, body {
            touch-action: manipulation;
            user-select: ${this.protected ? "none" : "auto"};
        }`;
  }
  mount(t, e) {
    const i = t.document.createElement("style");
    return i.dataset.readium = "true", i.id = ce, i.textContent = this.buildStyles(), t.document.head.appendChild(i), e.register("protect", j.moduleName, (s, n) => {
      this.protected = !0, i.textContent = this.buildStyles(), n(!0);
    }), e.register("unprotect", j.moduleName, (s, n) => {
      this.protected = !1, i.textContent = this.buildStyles(), n(!0);
    }), e.log("Snapper Mounted"), !0;
  }
  unmount(t, e) {
    return t.document.getElementById(ce)?.remove(), e.log("Snapper Unmounted"), !0;
  }
};
j.moduleName = "snapper";
let st = j;
function B(r) {
  return r.document.body.dir.toLowerCase() === "rtl";
}
function Te(r) {
  return parseInt(
    r.getComputedStyle(
      r.document.documentElement
    ).getPropertyValue("column-count")
  );
}
function he(r) {
  const t = getComputedStyle(r), e = parseFloat(t.paddingTop || "0"), i = parseFloat(t.paddingBottom || "0");
  return r.clientHeight - e - i;
}
function de(r) {
  const t = Te(r);
  if (!t)
    return !1;
  const e = r.document.querySelectorAll("div[id^='readium-virtual-page']");
  for (const h of e)
    h.remove();
  const i = e.length, s = r.document.scrollingElement.scrollWidth, n = r.visualViewport.width, a = Math.round(s / n * t) % t, d = t === 1 || a === 0 ? 0 : t - a;
  if (d > 0)
    for (let h = 0; h < d; h++) {
      const u = r.document.createElement("div");
      u.setAttribute("id", `readium-virtual-page-${h}`), u.dataset.readium = "true", CSS.supports("break-before", "column") ? u.style.breakBefore = "column" : (CSS.supports("break-inside", "avoid-column") && (u.style.breakInside = "avoid-column"), u.style.height = he(r.document.documentElement) + "px"), u.innerHTML = "&#8203;", r.document.body.appendChild(u);
    }
  return i !== d;
}
function Pe(r) {
  const t = r.document.createElement("style");
  t.appendChild(r.document.createTextNode("*{}")), r.document.body.appendChild(t), r.document.body.removeChild(t);
}
function oi(r) {
  return r < 0.5 ? 2 * r * r : -1 + (4 - 2 * r) * r;
}
function A(r) {
  const t = r.getSelection();
  t && t.removeAllRanges();
}
const ai = [
  "a",
  "audio",
  "button",
  "canvas",
  "details",
  "input",
  "label",
  "option",
  "select",
  "submit",
  "textarea",
  "video"
];
function Ne(r) {
  return ai.indexOf(r.nodeName.toLowerCase()) !== -1 || r.hasAttribute("contenteditable") && r.getAttribute("contenteditable")?.toLowerCase() !== "false" ? r : r.parentElement ? Ne(r.parentElement) : null;
}
function Ut(r, t) {
  const e = Le(r, r.document.body, t), i = r._readium_cssSelectorGenerator.getCssSelector(e, {
    selectors: ["tag", "id", "class", "nthchild", "nthoftype", "attribute"]
  });
  return new W({
    href: "#",
    type: "application/xhtml+xml",
    locations: new C({
      otherLocations: /* @__PURE__ */ new Map([
        ["cssSelector", i]
      ])
    }),
    text: new H({
      highlight: e.textContent || void 0
    })
  });
}
function Le(r, t, e) {
  for (var i = 0; i < t.children.length; i++) {
    const s = t.children[i];
    if (!hi(s) && li(r, s, e))
      return ci(r, s) ? s : Le(r, s, e);
  }
  return t;
}
function li(r, t, e) {
  if (t === document.body || t === document.documentElement)
    return !0;
  if (!document || !document.documentElement || !document.body)
    return !1;
  const i = t.getBoundingClientRect();
  return e ? i.bottom > 0 && i.top < r.innerHeight : i.right > 0 && i.left < r.innerWidth;
}
function ci(r, t) {
  const e = t.getBoundingClientRect();
  return e.top >= 0 && e.left >= 0 && e.bottom <= r.innerHeight && e.right <= r.innerWidth;
}
function hi(r) {
  const t = getComputedStyle(r);
  if (t) {
    const e = t.getPropertyValue("display");
    if (e != "block" && e != "list-item" || t.getPropertyValue("opacity") === "0")
      return !0;
  }
  return !1;
}
const di = {
  maxVelocity: 200,
  // Reasonable default for human-like scrolling (pixels/ms)
  minVariance: 0.01,
  // Default variance threshold
  historySize: 20,
  // Balanced history size for performance
  minDirectionChanges: 0.2,
  // Reasonable default for detecting patterns
  maxConsistentScrolls: 15
  // Balanced threshold for flagging
}, Oe = {
  maxVelocity: 200,
  // Extremely fast scrolling (pixels/ms)
  minVariance: 1e-5,
  // Near-perfect consistency
  historySize: 100,
  // Large history window
  minDirectionChanges: 0.1,
  // Only trigger on near-perfect patterns
  maxConsistentScrolls: 20
  // Need many consistent scrolls
}, Re = {
  maxSelectionsPerSecond: 500,
  minVariance: 50,
  historySize: 20
}, ui = {
  enabled: !0,
  maxSelectionPercent: 0.1,
  minThreshold: 100,
  absoluteMaxChars: 5e3,
  historySize: 20
};
class Bt {
  constructor(t = {}) {
    this.history = [], this.consistentScrollCount = 0, this.options = { ...di, ...t };
  }
  analyze(t, e, i) {
    if (i <= 0) return !1;
    const s = Math.abs(e) / i, n = Date.now();
    if (this.history.push({
      timestamp: n,
      direction: t,
      velocity: s,
      distance: Math.abs(e)
    }), this.history = this.history.filter((p) => n - p.timestamp < 2e3).slice(-(this.options.historySize || 20)), this.history.length < 3) return !1;
    if (s > this.options.maxVelocity)
      return this.resetAfterDetection(), !0;
    const o = this.history.map((p) => p.velocity), a = this.history.map((p) => p.distance), d = o.reduce((p, b) => p + b, 0) / o.length, h = a.reduce((p, b) => p + b, 0) / a.length, u = o.reduce((p, b) => p + Math.pow(b - d, 2), 0) / o.length, g = a.reduce((p, b) => p + Math.pow(b - h, 2), 0) / a.length;
    if (u < this.options.minVariance && g < h * 0.1) {
      if (this.consistentScrollCount++, this.consistentScrollCount >= (this.options.maxConsistentScrolls || 10))
        return this.resetAfterDetection(), !0;
    } else
      this.consistentScrollCount = Math.max(0, this.consistentScrollCount - 1);
    let m = 0, v = this.history[0].direction;
    for (let p = 1; p < this.history.length; p++)
      this.history[p].direction !== v && (m++, v = this.history[p].direction);
    return m / this.history.length > (this.options.minDirectionChanges || 0.3) ? (this.resetAfterDetection(), !0) : !1;
  }
  resetAfterDetection() {
    this.history = this.history.slice(-3), this.consistentScrollCount = 0;
  }
  clear() {
    this.history = [], this.consistentScrollCount = 0;
  }
}
const ue = "readium-column-snapper-style", pi = 200, P = class P extends st {
  constructor() {
    super(...arguments), this.isSnapProtectionEnabled = !1, this.patternAnalyzer = null, this.lastTurnTime = 0, this.shakeTimeout = 0, this.snappingCancelled = !1, this.alreadyScrollLeft = 0, this.overscroll = 0, this.cachedScrollWidth = 0, this.touchState = 0, this.startingX = void 0, this.endingX = void 0, this.onTouchStarter = this.onTouchStart.bind(this), this.onTouchEnder = this.onTouchEnd.bind(this), this.onWidthChanger = this.onWidthChange.bind(this), this.onTouchMover = this.onTouchMove.bind(this);
  }
  doc() {
    return this.wnd.document.scrollingElement;
  }
  scrollOffset() {
    return this.doc().scrollLeft > 0 ? this.doc().scrollLeft : this.alreadyScrollLeft;
  }
  snapOffset(t) {
    const e = t + (B(this.wnd) ? -1 : 1);
    return e - e % this.wnd.innerWidth;
  }
  reportProgress() {
    const t = this.wnd.scrollX, e = this.cachedScrollWidth, i = Math.max(0, Math.min(1, t / e)), s = Math.max(0, Math.min(1, (t + this.wnd.innerWidth) / e));
    this.comms.send("progress", {
      start: i,
      end: s
    });
  }
  shake() {
    if (this.overscroll !== 0 || this.shakeTimeout !== 0) return;
    const t = this.doc();
    t.classList.add(B(this.wnd) ? "readium-bounce-l" : "readium-bounce-r");
    const e = this.scrollOffset();
    this.shakeTimeout = this.wnd.setTimeout(() => {
      t.classList.remove("readium-bounce-l"), t.classList.remove("readium-bounce-r"), this.shakeTimeout = 0, this.doc().scrollLeft = e;
    }, 150);
  }
  // We have to cache this because during overscroll (transform, or left) the width is incorrect due to browser
  takeOverSnap() {
    this.snappingCancelled = !0, this.clearTouches();
    const t = this.doc();
    this.overscroll = t.style.transform?.length > 12 ? parseFloat(t.style.transform.slice(12).split("px")[0]) : 0;
  }
  // Snaps the current offset to the page width.
  snapCurrentOffset(t = !1, e = !1) {
    const i = this.wnd.scrollX > 0 ? this.wnd.scrollX : this.alreadyScrollLeft, s = this.doc(), n = this.dragOffset(), o = Te(this.wnd), a = Math.min(Math.max(0, i), this.cachedScrollWidth), d = B(this.wnd) ? -1 : 1, h = (
      // The hurdle to overcome in order to change pages
      d * (this.wnd.innerWidth / 3) * (d * n > 0 ? 2 : 1)
    ), u = this.snapOffset(a + h), g = u > this.scrollOffset() ? "right" : "left";
    if (this.checkSuspiciousSnap(g, Math.abs(u - this.scrollOffset())), t && u !== this.scrollOffset()) {
      this.snappingCancelled = !1;
      const m = (b, x, _, q) => _ > q ? x : b + (x - b) * oi(_ / q), v = (
        /*Math.abs(startX - (this.useTransform ? currentOffset : 0)) < 10 ? 1 : */
        pi * o
      );
      let f;
      const p = (b) => {
        if (this.snappingCancelled) return;
        f || (f = b);
        const x = b - f, _ = m(this.overscroll, 0, x, v), q = m(i, u, x, v);
        s.scrollLeft = q, this.overscroll !== 0 && (s.style.transform = `translate3d(${-_}px, 0px, 0px)`), x < v ? this.wnd.requestAnimationFrame(p) : (this.clearTouches(), s.style.removeProperty("transform"), s.scrollLeft = u, e || this.reportProgress());
      };
      this.wnd.requestAnimationFrame(p);
    } else
      s.style.removeProperty("transform"), this.wnd.requestAnimationFrame(() => {
        s.scrollLeft = u, this.clearTouches(), e || this.reportProgress();
      });
  }
  dragOffset() {
    return (this.startingX ?? 0) - (this.endingX ?? 0);
  }
  clearTouches() {
    this.startingX = void 0, this.endingX = void 0, this.overscroll = 0;
  }
  onTouchStart(t) {
    switch (t.stopPropagation(), this.takeOverSnap(), t.touches.length) {
      case 1:
        break;
      case 2:
        this.onTouchEnd(t);
        return;
      default: {
        this.onTouchEnd(t), this.comms.send("tap_more", t.touches.length);
        return;
      }
    }
    this.startingX = t.touches[0].clientX, this.alreadyScrollLeft = this.doc().scrollLeft, this.touchState = 1;
  }
  onTouchEnd(t) {
    if (this.touchState === 2) {
      const e = this.dragOffset(), i = this.scrollOffset();
      this.cachedScrollWidth <= this.wnd.innerWidth ? (this.reportProgress(), e > 5 && this.comms.send("no_more", void 0), e < -5 && this.comms.send("no_less", void 0)) : i < 5 && e < 5 ? (this.alreadyScrollLeft = 0, this.comms.send("no_less", void 0)) : this.cachedScrollWidth - i - this.wnd.innerWidth < 5 && e > 5 && (this.alreadyScrollLeft = this.cachedScrollWidth, this.comms.send("no_more", void 0)), this.snapCurrentOffset(!0), this.comms.send("swipe", e);
    }
    this.touchState = 0;
  }
  onWidthChange() {
    this.cachedScrollWidth = this.doc().scrollWidth, this.comms.ready && this.snapCurrentOffset();
  }
  onTouchMove(t) {
    if (this.touchState === 0) return;
    this.touchState === 1 && (this.touchState = 2, A(this.wnd)), this.endingX = t.touches[0].clientX;
    const e = this.dragOffset(), i = this.alreadyScrollLeft + e;
    i < 0 ? (this.overscroll = i, this.doc().style.transform = `translate3d(${-this.overscroll}px, 0px, 0px)`) : i + this.wnd.innerWidth > this.cachedScrollWidth ? (this.overscroll = i, this.doc().style.transform = `translate3d(${-i}px, 0px, 0px)`) : (this.overscroll = 0, this.doc().style.removeProperty("transform"), this.doc().scrollLeft = this.alreadyScrollLeft + e);
  }
  enableSnapProtection() {
    this.patternAnalyzer || (this.patternAnalyzer = new Bt({
      maxVelocity: this.wnd.innerWidth,
      // page width
      minVariance: 0.1,
      // Allow for some variation in swipe speed
      historySize: 5,
      // Fewer samples needed for swipe detection
      maxConsistentScrolls: 3,
      // Lower threshold for consistent scrolling
      minDirectionChanges: 0.3
      // Require more direction changes
    }), this.isSnapProtectionEnabled = !0, this.comms?.log("Snap protection enabled"));
  }
  checkSuspiciousSnap(t, e) {
    if (!this.isSnapProtectionEnabled || !this.patternAnalyzer) return;
    const i = Date.now(), s = i - (this.lastTurnTime || i);
    this.lastTurnTime = i, this.patternAnalyzer.analyze(t, e, s) && this.comms?.send("content_protection", {
      type: "suspicious_snapping",
      timestamp: Date.now(),
      event: null
    });
  }
  mount(t, e) {
    if (this.wnd = t, this.comms = e, !super.mount(t, e)) return !1;
    t.navigator.epubReadingSystem && (t.navigator.epubReadingSystem.layoutStyle = "paginated");
    const i = t.document.createElement("style");
    i.dataset.readium = "true", i.id = ue, i.textContent = `
        @keyframes readium-bounce-l-animation {
            0%, 100% {transform: translate3d(0, 0, 0);}
            50% {transform: translate3d(-50px, 0, 0);}
        }

        @keyframes readium-bounce-r-animation {
            0%, 100% {transform: translate3d(0, 0, 0);}
            50% {transform: translate3d(50px, 0, 0);}
        }

        .readium-bounce-l {
            animation: readium-bounce-l-animation 150ms ease-out 1;
        }

        .readium-bounce-r {
            animation: readium-bounce-r-animation 150ms ease-out 1;
        }

        html {
            overflow: hidden;
        }

        body {
            -ms-overflow-style: none; /* for Internet Explorer, Edge */
        }

        * {
            scrollbar-width: none; /* for Firefox */
        }
        
        body::-webkit-scrollbar {
            display: none; /* for Chrome, Safari, and Opera */
        }
        `, t.document.head.appendChild(i), this.resizeObserver = new ResizeObserver(() => {
      t.requestAnimationFrame(() => {
        t && de(t);
      }), this.onWidthChange();
    }), this.resizeObserver.observe(t.document.body), this.mutationObserver = new MutationObserver((n) => {
      for (const o of n)
        if (o.target === this.wnd.document.documentElement) {
          const a = o.oldValue, d = o.target.getAttribute("style"), h = /transform\s*:\s*([^;]+)/, u = a?.match(h), g = d?.match(h);
          (!u && !g || u && !g || u && g && u[1] !== g[1]) && (t.requestAnimationFrame(() => {
            t && de(t);
          }), this.onWidthChange());
        } else
          t.requestAnimationFrame(() => this.cachedScrollWidth = this.doc().scrollWidth);
    }), t.frameElement && this.mutationObserver.observe(t.frameElement, { attributes: !0, attributeFilter: ["style"] }), this.mutationObserver.observe(t.document, { attributes: !0, attributeFilter: ["style"] }), this.mutationObserver.observe(t.document.documentElement, { attributes: !0, attributeFilter: ["style"] }), e.register("scroll_protection", P.moduleName, (n, o) => {
      this.enableSnapProtection(), o(!0);
    });
    const s = (n) => {
      const o = this.doc().scrollLeft;
      return this.doc().scrollLeft = this.snapOffset(n), o !== this.doc().scrollLeft;
    };
    return t.addEventListener("orientationchange", this.onWidthChanger), t.addEventListener("resize", this.onWidthChanger), t.requestAnimationFrame(() => this.cachedScrollWidth = this.doc().scrollWidth), e.register("go_progression", P.moduleName, (n, o) => {
      const a = n;
      if (a < 0 || a > 1) {
        e.send("error", {
          message: "go_progression must be given a position from 0.0 to 1.0"
        }), o(!1);
        return;
      }
      this.wnd.requestAnimationFrame(() => {
        this.cachedScrollWidth = this.doc().scrollWidth;
        const d = this.cachedScrollWidth, h = B(t) ? -1 : 1, u = d * a * h;
        this.doc().scrollLeft = this.snapOffset(u), this.reportProgress(), A(this.wnd), o(!0);
      });
    }), e.register("go_id", P.moduleName, (n, o) => {
      const a = t.document.getElementById(n);
      if (!a) {
        o(!1);
        return;
      }
      this.wnd.requestAnimationFrame(() => {
        this.doc().scrollLeft = this.snapOffset(a.getBoundingClientRect().left + t.scrollX), this.reportProgress(), A(this.wnd), o(!0);
      });
    }), e.register("go_text", P.moduleName, (n, o) => {
      let a;
      Array.isArray(n) && (n.length > 1 && (a = n[1]), n = n[0]);
      const d = H.deserialize(n), h = pt(this.wnd.document, new W({
        href: t.location.href,
        type: "text/html",
        text: d,
        locations: a ? new C({
          otherLocations: /* @__PURE__ */ new Map([
            ["cssSelector", a]
          ])
        }) : void 0
      }));
      if (!h) {
        o(!1);
        return;
      }
      this.wnd.requestAnimationFrame(() => {
        this.doc().scrollLeft = this.snapOffset(h.getBoundingClientRect().left + t.scrollX), this.reportProgress(), A(this.wnd), o(!0);
      });
    }), e.register("go_end", P.moduleName, (n, o) => {
      const a = B(t) ? -1 : 1;
      this.wnd.requestAnimationFrame(() => {
        this.cachedScrollWidth = this.doc().scrollWidth;
        const d = this.cachedScrollWidth * a;
        if (this.doc().scrollLeft === d) return o(!1);
        this.doc().scrollLeft = this.snapOffset(d), this.reportProgress(), A(this.wnd), o(!0);
      });
    }), e.register("go_start", P.moduleName, (n, o) => {
      this.wnd.requestAnimationFrame(() => {
        if (this.doc().scrollLeft === 0) return o(!1);
        this.doc().scrollLeft = 0, this.reportProgress(), A(this.wnd), o(!0);
      });
    }), e.register("go_prev", P.moduleName, (n, o) => {
      this.wnd.requestAnimationFrame(() => {
        this.cachedScrollWidth = this.doc().scrollWidth;
        const a = t.scrollX - t.innerWidth, d = B(t) ? -(this.cachedScrollWidth - t.innerWidth) : 0, h = s(Math.max(a, d));
        h && (this.reportProgress(), A(this.wnd), this.checkSuspiciousSnap("left", this.wnd.innerWidth)), o(h);
      });
    }), e.register("go_next", P.moduleName, (n, o) => {
      this.wnd.requestAnimationFrame(() => {
        this.cachedScrollWidth = this.doc().scrollWidth;
        const a = t.scrollX + t.innerWidth, d = B(t) ? 0 : this.cachedScrollWidth - t.innerWidth, h = s(Math.min(a, d));
        h && (this.reportProgress(), A(this.wnd), this.checkSuspiciousSnap("right", this.wnd.innerWidth)), o(h);
      });
    }), e.register("unfocus", P.moduleName, (n, o) => {
      this.snappingCancelled = !0, A(this.wnd), o(!0);
    }), e.register("shake", P.moduleName, (n, o) => {
      this.shake(), o(!0);
    }), e.register("focus", P.moduleName, (n, o) => {
      this.wnd.requestAnimationFrame(() => {
        this.cachedScrollWidth = this.doc().scrollWidth, this.snapCurrentOffset(!1, !0), this.reportProgress(), o(!0);
      });
    }), e.register("first_visible_locator", P.moduleName, (n, o) => {
      const a = Ut(t, !1);
      this.comms.send("first_visible_locator", a.serialize()), o(!0);
    }), t.addEventListener("touchstart", this.onTouchStarter, { passive: !0 }), t.addEventListener("touchend", this.onTouchEnder, { passive: !0 }), t.addEventListener("touchmove", this.onTouchMover, { passive: !0 }), t.document.addEventListener("touchstart", () => {
    }), e.log("ColumnSnapper Mounted"), !0;
  }
  unmount(t, e) {
    return this.snappingCancelled = !0, e.unregisterAll(P.moduleName), this.resizeObserver.disconnect(), this.mutationObserver.disconnect(), this.patternAnalyzer && (this.patternAnalyzer.clear(), this.patternAnalyzer = null, this.isSnapProtectionEnabled = !1), t.removeEventListener("touchstart", this.onTouchStarter), t.removeEventListener("touchend", this.onTouchEnder), t.removeEventListener("touchmove", this.onTouchMover), t.removeEventListener("orientationchange", this.onWidthChanger), t.removeEventListener("resize", this.onWidthChanger), t.document.getElementById(ue)?.remove(), e.log("ColumnSnapper Unmounted"), super.unmount(t, e);
  }
};
P.moduleName = "column_snapper";
let At = P;
const pe = "readium-scroll-snapper-style", N = class N extends st {
  constructor() {
    super(...arguments), this.patternAnalyzer = null, this.lastScrollTime = 0, this.isScrollProtectionEnabled = !1, this.initialScrollHandled = !1, this.isScrolling = !1, this.lastScrollTop = 0, this.isResizing = !1, this.resizeDebounce = null, this.handleScroll = (t) => {
      if (this.comms.ready && !this.isResizing) {
        if (!this.initialScrollHandled) {
          this.lastScrollTop = this.doc().scrollTop, this.initialScrollHandled = !0, this.reportProgress();
          return;
        }
        this.isScrolling || (this.isScrolling = !0, this.wnd.requestAnimationFrame(() => {
          this.reportProgress();
          const e = this.doc().scrollTop, i = e - this.lastScrollTop;
          if (this.lastScrollTop = e, this.isScrollProtectionEnabled && Math.abs(i) > 5) {
            const s = Date.now(), n = s - (this.lastScrollTime || s);
            if (this.patternAnalyzer && this.patternAnalyzer.analyze(
              i > 0 ? "down" : "up",
              Math.abs(i),
              n
            )) {
              const a = t.target && "tagName" in t.target ? { tagName: t.target.tagName } : null;
              this.comms?.send("content_protection", {
                type: "suspicious_scrolling",
                timestamp: Date.now(),
                scrollDelta: i,
                scrollDirection: i > 0 ? "down" : "up",
                targetElement: a
              });
            }
            this.lastScrollTime = s;
          }
          this.comms.send("scroll", i), this.isScrolling = !1;
        }));
      }
    };
  }
  doc() {
    return this.wnd.document.scrollingElement;
  }
  reportProgress() {
    if (!this.comms.ready) return;
    const t = Math.ceil(this.doc().scrollTop), e = this.doc().scrollHeight, i = this.wnd.innerHeight, s = Math.max(0, Math.min(1, t / e)), n = Math.max(0, Math.min(1, (t + i) / e));
    this.comms.send("progress", {
      start: s,
      end: n
    });
  }
  enableScrollProtection() {
    this.patternAnalyzer || (this.patternAnalyzer = new Bt(Oe), this.isScrollProtectionEnabled = !0, this.comms?.log("Scroll protection enabled"));
  }
  mount(t, e) {
    this.wnd = t, this.comms = e, this.initialScrollHandled = !1, this.lastScrollTop = 0, this.isResizing = !1, this.resizeDebounce && (this.wnd.clearTimeout(this.resizeDebounce), this.resizeDebounce = null), t.navigator.epubReadingSystem && (t.navigator.epubReadingSystem.layoutStyle = "scrolling");
    const i = t.document.createElement("style");
    return i.dataset.readium = "true", i.id = pe, i.textContent = `
        * {
            scrollbar-width: none; /* for Firefox */
        }
        
        body::-webkit-scrollbar {
            display: none; /* for Chrome, Safari, and Opera */
        }
        `, t.document.head.appendChild(i), this.resizeObserver = new ResizeObserver(() => {
      this.resizeDebounce && this.wnd.clearTimeout(this.resizeDebounce), this.isResizing = !0, this.resizeDebounce = this.wnd.setTimeout(() => {
        this.isResizing = !1, this.resizeDebounce = null, this.reportProgress();
      }, 50);
    }), this.resizeObserver.observe(t.document.body), t.addEventListener("scroll", this.handleScroll, { passive: !0 }), e.register("force_webkit_recalc", N.moduleName, () => {
      Pe(this.wnd);
      const s = this.doc().scrollTop;
      s > 1 ? this.doc().scrollTop = s - 1 : this.doc().scrollTop = s + 1, this.doc().scrollTop = s;
    }), e.register("go_progression", N.moduleName, (s, n) => {
      const o = s;
      if (o < 0 || o > 1) {
        e.send("error", {
          message: "go_progression must be given a position from 0.0 to 1.0"
        }), n(!1);
        return;
      }
      this.wnd.requestAnimationFrame(() => {
        this.doc().scrollTop = this.doc().offsetHeight * o, this.reportProgress(), A(this.wnd), n(!0);
      });
    }), e.register("go_id", N.moduleName, (s, n) => {
      const o = t.document.getElementById(s);
      if (!o) {
        n(!1);
        return;
      }
      this.wnd.requestAnimationFrame(() => {
        this.doc().scrollTop = o.getBoundingClientRect().top + t.scrollY - t.innerHeight / 2, this.reportProgress(), A(this.wnd), n(!0);
      });
    }), e.register("go_text", N.moduleName, (s, n) => {
      let o;
      Array.isArray(s) && (s.length > 1 && (o = s[1]), s = s[0]);
      const a = H.deserialize(s), d = pt(this.wnd.document, new W({
        href: t.location.href,
        type: "text/html",
        text: a,
        locations: o ? new C({
          otherLocations: /* @__PURE__ */ new Map([
            ["cssSelector", o]
          ])
        }) : void 0
      }));
      if (!d) {
        n(!1);
        return;
      }
      this.wnd.requestAnimationFrame(() => {
        this.doc().scrollTop = d.getBoundingClientRect().top + t.scrollY - t.innerHeight / 2, this.reportProgress(), A(this.wnd), n(!0);
      });
    }), e.register("go_start", N.moduleName, (s, n) => {
      if (this.doc().scrollTop === 0) return n(!1);
      this.doc().scrollTop = 0, this.reportProgress(), n(!0);
    }), e.register("go_end", N.moduleName, (s, n) => {
      if (this.doc().scrollTop === this.doc().scrollHeight - this.doc().offsetHeight) return n(!1);
      this.doc().scrollTop = this.doc().scrollHeight - this.doc().offsetHeight, this.reportProgress(), n(!0);
    }), e.register("unfocus", N.moduleName, (s, n) => {
      A(this.wnd), n(!0);
    }), e.register("scroll_protection", N.moduleName, (s, n) => {
      this.enableScrollProtection(), n(!0);
    }), e.register([
      "go_next",
      "go_prev"
    ], N.moduleName, (s, n) => n(!1)), e.register("focus", N.moduleName, (s, n) => {
      this.reportProgress(), n(!0);
    }), e.register("first_visible_locator", N.moduleName, (s, n) => {
      const o = Ut(t, !0);
      this.comms.send("first_visible_locator", o.serialize()), n(!0);
    }), e.log("ScrollSnapper Mounted"), !0;
  }
  unmount(t, e) {
    return e.unregisterAll(N.moduleName), this.resizeObserver.disconnect(), this.handleScroll && t.removeEventListener("scroll", this.handleScroll), t.document.getElementById(pe)?.remove(), this.patternAnalyzer && (this.patternAnalyzer.clear(), this.patternAnalyzer = null, this.isScrollProtectionEnabled = !1), e.log("ScrollSnapper Unmounted"), !0;
  }
};
N.moduleName = "scroll_snapper";
let Ct = N;
const L = class L extends st {
  constructor() {
    super(...arguments), this.patternAnalyzer = null, this.lastScrollTime = 0, this.isScrollProtectionEnabled = !1, this.initialScrollHandled = !1, this.isScrolling = !1, this.lastScrollTop = 0, this.isResizing = !1, this.resizeDebounce = null, this.handleScroll = (t) => {
      if (this.comms.ready && !this.isResizing) {
        if (!this.initialScrollHandled) {
          this.lastScrollTop = this.doc().scrollTop, this.initialScrollHandled = !0, this.reportProgress();
          return;
        }
        this.isScrolling || (this.isScrolling = !0, this.wnd.requestAnimationFrame(() => {
          this.reportProgress();
          const e = this.doc().scrollTop, i = e - this.lastScrollTop;
          if (this.lastScrollTop = e, this.isScrollProtectionEnabled && Math.abs(i) > 5) {
            const s = Date.now(), n = s - (this.lastScrollTime || s);
            if (this.patternAnalyzer && this.patternAnalyzer.analyze(
              i > 0 ? "down" : "up",
              Math.abs(i),
              n
            )) {
              const a = t.target && "tagName" in t.target ? { tagName: t.target.tagName } : null;
              this.comms?.send("content_protection", {
                type: "suspicious_scrolling",
                timestamp: Date.now(),
                scrollDelta: i,
                scrollDirection: i > 0 ? "down" : "up",
                targetElement: a
              });
            }
            this.lastScrollTime = s;
          }
          this.comms.send("scroll", i), this.isScrolling = !1;
        }));
      }
    };
  }
  doc() {
    return this.wnd.document.scrollingElement;
  }
  reportProgress() {
    if (!this.comms.ready) return;
    const t = Math.ceil(this.doc().scrollTop), e = this.doc().scrollHeight, i = this.wnd.innerHeight, s = Math.max(0, Math.min(1, t / e)), n = Math.max(0, Math.min(1, (t + i) / e));
    this.comms.send("progress", {
      start: s,
      end: n
    });
  }
  enableScrollProtection() {
    this.patternAnalyzer || (this.patternAnalyzer = new Bt(Oe), this.isScrollProtectionEnabled = !0, this.comms?.log("Scroll protection enabled"));
  }
  mount(t, e) {
    return this.wnd = t, this.comms = e, this.initialScrollHandled = !1, this.lastScrollTop = 0, this.isResizing = !1, this.resizeDebounce && (this.wnd.clearTimeout(this.resizeDebounce), this.resizeDebounce = null), this.resizeObserver = new ResizeObserver(() => {
      this.resizeDebounce && this.wnd.clearTimeout(this.resizeDebounce), this.isResizing = !0, this.resizeDebounce = this.wnd.setTimeout(() => {
        this.isResizing = !1, this.resizeDebounce = null, this.reportProgress();
      }, 50);
    }), this.resizeObserver.observe(t.document.body), t.addEventListener("scroll", this.handleScroll, { passive: !0 }), e.register("force_webkit_recalc", L.moduleName, () => {
      Pe(this.wnd);
      const i = this.doc().scrollTop;
      i > 1 ? this.doc().scrollTop = i - 1 : this.doc().scrollTop = i + 1, this.doc().scrollTop = i;
    }), e.register("go_progression", L.moduleName, (i, s) => {
      const n = i;
      if (n < 0 || n > 1) {
        e.send("error", {
          message: "go_progression must be given a position from 0.0 to 1.0"
        }), s(!1);
        return;
      }
      this.wnd.requestAnimationFrame(() => {
        this.doc().scrollTop = this.doc().offsetHeight * n, this.reportProgress(), A(this.wnd), s(!0);
      });
    }), e.register("go_id", L.moduleName, (i, s) => {
      const n = t.document.getElementById(i);
      if (!n) {
        s(!1);
        return;
      }
      this.wnd.requestAnimationFrame(() => {
        this.doc().scrollTop = n.getBoundingClientRect().top + t.scrollY - t.innerHeight / 2, this.reportProgress(), A(this.wnd), s(!0);
      });
    }), e.register("go_text", L.moduleName, (i, s) => {
      let n;
      Array.isArray(i) && (i.length > 1 && (n = i[1]), i = i[0]);
      const o = H.deserialize(i), a = pt(this.wnd.document, new W({
        href: t.location.href,
        type: "text/html",
        text: o,
        locations: n ? new C({
          otherLocations: /* @__PURE__ */ new Map([
            ["cssSelector", n]
          ])
        }) : void 0
      }));
      if (!a) {
        s(!1);
        return;
      }
      this.wnd.requestAnimationFrame(() => {
        this.doc().scrollTop = a.getBoundingClientRect().top + t.scrollY - t.innerHeight / 2, this.reportProgress(), A(this.wnd), s(!0);
      });
    }), e.register("go_start", L.moduleName, (i, s) => {
      if (this.doc().scrollTop === 0) return s(!1);
      this.doc().scrollTop = 0, this.reportProgress(), s(!0);
    }), e.register("go_end", L.moduleName, (i, s) => {
      if (this.doc().scrollTop === this.doc().scrollHeight - this.doc().offsetHeight) return s(!1);
      this.doc().scrollTop = this.doc().scrollHeight - this.doc().offsetHeight, this.reportProgress(), s(!0);
    }), e.register("unfocus", L.moduleName, (i, s) => {
      A(this.wnd), s(!0);
    }), e.register("scroll_protection", L.moduleName, (i, s) => {
      this.enableScrollProtection(), s(!0);
    }), e.register([
      "go_next",
      "go_prev"
    ], L.moduleName, (i, s) => s(!1)), e.register("focus", L.moduleName, (i, s) => {
      this.reportProgress(), s(!0);
    }), e.register("first_visible_locator", L.moduleName, (i, s) => {
      const n = Ut(t, !0);
      e.send("first_visible_locator", n.serialize()), s(!0);
    }), e.log("WebPubSnapper Mounted"), !0;
  }
  unmount(t, e) {
    return e.unregisterAll(L.moduleName), this.resizeObserver.disconnect(), this.handleScroll && t.removeEventListener("scroll", this.handleScroll), this.patternAnalyzer && (this.patternAnalyzer.clear(), this.patternAnalyzer = null, this.isScrollProtectionEnabled = !1), e.log("WebPubSnapper Unmounted"), !0;
  }
};
L.moduleName = "webpub_snapper";
let xt = L;
class mi {
  constructor(t, e) {
    this.window = t, this.copyHistory = [], this.lastSelectionLength = 0, this.lastSelectionTime = 0, this.options = e;
  }
  cleanupOldHistory(t) {
    this.copyHistory = this.copyHistory.filter(
      (i) => t - i.timestamp < 1e4
    ), this.copyHistory.length > this.options.historySize && (this.copyHistory = this.copyHistory.slice(-this.options.historySize));
  }
  isSuspiciousPattern(t) {
    return this.copyHistory.length < 3 ? !1 : this.copyHistory.filter(
      (s) => t - s.timestamp < 2e3
      // Last 2 seconds
    ).length >= 3 ? !0 : this.copyHistory.slice().sort((s, n) => s.timestamp - n.timestamp).every((s, n, o) => n === 0 ? !0 : s.length > o[n - 1].length * 1.5);
  }
  shouldAllowCopy(t) {
    if (!this.options.enabled) return !0;
    const e = this.window.getSelection();
    if (!e) return !0;
    const s = e.toString().length, n = this.window.document.body.innerText.length, o = Date.now();
    if (this.cleanupOldHistory(o), s < this.options.minThreshold)
      return this.copyHistory.push({
        timestamp: o,
        length: s,
        wasBlocked: !1
      }), !0;
    const d = o - this.lastSelectionTime < 100 && s > this.lastSelectionLength * 1.5, h = Math.min(
      n * this.options.maxSelectionPercent,
      this.options.absoluteMaxChars
    ), u = this.isSuspiciousPattern(o), g = s > h || d || u;
    return this.copyHistory.push({
      timestamp: o,
      length: s,
      wasBlocked: g
    }), g ? (t?.preventDefault(), !1) : (this.lastSelectionLength = s, this.lastSelectionTime = o, !0);
  }
  destroy() {
    this.lastSelectionLength = 0, this.lastSelectionTime = 0, this.copyHistory = [], this.options.enabled = !1;
  }
}
class fi {
  constructor(t = Re) {
    this.options = t, this.events = [], this.selectionStartTime = 0, this.lastSelectionTime = 0, this.lastSelectionPosition = 0, this.selectionPatterns = [], this.lastSelectedText = "";
  }
  analyze(t) {
    if (!t)
      return this.clear(), !1;
    const e = t.toString();
    if (e.length === 0)
      return this.clear(), !1;
    if (t.type !== "Range" || !t.rangeCount)
      return !1;
    const i = Date.now();
    if (e.length <= 50 || e === this.lastSelectedText)
      return !1;
    if (this.selectionStartTime === 0)
      return this.selectionStartTime = i, this.lastSelectedText = e, !1;
    if (i - this.selectionStartTime < 500)
      return !1;
    i - this.lastSelectionTime > 1e3 && (this.lastSelectionTime = i), this.selectionStartTime === 0 && (this.selectionStartTime = i), this.lastSelectedText = e;
    const n = this.analyzeSelectionPattern(t, i);
    return this.cleanup(i), n;
  }
  analyzeSelectionPattern(t, e) {
    if (!t.rangeCount) return !1;
    const i = t.getRangeAt(0), s = i.toString(), n = (e - this.selectionStartTime) / 1e3;
    if (s.length / Math.max(1, n) > this.options.maxSelectionsPerSecond) return !0;
    const a = i.startOffset, d = Math.abs(a - this.lastSelectionPosition);
    return this.selectionPatterns.push(d), this.selectionPatterns.length > this.options.historySize && (this.selectionPatterns.shift(), this.calculateVariance(this.selectionPatterns) < this.options.minVariance) ? !0 : (this.lastSelectionPosition = a, !1);
  }
  calculateVariance(t) {
    if (t.length === 0) return 0;
    const e = t.reduce((i, s) => i + s, 0) / t.length;
    return t.reduce((i, s) => i + Math.pow(s - e, 2), 0) / t.length;
  }
  cleanup(t) {
    this.events = this.events.filter((e) => t - e.timestamp <= 1e3);
  }
  clear() {
    this.events = [], this.selectionStartTime = 0, this.lastSelectionTime = 0, this.lastSelectionPosition = 0, this.selectionPatterns = [], this.lastSelectedText = "";
  }
}
class gi {
  /**
   * Checks if the given keyboard event matches any of the provided key combinations
   */
  match(t, e) {
    for (const i of e) {
      const s = t.keyCode === i.keyCode, n = i.ctrl === void 0 || t.ctrlKey === i.ctrl, o = i.shift === void 0 || t.shiftKey === i.shift, a = i.alt === void 0 || t.altKey === i.alt, d = i.meta === void 0 || t.metaKey === i.meta;
      if (s && n && o && a && d)
        return !0;
    }
    return !1;
  }
  /**
   * Creates an event handler that will call the provided handler when any of the key combinations match
   */
  createKeyHandler(t, e) {
    return (i) => {
      this.match(i, t) && (i.preventDefault(), i.stopPropagation(), e(i));
    };
  }
  /**
   * Creates a standardized activity event for keyboard shortcuts
   */
  createActivityEvent(t, e, i, s) {
    let n;
    if (s) {
      const o = s.getSelection(), a = o?.toString() || "", h = (a && o?.rangeCount ? o.getRangeAt(0)?.getClientRects() : null)?.[0];
      h && a && (n = {
        text: a,
        x: h.x,
        y: h.y,
        width: h.width,
        height: h.height
      });
    }
    return {
      type: e,
      timestamp: Date.now(),
      key: t.key,
      code: t.code,
      keyCode: t.keyCode,
      ctrlKey: t.ctrlKey,
      altKey: t.altKey,
      shiftKey: t.shiftKey,
      metaKey: t.metaKey,
      targetFrameSrc: i,
      selectedText: n
    };
  }
  /**
   * Creates handlers for keyboard shortcuts with centralized activity event dispatch
   */
  createKeyboardHandlers(t, e, i, s) {
    const n = [];
    return e.forEach((o) => {
      n.push(...o.keyCombos.map((a) => ({
        ...a,
        handler: (d) => {
          const h = o.type, u = this.createActivityEvent(d, h, t, s);
          i(u);
        }
      })));
    }), n;
  }
  /**
   * Creates a unified keyboard event handler that processes all shortcuts
   */
  createUnifiedHandler(t, e, i, s) {
    const n = this.createKeyboardHandlers(t, e, i, s);
    return (o) => {
      for (const a of n)
        if (this.match(o, [a])) {
          o.preventDefault(), o.stopPropagation(), a.handler(o);
          return;
        }
    };
  }
}
const $ = class $ extends X {
  constructor() {
    super(...arguments), this.configApplied = !1, this.cleanupCallbacks = [], this.pointerMoved = !1, this.isContextMenuEnabled = !1, this.isDragAndDropEnabled = !1, this.isSelectionMonitoringEnabled = !1, this.isBulkCopyProtectionEnabled = !1, this.selectionAnalyzer = null, this.currentSelection = null, this.bulkCopyProtector = null, this.keyManager = new gi(), this.keyDownHandler = null, this.preventBulkCopy = (t) => {
      if (!this.isBulkCopyProtectionEnabled || !this.bulkCopyProtector)
        return !0;
      if (!this.bulkCopyProtector.shouldAllowCopy(t)) {
        t.preventDefault();
        const e = this.wnd.getSelection(), i = e?.toString() || "", n = (i ? e?.getRangeAt(0)?.getClientRects() : null)?.[0], o = {
          type: "bulk_copy",
          timestamp: Date.now(),
          clipboardTypes: t.clipboardData?.types ? [...t.clipboardData.types] : [],
          selectedText: n ? {
            text: i,
            x: n.x,
            y: n.y,
            width: n.width,
            height: n.height
          } : void 0,
          selectionLength: i.length,
          targetFrameSrc: this.wnd.location.href
        };
        return this.comms?.send("content_protection", o), !1;
      }
      return !0;
    }, this.handleSelection = (t) => {
      if (!this.isSelectionMonitoringEnabled || !this.wnd || !this.selectionAnalyzer)
        return;
      const e = this.wnd.getSelection();
      if (e) {
        if (this.currentSelection = e.toString(), this.selectionAnalyzer.analyze(e) && this.currentSelection) {
          const s = this.wnd.getSelection(), n = s?.toString() || "", a = (n && s?.rangeCount ? s.getRangeAt(0)?.getClientRects() : null)?.[0], d = {
            type: "suspicious_selection",
            timestamp: Date.now(),
            selectionLength: n.length,
            selectedText: {
              text: n,
              x: a?.x ?? 0,
              y: a?.y ?? 0,
              width: a?.width ?? 0,
              height: a?.height ?? 0
            },
            eventType: t?.type || "selectionchange",
            targetFrameSrc: this.wnd.location.href
          };
          this.comms?.send("content_protection", d);
        }
      } else
        this.currentSelection = null;
    }, this.onDragStart = (t) => {
      if (this.isDragAndDropEnabled) {
        t.preventDefault();
        const e = {
          type: "drag_detected",
          timestamp: Date.now(),
          dataTransferTypes: t.dataTransfer?.types ? [...t.dataTransfer.types] : [],
          targetFrameSrc: this.wnd.location.href
        };
        return this.comms?.send("content_protection", e), !1;
      } else
        return !0;
    }, this.onDrop = (t) => {
      if (this.isDragAndDropEnabled) {
        t.preventDefault();
        const e = t.dataTransfer, i = {
          type: "drop_detected",
          timestamp: Date.now(),
          dataTransferTypes: e?.types ? [...e.types] : [],
          fileCount: e?.files?.length || 0,
          targetFrameSrc: this.wnd.location.href
        };
        return this.comms?.send("content_protection", i), !1;
      } else
        return !0;
    }, this.onContext = (t) => {
      if (this.isContextMenuEnabled) {
        t.preventDefault();
        const e = this.wnd.getSelection(), i = e?.toString() || "", n = (i && e?.rangeCount ? e.getRangeAt(0)?.getClientRects() : null)?.[0], o = {
          timestamp: Date.now(),
          clientX: t.clientX,
          clientY: t.clientY,
          ...n && {
            selectedText: {
              text: i,
              x: n.x,
              y: n.y,
              width: n.width,
              height: n.height
            }
          },
          targetFrameSrc: this.wnd.location.href
        };
        this.comms?.send("context_menu", o);
      }
    }, this.onPointerUp = this.onPointUp.bind(this), this.onPointerMove = this.onPointMove.bind(this), this.onPointerDown = this.onPointDown.bind(this), this.onClicker = this.onClick.bind(this);
  }
  addContextMenuPrevention() {
    this.isContextMenuEnabled || !this.wnd || (this.wnd.document.addEventListener("contextmenu", this.onContext), this.isContextMenuEnabled = !0);
  }
  removeContextMenuPrevention() {
    !this.isContextMenuEnabled || !this.wnd || (this.wnd.document.removeEventListener("contextmenu", this.onContext), this.isContextMenuEnabled = !1);
  }
  addDragAndDropPrevention() {
    this.isDragAndDropEnabled || !this.wnd || (this.wnd.document.addEventListener("dragstart", this.onDragStart), this.wnd.document.addEventListener("drop", this.onDrop), this.isDragAndDropEnabled = !0);
  }
  removeDragAndDropPrevention() {
    !this.isDragAndDropEnabled || !this.wnd || (this.wnd.document.removeEventListener("dragstart", this.onDragStart), this.wnd.document.removeEventListener("drop", this.onDrop), this.isDragAndDropEnabled = !1);
  }
  enableKeyboardPeripherals(t = []) {
    this.disableKeyboardPeripherals();
    const e = (i) => {
      this.comms?.send("keyboard_peripherals", i);
    };
    this.keyDownHandler = this.keyManager.createUnifiedHandler(this.wnd.location.href, t, e, this.wnd), this.wnd && this.wnd.document.addEventListener("keydown", this.keyDownHandler, {
      capture: !0
    });
  }
  disableKeyboardPeripherals() {
    this.wnd && this.keyDownHandler && (this.wnd.document.removeEventListener("keydown", this.keyDownHandler, {
      capture: !0
    }), this.keyDownHandler = null);
  }
  addBulkCopyProtection(t = {}) {
    if (this.isBulkCopyProtectionEnabled || !this.wnd) return;
    const e = ui, i = t ? { ...e, ...t } : e;
    this.bulkCopyProtector = new mi(this.wnd, i), this.wnd.document.addEventListener("copy", this.preventBulkCopy, !0), this.wnd.document.addEventListener("cut", this.preventBulkCopy, !0), this.isBulkCopyProtectionEnabled = !0;
  }
  removeBulkCopyProtection() {
    !this.isBulkCopyProtectionEnabled || !this.wnd || (this.wnd.document.removeEventListener("copy", this.preventBulkCopy, !0), this.wnd.document.removeEventListener("cut", this.preventBulkCopy, !0), this.bulkCopyProtector?.destroy(), this.bulkCopyProtector = null, this.isBulkCopyProtectionEnabled = !1);
  }
  addSelectionMonitoring(t) {
    if (this.isSelectionMonitoringEnabled || !this.wnd) return;
    const e = t || Re;
    this.selectionAnalyzer = new fi(e), this.wnd.document.addEventListener("selectionchange", this.handleSelection), this.isSelectionMonitoringEnabled = !0;
  }
  removeSelectionMonitoring() {
    !this.isSelectionMonitoringEnabled || !this.wnd || (this.wnd.document.removeEventListener("selectionchange", this.handleSelection), this.selectionAnalyzer?.clear(), this.selectionAnalyzer = null, this.isSelectionMonitoringEnabled = !1);
  }
  onPointUp(t) {
    const e = this.wnd.getSelection();
    if (e && e.toString()?.length > 0) {
      const s = e.getRangeAt(0)?.getClientRects();
      if (!s || s.length === 0)
        return;
      const n = s[0], o = {
        text: e.toString(),
        x: n.x,
        y: n.y,
        width: n.width,
        height: n.height,
        targetFrameSrc: this.wnd?.location?.href
      };
      this.comms.send("text_selected", o);
    }
    if (this.pointerMoved) {
      this.pointerMoved = !1;
      return;
    }
    if (!e?.isCollapsed || !t.isPrimary) return;
    const i = this.wnd.devicePixelRatio;
    t.preventDefault(), this.comms.send(t.pointerType === "touch" ? "tap" : "click", {
      defaultPrevented: t.defaultPrevented,
      x: t.clientX * i,
      y: t.clientY * i,
      targetFrameSrc: this.wnd.location.href,
      targetElement: t.target.outerHTML,
      interactiveElement: Ne(t.target)?.outerHTML,
      cssSelector: this.wnd._readium_cssSelectorGenerator.getCssSelector(t.target)
    }), this.pointerMoved = !1;
  }
  onPointMove(t) {
    if (t.movementY !== void 0 && t.movementX !== void 0) {
      (Math.abs(t.movementX) > 1 || Math.abs(t.movementY) > 1) && (this.pointerMoved = !0);
      return;
    }
    this.pointerMoved = !0;
  }
  onPointDown() {
    this.pointerMoved = !1;
  }
  onClick(t) {
    if (t.preventDefault(), !t.isTrusted) {
      const e = new PointerEvent("pointerup", {
        isPrimary: !0,
        pointerType: "mouse",
        // Not really a better choice than this
        clientX: t.clientX,
        clientY: t.clientY
      });
      Object.defineProperty(e, "target", { writable: !1, value: t.target }), Object.defineProperty(e, "defaultPrevented", { writable: !1, value: t.defaultPrevented }), this.onPointUp(e);
    }
  }
  registerProtectionHandlers() {
    this.comms?.register("peripherals_protection", $.moduleName, (t, e) => {
      const i = t;
      if (!this.configApplied) {
        if (this.configApplied = !0, i.monitorSelection) {
          const s = typeof i.monitorSelection == "boolean" ? void 0 : i.monitorSelection;
          this.addSelectionMonitoring(s), this.comms?.log("Selection monitoring enabled");
        }
        typeof i.protectCopy == "object" ? (this.addBulkCopyProtection({
          enabled: !0,
          ...i.protectCopy
        }), this.comms?.log("Copy protection enabled (limited)")) : i.protectCopy === !0 && (this.addBulkCopyProtection({
          enabled: !0,
          maxSelectionPercent: 0,
          minThreshold: 0,
          absoluteMaxChars: 0
        }), this.comms?.log("Copy protection enabled")), i.disableContextMenu && (this.addContextMenuPrevention(), this.comms?.log("Context menu protection enabled")), i.disableDragAndDrop && (this.addDragAndDropPrevention(), this.comms?.log("Drag and drop protection enabled"));
      }
      e(!0);
    }), this.comms?.register("keyboard_peripherals", $.moduleName, (t, e) => {
      const i = t;
      i && i.length > 0 && (this.enableKeyboardPeripherals(i), this.comms?.log(`Keyboard peripherals enabled: ${i.map((s) => s.type).join(", ")}`)), e(!0);
    });
  }
  mount(t, e) {
    return this.wnd = t, this.comms = e, this.registerProtectionHandlers(), t.document.addEventListener("pointerdown", this.onPointerDown), t.document.addEventListener("pointerup", this.onPointerUp), t.document.addEventListener("pointermove", this.onPointerMove), t.document.addEventListener("click", this.onClicker), e.log("Peripherals Mounted"), !0;
  }
  unmount(t, e) {
    return this.removeBulkCopyProtection(), this.removeSelectionMonitoring(), this.removeContextMenuPrevention(), this.removeDragAndDropPrevention(), this.disableKeyboardPeripherals(), this.cleanupCallbacks.forEach((i) => i()), this.cleanupCallbacks = [], t.document.removeEventListener("pointerdown", this.onPointerDown), t.document.removeEventListener("pointerup", this.onPointerUp), t.document.removeEventListener("pointermove", this.onPointerMove), t.document.removeEventListener("click", this.onClicker), e.unregisterAll($.moduleName), this.configApplied = !1, e.log("Peripherals Unmounted"), !0;
  }
};
$.moduleName = "peripherals";
let Tt = $;
const tt = class tt extends X {
  constructor() {
    super(...arguments), this.mediaPlayingCount = 0, this.allAnimations = /* @__PURE__ */ new Set();
  }
  wndOnErr(t) {
    this.comms?.send("error", {
      message: t.message,
      filename: t.filename,
      lineno: t.lineno,
      colno: t.colno
    });
  }
  unblock(t) {
    for (t._readium_blockEvents = !1; t._readium_blockedEvents?.length > 0; ) {
      const e = t._readium_blockedEvents.shift();
      switch (e[0]) {
        case 0:
          Reflect.apply(e[1], e[2], e[3]);
          break;
        case 1:
          const i = e[1], s = e[2];
          t.removeEventListener(i.type, t._readium_eventBlocker, !0);
          const n = new Event(i.type, {
            bubbles: i.bubbles,
            cancelable: i.cancelable
          });
          s ? s.dispatchEvent(n) : t.dispatchEvent(n);
          break;
      }
    }
  }
  onMediaPlayEvent() {
    this.mediaPlayingCount++, this.comms?.send("media_play", this.mediaPlayingCount);
  }
  onMediaPauseEvent() {
    this.mediaPlayingCount > 0 && this.mediaPlayingCount--, this.comms?.send("media_pause", this.mediaPlayingCount);
  }
  pauseAllMedia(t) {
    const e = t.document.querySelectorAll("audio,video");
    for (let i = 0; i < e.length; i++)
      e[i].pause();
  }
  mount(t, e) {
    this.comms = e, t.addEventListener(
      "error",
      this.wndOnErr,
      !1
    ), Reflect.defineProperty(t.navigator, "epubReadingSystem", {
      value: {
        name: "readium-ts-toolkit",
        version: "2.3.0",
        hasFeature: (s, n = "") => {
          switch (s) {
            case "dom-manipulation":
              return !0;
            case "layout-changes":
              return !0;
            case "touch-events":
              return !0;
            case "mouse-events":
              return !0;
            case "keyboard-events":
              return !0;
            case "spine-scripting":
              return !0;
            case "embedded-web-content":
              return !0;
            default:
              return !1;
          }
        }
      },
      writable: !1
    }), "getAnimations" in t.document && t.document.getAnimations().forEach((s) => {
      s.cancel(), this.allAnimations.add(s);
    }), e.register("activate", tt.moduleName, (s, n) => {
      this.allAnimations.forEach((o) => {
        o.cancel(), o.play();
      }), n(!0);
    }), e.register("unfocus", tt.moduleName, (s, n) => {
      this.pauseAllMedia(t), this.allAnimations.forEach((o) => o.pause()), n(!0);
    });
    const i = t.document.querySelectorAll("audio,video");
    for (let s = 0; s < i.length; s++) {
      const n = i[s];
      n.addEventListener("play", this.onMediaPlayEvent, {
        passive: !0
      }), n.addEventListener("pause", this.onMediaPauseEvent, {
        passive: !0
      });
    }
    return e.log("Setup Mounted"), !0;
  }
  unmount(t, e) {
    return t.removeEventListener("error", this.wndOnErr), t.removeEventListener("play", this.onMediaPlayEvent), t.removeEventListener("pause", this.onMediaPauseEvent), this.allAnimations.forEach((i) => i.cancel()), this.allAnimations.clear(), e.log("Setup Unmounted"), !0;
  }
};
tt.moduleName = "setup";
let ut = tt;
const me = "readium-viewport", M = class M extends ut {
  onViewportWidthChanged(t) {
    const e = t.target;
    it(e, "--RS__viewportWidth", `${e.innerWidth}px`);
  }
  mount(t, e) {
    if (!super.mount(t, e)) return !1;
    const i = t.document.createElement("meta");
    return i.dataset.readium = "true", i.setAttribute("name", "viewport"), i.setAttribute("id", me), i.setAttribute(
      "content",
      "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"
    ), t.document.head.appendChild(i), t.addEventListener("orientationchange", this.onViewportWidthChanged), t.addEventListener("resize", this.onViewportWidthChanged), this.onViewportWidthChanged({
      target: t
    }), e.register("get_properties", M.moduleName, (s, n) => {
      Wt(t), n(!0);
    }), e.register("update_properties", M.moduleName, (s, n) => {
      s["--RS__viewportWidth"] = `${t.innerWidth}px`, xe(t, s), n(!0);
    }), e.register("set_property", M.moduleName, (s, n) => {
      const o = s;
      it(t, o[0], o[1]), n(!0);
    }), e.register("remove_property", M.moduleName, (s, n) => {
      mt(t, s), n(!0);
    }), e.register("activate", M.moduleName, (s, n) => {
      this.unblock(t), n(!0);
    }), e.log("ReflowableSetup Mounted"), !0;
  }
  unmount(t, e) {
    return e.unregisterAll(M.moduleName), t.document.head.querySelector(`#${me}`)?.remove(), t.removeEventListener("orientationchange", this.onViewportWidthChanged), e.log("ReflowableSetup Unmounted"), super.unmount(t, e);
  }
};
M.moduleName = "reflowable_setup";
let Pt = M;
const fe = "readium-fixed-style", D = class D extends ut {
  mount(t, e) {
    if (!super.mount(t, e)) return !1;
    t.navigator.epubReadingSystem && (t.navigator.epubReadingSystem.layoutStyle = "paginated");
    const i = t.document.createElement("style");
    return i.id = fe, i.dataset.readium = "true", i.textContent = `
        html, body {
            text-size-adjust: none;
            -ms-text-size-adjust: none;
            -webkit-text-size-adjust: none;
            -moz-text-size-adjust: none;

            /* Fight Safari pinches */
            touch-action: none !important;
            min-height: 100%;

            /*cursor: var() TODO*/
        }`, t.document.head.appendChild(i), e.register("set_property", D.moduleName, (s, n) => {
      const o = s;
      it(t, o[0], o[1]), n(!0);
    }), e.register("remove_property", D.moduleName, (s, n) => {
      mt(t, s), n(!0);
    }), e.register("first_visible_locator", D.moduleName, (s, n) => n(!1)), e.register("unfocus", D.moduleName, (s, n) => {
      A(t), n(!0);
    }), e.register([
      "focus",
      "go_next",
      "go_prev",
      "go_id",
      "go_end",
      "go_start",
      "go_text",
      "go_progression"
    ], D.moduleName, (s, n) => n(!0)), e.register("activate", D.moduleName, (s, n) => {
      this.unblock(t), n(!0);
    }), e.log("FixedSetup Mounted"), !0;
  }
  unmount(t, e) {
    return e.unregisterAll(D.moduleName), t.document.getElementById(fe)?.remove(), e.log("FixedSetup Unmounted"), super.unmount(t, e);
  }
};
D.moduleName = "fixed_setup";
let Nt = D;
const k = class k extends X {
  wndOnErr(t) {
    this.comms?.send("error", {
      message: t.message,
      filename: t.filename,
      lineno: t.lineno,
      colno: t.colno
    });
  }
  mount(t, e) {
    return this.comms = e, t.addEventListener(
      "error",
      this.wndOnErr,
      !1
    ), e.register("get_properties", k.moduleName, (i, s) => {
      Wt(t), s(!0);
    }), e.register("update_properties", k.moduleName, (i, s) => {
      xe(t, i), s(!0);
    }), e.register("set_property", k.moduleName, (i, s) => {
      const n = i;
      it(t, n[0], n[1]), s(!0);
    }), e.register("remove_property", k.moduleName, (i, s) => {
      mt(t, i), s(!0);
    }), e.register("activate", k.moduleName, (i, s) => {
      s(!0);
    }), e.log("WebPubSetup Mounted"), !0;
  }
  unmount(t, e) {
    return e.unregisterAll(k.moduleName), t.removeEventListener("error", this.wndOnErr), e.log("WebPubSetup Unmounted"), !0;
  }
};
k.moduleName = "webpub_setup";
let Lt = k;
const et = class et extends X {
  constructor() {
    super(...arguments), this.styleElement = null, this.beforePrintHandler = null, this.configApplied = !1;
  }
  setupPrintProtection(t, e) {
    if (!e.disable) return;
    const i = t.document.createElement("style");
    i.textContent = `
            @media print {
                body * {
                    display: none !important;
                }
                body::after {
                    content: "${e.watermark || "Printing has been disabled"}";
                    font-size: 200%;
                    display: block;
                    text-align: center;
                    margin-top: 50vh;
                    transform: translateY(-50%);
                }
            }
        `, t.document.head.appendChild(i), this.styleElement = i, this.beforePrintHandler = (s) => (s.preventDefault(), !1), t.addEventListener("beforeprint", this.beforePrintHandler);
  }
  registerPrintHandlers() {
    this.comms?.register("print_protection", et.moduleName, (t) => {
      const e = t;
      return this.configApplied || (this.configApplied = !0, this.setupPrintProtection(this.wnd, e), this.comms?.log("Print protection configuration applied")), !0;
    });
  }
  mount(t, e) {
    return this.wnd = t, this.comms = e, this.registerPrintHandlers(), !0;
  }
  unmount(t, e) {
    return this.beforePrintHandler && (t.removeEventListener("beforeprint", this.beforePrintHandler), this.beforePrintHandler = null), this.styleElement?.parentNode && (this.styleElement.parentNode.removeChild(this.styleElement), this.styleElement = null), this.comms?.unregisterAll(et.moduleName), this.configApplied = !1, !0;
  }
};
et.moduleName = "print_protection";
let Ot = et;
const yi = [
  "fixed_setup",
  "decorator",
  "peripherals",
  "print_protection"
], bi = [
  "reflowable_setup",
  "decorator",
  "peripherals",
  "column_snapper",
  "scroll_snapper",
  "print_protection"
], vi = [
  "webpub_setup",
  "webpub_snapper",
  "decorator",
  "peripherals",
  "print_protection"
], ge = new Map([
  // All modules go here
  Nt,
  Pt,
  Lt,
  xt,
  Tt,
  Et,
  At,
  Ct,
  Ot
].map((r) => [r.moduleName, r]));
class wi {
  /**
   * @param wnd Window instance to operate on
   * @param initialModules List of initial modules to load
   */
  constructor(t = window, e = []) {
    this.loadedModules = [], this.wnd = t, this.comms = new ze(t);
    const i = [...new Set(e)];
    if (i.length) {
      if (typeof t > "u")
        throw Error("Loader is not in a web browser");
      t.parent !== t && this.comms.log("Loader is probably in a frame"), this.loadedModules = i.map((s) => {
        const n = this.loadModule(s);
        if (n)
          return n.mount(this.wnd, this.comms), n;
      }).filter((s) => s !== void 0);
    }
  }
  loadModule(t) {
    const e = ge.get(t);
    return e === void 0 ? (this.comms.log(`Module "${name}" does not exist in the library`), e) : new e();
  }
  /**
   * Add a module by name
   * @param moduleName Module name
   * @returns Success
   */
  addModule(t) {
    const e = this.loadModule(t);
    return !e || !e.mount(this.wnd, this.comms) ? !1 : (this.loadedModules.push(e), !0);
  }
  /**
   * Remove a module by name
   * @param moduleName Module name
   * @returns Success
   */
  removeModule(t) {
    const e = ge.get(t);
    if (e === void 0)
      return this.comms.log(`Module "${t}" does not exist in the library`), !1;
    const i = this.loadedModules.findIndex((s) => s instanceof e);
    return i < 0 ? !1 : (this.loadedModules[i].unmount(this.wnd, this.comms), this.loadedModules.splice(i, 1), !0);
  }
  /**
   * Unmount and remove all modules
   */
  destroy() {
    this.comms.destroy(), this.loadedModules.forEach((t) => t.unmount(this.wnd, this.comms)), this.loadedModules = [];
  }
}
const Si = {
  type: "developer_tools",
  keyCombos: [
    { keyCode: 73, meta: !0, alt: !0 },
    // I key
    { keyCode: 74, meta: !0, alt: !0 },
    // J key
    { keyCode: 85, meta: !0, alt: !0 },
    // U key
    { keyCode: 67, meta: !0, alt: !0 },
    // C key
    { keyCode: 67, meta: !0, shift: !0 },
    // C key (Cmd+Shift+C)
    { keyCode: 67, ctrl: !0, shift: !0 },
    // C key (Ctrl+Shift+C)
    { keyCode: 123 },
    // F12
    { keyCode: 123, shift: !0 },
    // F12+Shift
    { keyCode: 123, ctrl: !0, shift: !0 },
    // F12+Ctrl+Shift
    { keyCode: 123, meta: !0, alt: !0 }
    // F12+Meta+Alt
  ]
}, Ei = {
  type: "select_all",
  keyCombos: [
    { keyCode: 65, meta: !0 },
    // A key (Cmd+A)
    { keyCode: 65, ctrl: !0 }
    // A key (Ctrl+A)
  ]
}, Ai = {
  type: "print",
  keyCombos: [
    { keyCode: 80, meta: !0 },
    // P key (Cmd+P)
    { keyCode: 80, ctrl: !0 },
    // P key (Ctrl+P)
    { keyCode: 80, meta: !0, shift: !0 },
    // P key (Cmd+Shift+P)
    { keyCode: 80, ctrl: !0, shift: !0 },
    // P key (Ctrl+Shift+P)
    { keyCode: 80, meta: !0, alt: !0 },
    // P key (Cmd+Alt+P)
    { keyCode: 80, ctrl: !0, alt: !0 }
    // P key (Ctrl+Alt+P)
  ]
}, Ci = {
  type: "save",
  keyCombos: [
    { keyCode: 83, meta: !0 },
    // S key (Cmd+S)
    { keyCode: 83, ctrl: !0 }
    // S key (Ctrl+S)
  ]
};
export {
  mi as BulkCopyProtector,
  K as COMMS_VERSION,
  ze as Comms,
  Si as DEV_TOOLS,
  Et as Decorator,
  yi as FXLModules,
  gi as KeyCombinationManager,
  si as Layout,
  wi as Loader,
  X as Module,
  ge as ModuleLibrary,
  Ai as PRINT,
  Bt as PatternAnalyzer,
  Tt as Peripherals,
  Ot as PrintProtector,
  bi as ReflowableModules,
  Ci as SAVE,
  Ei as SELECT_ALL,
  fi as SelectionAnalyzer,
  vi as WebPubModules,
  ii as Width,
  De as mid
};
